add codeforces solutions folder

This commit is contained in:
2026-03-05 19:55:52 +05:30
parent 77ff815f38
commit e698c35654
20 changed files with 778 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int count = 0;
for(int i = 0; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
if(a + b + c >= 2) {
count++;
}
}
cout << count << endl;
return 0;
}
@@ -0,0 +1,52 @@
class Solution{
public:
char findKthBit(int n, int k){
int invertCount = 0;
int len = (1<<n)-1;
while(k>1){
if(k==len/2+1){
return invertCount % 2==0? '1' : '0';
}
if(k>len/2){
k = len-k+1;
invertCount++;
}
len/=2;
}
return invertCount%2==0?'0':'1';
}
};
//TC: o(n) , SC : o(1)
/*
Approach:
We do NOT build the full string Sn because its length grows exponentially (2^n - 1).
Instead, we use the recursive structure:
Sn = S(n-1) + "1" + reverse(invert(S(n-1)))
For any position k:
1) If k lies in the left half:
→ It directly corresponds to the same position in S(n-1).
2) If k is the middle element:
→ The value is always '1'.
3) If k lies in the right half:
→ The right half is reverse(invert(S(n-1))).
→ Mirror the index into the left half.
→ Remember that the value must be inverted.
We keep reducing the problem from Sn → S(n-1) until we reach
the base case S1 = "0".
The final answer depends on how many times we entered
the right half (i.e., how many inversions occurred).
Time Complexity: O(n)
Space Complexity: O(1) (iterative version)
*/
+17
View File
@@ -0,0 +1,17 @@
class Solution{
public:
char findKthBit(int n, int k){
string seq = "0";
for(int i = 1;i<n && seq.length() < k;++i){
seq+='1';
string temp = seq;
for(int j=temp.length()-2;j>=0;--j){
char invertedBit = (temp[j]=='1')? '0': '1';
seq+=invertedBit;
}
}
return seq[k-1];
}
}
+48
View File
@@ -0,0 +1,48 @@
class Solution{
public:
char findKthBit(int n, int k){
if(n==1) return '0';
int len = 1<<n;
if(k<len/2) {
return findKthBit(n-1,k);
}
else if(k == len/2){
return '1';
}
else{
char correspondingBit = findKthBit(n-1, len-k);
return ((correspondingBit == '0')? '1':'0');
}
}
}
/*
Recursive Idea:
The string is defined as:
Sn = S(n-1) + "1" + reverse(invert(S(n-1)))
Instead of building the full string (which grows exponentially),
we determine where the k-th position lies:
1) If k is in the left half:
→ It directly corresponds to the same position in S(n-1).
→ So recurse: findKthBit(n-1, k)
2) If k is exactly the middle:
→ The middle element is always '1'.
3) If k is in the right half:
→ The right half is reverse(invert(S(n-1))).
→ Mirror the index using (len - k).
→ Recursively find that bit in S(n-1).
→ Invert the result.
Each recursive call reduces n by 1,
tracing the origin of the bit back to the base case S1 = "0".
Time Complexity: O(n)
Space Complexity: O(n) (recursion stack)
*/
// TC: o(n) and SC : o(n)
+32
View File
@@ -0,0 +1,32 @@
class Solution{
public:
int numSpecial(vector<vector<int>> &mat){
int ans = 0;
int r = mat.size();
int c = mat[0].size();
for(int row=0;row<r;row++){
for(int col = 0;col<c;col++){
if(mat[row][col]==0) continue;
bool good = true;
for(int m = 0;m<r;m++){
if(m!=row && mat[m][col] == 1){
good = false;
break;
}
}
for(int n = 0;n<c;n++){
if(n!=col && mat[row][n] == 1){
good = false;
break;
}
}
if(good) ans++;
}
}
return ans;
}
};
//TC : o(r.c(r+c)) SC: o(1)
+31
View File
@@ -0,0 +1,31 @@
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<int> rowCount(m, 0);
vector<int> colCount(n, 0);
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (mat[row][col] == 1) {
rowCount[row]++;
colCount[col]++;
}
}
}
int ans = 0;
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (mat[row][col] == 1) {
if (rowCount[row] == 1 && colCount[col] == 1) {
ans++;
}
}
}
}
return ans;
}
};
+48
View File
@@ -0,0 +1,48 @@
class Solution{
public:
int numSpecial(vector<vector<int>> &mat){
int ans = 0;
int m = mat.size();
int n = mat[0].size();
for(int row = 0;row<m;row++){
int colIndex = -1;
int count = 0;
for(int col = 0;col<n;col++){
if(mat[row][col]==1){
count++;
colIndex = col;
}
}
if(count==1){
bool good = true;
for(int r=0;r<m;r++){
if(r!=row && mat[r][colIndex]==1) {
good = false;
break;
}
}
if(good) ans++;
}
}
return ans;
}
};
/*
Approach:
We iterate through each row of the matrix and count how many 1s appear in that row.
While scanning the row, we also record the column index where the 1 occurs. If a row
contains exactly one 1, it becomes a candidate for a special position. For that candidate,
we then check the entire column corresponding to that 1 to ensure no other row contains a 1
in the same column. If the column also has exactly one 1 (the current position), then that
position satisfies both conditions and we increment the answer. After checking all rows,
the total number of such positions is returned.
Time Complexity: O(mn + m²) in the worst case. We scan each row once (mn work), and for
rows that contain exactly one 1 we scan the column (up to m operations). In practice this
is usually closer to O(mn).
Space Complexity: O(1)
*/
+17
View File
@@ -0,0 +1,17 @@
class Solution{
public:
int minPartitions(string n){
int ans = 0;
for(char& c : n){
ans = max(ans, c-'0');
if(ans==9) break;
}
return ans;
}
};
//TC: o(n), SC : o(1)
//My first greedy problem.The greedy approach works because each deci-binary number can contribute at most 1 to any digit position, so if a digit in the number is d, we need at least d deci-binary numbers to build that column. This makes the maximum digit in the string the tightest constraint (bottleneck). Since we cannot use fewer than that many numbers and we can always construct exactly that many layers to form the number, the answer is simply the maximum digit. We make one optimal local decision (take the largest digit) and it directly gives the globally optimal solution, which is why this is a greedy approach.
//For c - '0', characters in C++ are stored using ASCII values, where '0' is 48, '1' is 49, up to '9' as 57. When you subtract '0' from a digit character like '7', both characters are implicitly promoted to integers, so the operation becomes 55 - 48 = 7, giving the numeric value of the digit. This works because '0' is a single character. However, "0" is a string literal (a pointer to a character array), not a character, so it cannot be used in arithmetic like this. c-"0"[0] would work tho.
+25
View File
@@ -0,0 +1,25 @@
class Solution{
public:
int minOperations(string s){
int start0=0,start1=0;
for(int i =0;i<s.size();i++){
if(i%2==0){
if(s[i]=='1') start0++;
else start1++;
}
else{
if(s[i]=='1') start1++;
else start0++;
}
}
return min(start0, start1);
}
}
//TC: o(n), SC: o(1)
//It has a brute force approach where we construct both 0-start-alternating and 1-start-alternating string and count differences for each, compared to the string s, and return min of the count of differences. It takes o(n) space complexity
//here the core idea is that a binary string can be alternating in only two possible patterns: one starting with 0 (010101...) and the other starting with 1 (101010...). The algorithm scans the string once and counts how many characters do not match each of these patterns. For every index, it checks whether the character fits the expected value for both cases (start with 0 and start with 1) and increments the corresponding counter when there is a mismatch, which represents a flip operation. By the end of the loop, we know the number of flips required to convert the string into each alternating pattern, and the minimum of these two counts gives the minimum operations needed.
+18
View File
@@ -0,0 +1,18 @@
class Solution{
public:
int hammingWeight(int n){
int res= 0;
/*for(int i = 0;i<32;i++){
if(n>>i && 1) res ++;
}*/
//brian-kernighan's algo
while(n){
n = n&(n-1);
res++
}
return res;
}
};
//n&n-1 resets the last set bit to 0, brian's algo takes o(number of set bits to run) unlike brute force which takes o(total no. of bits). both are o(1).
+11
View File
@@ -0,0 +1,11 @@
class Solution{
public :
void deleteNode(ListNode* node){
ListNode* nextNode = node->next;
node->val = nextNode->val;
node->next = nextNode->next;
delete nextNode;
}
}
//The idea behind this solution is that since we are not given the head pointer and therefore cannot access the previous node, we cannot delete the current node in the normal way (which would require updating prev->next). So instead of deleting the given node directly, we copy the value of its next node into it. This makes the current node effectively take on the identity of the next node. Then we adjust the current nodes next pointer to skip over the next node, thereby removing it from the list. Finally, we delete that next node to free memory. This works because the problem guarantees that the given node is not the tail, so a next node always exists.
+45
View File
@@ -0,0 +1,45 @@
class Solution{
public:
int search(vector<int> nums, int target){
int start = 0, end = nums.size() - 1;
while(left<=right){
int mid = start + (end - start)/2;
if(nums[mid]==target) return mid;
if(nums[start]<=nums[mid]){
if(target>=nums[start] && target< nums[mid])
end = mid-1
else
start = mid+1;
}
else{
if(target>nums[mid] && target<= nums[end])
start = mid+1;
else
end = mid-1;
}
return -1;
}
};
//TC : o(logn), SC: o(1)
/*
Approach:
This is a modified binary search for a rotated sorted array.
The array was originally sorted in ascending order and then rotated once,
which means there is exactly one pivot point. Because of this, at any
given mid index, at least one half (left or right) must still be sorted.
At each step:
1) Find the middle index.
2) Determine which half is sorted.
3) Check if the target lies within the sorted half.
- If yes, move the search to that half.
- If no, move to the other half.
By always eliminating half of the array, we maintain
O(log n) time complexity without explicitly finding the pivot.
*/
+20
View File
@@ -0,0 +1,20 @@
class Solution{
public:
int searchInsert(vector<int>&nums, int target){
int start = 0, end = nums.size() -1;
while(start<=end){
int mid = left+(right-left)/2;
if(nums[mid]==target) return mid;
if(target<nums[mid]){
end = mid -1;
}
else{
start = mid+1;
}
}
return start;
}
};
+14
View File
@@ -0,0 +1,14 @@
class Solution{
public :
vector<string> readBinaryWatch(int turned On){
vector<string> ans;
for(int i =0;i<1024;i++){
int h = i>>6, m = i & 63;
if(h<12 && m<60 && __builtin_popcount(i) == turnedOn)
ans.push_back(to_string(h)+":"+(m<10?"0":"")+to_string(m));
}
return ans;
}
}
//TC : o(1) as total number of enumerations will be independent of input size
//SC : o(1)
+14
View File
@@ -0,0 +1,14 @@
class Solution{
public :
vector<string> readBinaryWatch(int turnedOn){
vector<string> ans;
for(int h=0;h<12;++h){
for(int m = 0;m<60;++m){
if(__builtin_popcount(h)+ __builtin_popcount(m) == turnedOn){
ans.push_back(to_string(h)+":"+(m<10?"0":"")+to_string(m));
}
}
}
return ans;
}
}
+291
View File
@@ -0,0 +1,291 @@
# C++ Bit Manipulation Reference
This document contains:
- GCC / Clang built-in bit functions
- C++20 `<bit>` header utilities
- C++23 additions
---
# Part 1 — GCC / Clang Built-in Bit Functions
These are compiler-specific (GCC / Clang).
They are fast (usually O(1)) and often map to CPU instructions.
---
## 1. `__builtin_popcount`
Counts number of set bits (1s).
### Variants
```cpp
__builtin_popcount(x) // → int
__builtin_popcountl(x) // → long
__builtin_popcountll(x) // → long long
```
### Example
```cpp
int x = 13; // 1101
int cnt = __builtin_popcount(x); // 3
```
---
## 2. `__builtin_clz`
Count Leading Zeros (from MSB).
### Variants
```cpp
__builtin_clz(x)
__builtin_clzl(x)
__builtin_clzll(x)
```
### Example
```cpp
int x = 8; // 000...1000
int zeros = __builtin_clz(x); // 28 (32-bit int)
```
### Notes
> ⚠️ Undefined if `x == 0`
```cpp
// Highest set bit index:
int highest = 31 - __builtin_clz(x);
```
---
## 3. `__builtin_ctz`
Count Trailing Zeros (from LSB).
### Variants
```cpp
__builtin_ctz(x)
__builtin_ctzl(x)
__builtin_ctzll(x)
```
### Example
```cpp
int x = 8; // 1000
int zeros = __builtin_ctz(x); // 3
```
> ⚠️ Undefined if `x == 0`
---
## 4. `__builtin_parity`
Returns `1` if odd number of set bits, `0` if even.
```cpp
int x = 7; // 111
int p = __builtin_parity(x); // 1
```
---
## 5. `__builtin_ffs`
Find First Set Bit (1-indexed from right). Returns `0` if input is `0`.
```cpp
int x = 10; // 1010
int pos = __builtin_ffs(x); // 2
```
---
# Part 2 — C++20 `<bit>` Header (Portable Standard)
```cpp
#include <bit>
```
> Works on **unsigned integer types** only.
---
## 1. `std::popcount`
Counts number of set bits.
```cpp
std::popcount(x);
```
---
## 2. `std::countl_zero`
Count leading zeros. Safe for `x == 0` (returns bit width).
```cpp
std::countl_zero(x);
```
---
## 3. `std::countl_one`
Count consecutive leading ones.
```cpp
std::countl_one(x);
```
---
## 4. `std::countr_zero`
Count trailing zeros. Safe for `x == 0` (returns bit width).
```cpp
std::countr_zero(x);
```
---
## 5. `std::countr_one`
Count consecutive trailing ones.
```cpp
std::countr_one(x);
```
---
## 6. `std::has_single_bit`
Returns `true` if exactly one bit is set (i.e., power of 2).
```cpp
std::has_single_bit(x);
// Equivalent to:
x > 0 && (x & (x - 1)) == 0;
```
---
## 7. `std::bit_width`
Number of bits required to represent `x`.
```cpp
std::bit_width(x);
// Equivalent to (for x > 0):
floor(log2(x)) + 1;
```
---
## 8. `std::bit_floor`
Largest power of 2 ≤ `x`.
```cpp
std::bit_floor(x);
// Example:
std::bit_floor(10); // → 8
```
---
## 9. `std::bit_ceil`
Smallest power of 2 ≥ `x`.
```cpp
std::bit_ceil(x);
// Example:
std::bit_ceil(10); // → 16
```
---
## 10. `std::rotl` — Rotate Left
Circular left rotation.
```cpp
std::rotl(x, s);
```
---
## 11. `std::rotr` — Rotate Right
Circular right rotation.
```cpp
std::rotr(x, s);
```
---
# Part 3 — C++23 Additions
---
## 1. `std::byteswap`
Swap byte order (endianness conversion).
```cpp
std::byteswap(x);
// Example:
// 0x12345678 → 0x78563412
```
---
## 2. `std::endian`
Detect system byte order.
```cpp
#include <bit>
if (std::endian::native == std::endian::little) {
// little-endian system
}
```
# Applications
A number of the form 1 << k has a one bit in position k and all other bits are zero,
so we can use such numbers to access single bits of numbers. In particular, the
kth bit of a number is one exactly when x & (1 << k) is not zero. The following
code prints the bit representation of an int number x:
```
for (int i = 31; i >= 0; i--) {
if (x&(1<<i)) cout << "1";
else cout << "0";
}
```
It is also possible to modify single bits of numbers using similar ideas. For
example, the formula x | (1 << k) sets the kth bit of x to one, the formula x &
~(1 << k) sets the kth bit of x to zero, and the formula x ^ (1 << k) inverts the
kth bit of x.
The formula x & (x 1) sets the last one bit of x to zero, and the formula x &
x sets all the one bits to zero, except for the last one bit. The formula x | (x 1)
inverts all the bits after the last one bit. Also note that a positive number x is a
power of two exactly when x & (x 1) = 0.
+15
View File
@@ -0,0 +1,15 @@
class Solution{
public :
bool hasAlternatingBits(int n){
bool cur = n%2;
n/=2;
while(n){
if(n%2 == cur) return false;
cur = n%2;
n/=2;
}
return true;
}
};
// n%2 extracts the last bit and n/=2 extracts the rest of the bits, now if last bit of the rest of the bits is equal to the current last bit, then two adjacent bits are same and hence we return false
+10
View File
@@ -0,0 +1,10 @@
class Solution{
public :
bool hasAlternatingBits(int n){
int m = n^(n>>1);
return (m&(m+1)==0);
}
}
// TC & SC : o(1)
// n>>1 inverts all bits and XOR makes m have all set bits if n had alternating bits. (m+1) makes all bits of m as zero and m&(m+1) will be zero
+30
View File
@@ -0,0 +1,30 @@
class Solution{
public:
int countPrimeSetBits(int left, int right){
int ans = 0;
for(int i = left;i<=right;i++){
if(isPrime(__builtin_popcount(i)))
ans++;
}
return ans;
}
bool isPrime(int n){
if(n<2) return false;
for(int i =2;i*i<=n;i++)
if(n%i == 0) return false;
return true;
}
};
//TC : o(right-left+1)
//SC : o(1)
/*
int countPrimeSetBits(int L, int R) {
int cnt = 0, hash[20] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1};
for (int i = L; i <= R; i++) {
bitset<20> b(i);
if(hash[b.count()]) cnt++;
}
return cnt;
}
*/
+18
View File
@@ -0,0 +1,18 @@
class Solution{
public :
int binaryGap(int n){
int last = -1;
int ans =0;
for(int i =0;i<32;i++){
if(n>>i & 1){
if(last!=-1)
ans = max(ans, i-last);
last = i;
}
}
return ans;
}
};
//We'll store last, the index of the last set bit encountered. If n has the ith bit set, answer is i - last, and then the new last value would be last = i.
//TC : o(logn) , logn is the number of digits in the binary representation of n
//SC : o(1)