Dsa Solution Sheet Final
Dsa Solution Sheet Final
Brute Force
C++:
int count = 0;
for(int i = 0; i < nums.size(); i++) {
return count;
}
Java:
int count = 0;
}
return count;
Optimized Solution
C++:
int count = 0;
count += freq[num]++;
return count;
}
Java:
int count = 0;
return count;
C++:
vector<int> result(nums.size());
int count = 0;
result[i] = count;
return result;
}
Java:
int count = 0;
result[i] = count;
return result;
}
Optimized Solution
C++:
sort(sorted.begin(), sorted.end());
result[i] = rank[nums[i]];
}
return result;
}
Java:
Arrays.sort(sorted);
result[i] = rank.get(nums[i]);
return result;
3. Two Sum
Brute Force
C++:
}
return {};
}
Java:
}
}
}
Optimized Solution
C++:
if(map.find(complement) != map.end()) {
map[nums[i]] = i;
}
return {};
}
Java:
if(map.containsKey(complement)) {
map.put(nums[i], i);
Brute Force
C++:
if(nums.empty()) return 0;
int index = 1;
if(nums[i] != nums[i-1]) {
nums[index++] = nums[i];
return index;
Java:
if(nums.length == 0) return 0;
int index = 1;
return index;
5. Missing Number
Brute Force
C++:
int n = nums.size();
return i;
return -1;
}
Java:
int n = nums.length;
if (num == i) {
found = true;
break;
}
}
if (!found) return i;
return -1;
}
Optimized Solution
C++:
int n = nums.size();
int sum = n * (n + 1) / 2;
sum -= num;
return sum;
}
Java:
int n = nums.length;
int sum = n * (n + 1) / 2;
sum -= num;
return sum;
6. Majority Element
Brute Force
C++:
return -1;
}
Java:
int count = 0;
return -1;
}
return candidate;
}
Java:
}
return candidate;
7. Sort Colors
C++:
int index = 0;
nums[index++] = i;
}
}
Java:
nums[index++] = i;
}
Optimized Solution (Dutch National Flag Algorithm)
C++:
Java:
if (nums[mid] == 0) {
swap(nums, low++, mid++);
} else if (nums[mid] == 1) {
mid++;
} else {
nums[i] = nums[j];
nums[j] = temp;
8. Maximum Subarray
Brute Force
C++:
int currentSum = 0;
currentSum += nums[j];
return maxSum;
}
Java:
int currentSum = 0;
for (int j = i; j < nums.length; j++) {
currentSum += nums[j];
return maxSum;
}
Optimized Solution (Kadane's Algorithm)
C++:
return maxSum;
}
Java:
}
return maxSum;
Brute Force
C++:
void setZeroes(vector<vector<int>>& matrix) {
if (matrix[i][j] == 0) {
row[i] = 0;
col[j] = 0;
if (row[i] == 0 || col[j] == 0) {
matrix[i][j] = 0;
}
Java:
col[j] = true;
matrix[i][j] = 0;
}
Optimized Solution (Using First Row and Column as Markers)
C++:
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
Java:
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
for (int i = 1; i < m; i++) {
Brute Force
C++:
int maxArea = 0;
}
return maxArea;
}
Java:
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
return maxArea;
C++:
int maxArea = 0;
left++;
} else {
right--;
}
return maxArea;
}
Java:
int maxArea = 0;
left++;
} else {
right--;
return maxArea;
Brute Force
C++:
}
return false;
}
Java:
return false;
C++:
}
return false;
}
Java:
return false;
Brute Force
C++:
int count = 0;
return count;
}
Java:
int count = 0;
return count;
vector<int> temp;
else temp.push_back(nums[k++]);
return count;
}
return count;
}
}
Java:
return count;
private int mergeAndCount(int[] nums, int left, int mid, int right) {
int count = 0, j = mid + 1;
for (int i = left; i <= mid; i++) {
else temp.add(nums[k++]);
return count;
}
SLIDING WINDOW –
C++:
sum += nums[right];
sum -= nums[left++];
}
Java:
sum -= nums[left++];
}
}
return minLen == Integer.MAX_VALUE ? 0 : minLen;
C++:
if (nums[left++] == 0) zeroCount--;
return maxLen;
}
Java:
if (nums[right] == 0) zeroCount++;
if (nums[left++] == 0) zeroCount--;
}
return maxLen;
}
3. Minimum Operations to Reduce X to Zero
C++:
currentSum += nums[right];
currentSum -= nums[left++];
if (currentSum == target) {
}
Java:
currentSum -= nums[left++];
if (currentSum == target) {
}
return maxLen == -1 ? -1 : nums.length - maxLen;
C++:
start = left;
}
if (++charCount[s[left++]] > 0) count--;
}
Java:
if (charCount.containsKey(rChar)) {
start = left;
}
if (charCount.containsKey(lChar)) {
C++:
total += nums[right];
total -= nums[left++];
return maxFreq;
Java:
long total = 0;
total += nums[right];
total -= nums[left++];
}
return maxFreq;
TWO POINTERS
else right--;
}
return false;
Java:
else right--;
return false;
C++:
left++;
} else {
right--;
return result;
Java:
Arrays.sort(nums);
powers[0] = 1;
left++;
} else {
right--;
return result;
C++:
sort(nums.begin(), nums.end());
left++;
right--;
return maxPairSum;
}
Java:
Arrays.sort(nums);
left++;
right--;
return maxPairSum;
left++;
} else {
right--;
}
}
return trappedWater;
Java:
java
Copy code
left++;
} else {
return trappedWater;
STRINGS
1. Valid Anagram
Brute Force:
Use two frequency arrays to count characters in both strings and then compare.
C++:
countT[t[i] - 'a']++;
}
Java:
countS[s.charAt(i) - 'a']++;
countT[t.charAt(i) - 'a']++;
Optimized:
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int i : count) {
if (i != 0) return false;
return true;
}
Java:
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
if (i != 0) return false;
return true;
2. Isomorphic Strings
Brute Force:
For each character, check if the mapping between the two strings is consistent.
C++:
return true;
}
Java:
return false;
mapStoT.put(c1, c2);
mapTtoS.put(c2, c1);
return true;
}
Optimized:
mapStoT[s[i]] = mapTtoS[t[i]] = i;
return true;
}
Java:
Arrays.fill(mapStoT, -1);
Arrays.fill(mapTtoS, -1);
mapStoT[s.charAt(i)] = mapTtoS[t.charAt(i)] = i;
}
return true;
Brute Force:
Compare characters one by one in all strings and stop at the first mismatch.
C++:
int j = 0;
j++;
}
prefix = prefix.substr(0, j);
if (prefix.empty()) return "";
return prefix;
}
Java:
int j = 0;
j++;
return prefix;
}
Optimized:
char c = strs[0][i];
if (i == strs[j].size() || strs[j][i] != c) {
return strs[0].substr(0, i);
}
return strs[0];
}
Java:
char c = strs[0].charAt(i);
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return strs[0];
Brute Force:
string reverseWords(string s) {
stringstream ss(s);
vector<string> words;
reverse(words.begin(), words.end());
result += words[i];
return result;
}
Java:
result.append(words[i]);
if (i != 0) result.append(" ");
return result.toString();
}
Optimized:
Trim spaces, reverse the entire string, and then reverse each word.
C++:
string reverseWords(string s) {
reverse(s.begin(), s.end());
int start = 0;
start = end + 1;
}
}
return s;
}
Java:
sb.reverse();
String[] words = sb.toString().split(" ");
sb.setLength(0);
return sb.toString().trim();
5. Group Anagrams
Brute Force:
sort(sortedStr.begin(), sortedStr.end());
anagrams[sortedStr].push_back(str);
vector<vector<string>> result;
for (auto& pair : anagrams) {
result.push_back(pair.second);
return result;
}
Java:
Arrays.sort(chars);
}
Optimized:
anagrams[key].push_back(str);
vector<vector<string>> result;
for (auto& pair : anagrams) {
result.push_back(pair.second);
return result;
}
Java:
count[c - 'a']++;
sb.append(i).append("#");
int beautySum(string s) {
int result = 0;
for (int i = 0; i < s.size(); i++) {
for (int j = i + 1; j <= s.size(); j++) {
}
}
return result;
}
Java:
int result = 0;
}
}
return result;
}
Optimized:
Use sliding window and a frequency count array to calculate the beauty efficiently.
C++:
int beautySum(string s) {
int result = 0;
freq[s[j] - 'a']++;
return result;
}
Java:
int result = 0;
freq[s.charAt(j) - 'a']++;
return result;
}
4. Reverse Words in a String
Brute Force:
string reverseWords(string s) {
stringstream ss(s);
words.push_back(word);
reverse(words.begin(), words.end());
result += words[i];
return result;
}
Java:
result.append(words[i]);
if (i != 0) result.append(" ");
return result.toString();
}
Optimized:
Trim spaces, reverse the entire string, and then reverse each word.
C++:
string reverseWords(string s) {
reverse(s.begin(), s.end());
int start = 0;
start = end + 1;
return s;
}
Java:
sb.reverse();
sb.setLength(0);
return sb.toString().trim();
5. Group Anagrams
Brute Force:
Sort each word and group them in a map.
C++:
sort(sortedStr.begin(), sortedStr.end());
anagrams[sortedStr].push_back(str);
}
vector<vector<string>> result;
result.push_back(pair.second);
return result;
}
Java:
Arrays.sort(chars);
}
Optimized:
anagrams[key].push_back(str);
}
vector<vector<string>> result;
result.push_back(pair.second);
return result;
}
Java:
count[c - 'a']++;
}
StringBuilder sb = new StringBuilder();
sb.append(i).append("#");
Brute Force:
int beautySum(string s) {
int result = 0;
return result;
}
Java:
int result = 0;
return result;
}
Optimized:
Use sliding window and a frequency count array to calculate the beauty efficiently.
C++:
int beautySum(string s) {
int result = 0;
freq[s[j] - 'a']++;
}
return result;
}
Java:
int result = 0;
for (int i = 0; i < s.length(); i++) {
int[] freq = new int[26];
freq[s.charAt(j) - 'a']++;
}
}
return result;
Brute Force:
int lengthOfLongestSubstring(string s) {
int maxLength = 0;
unordered_set<char> seen;
if (seen.count(s[j])) break;
seen.insert(s[j]);
maxLength = max(maxLength, j - i + 1);
return maxLength;
}
Java:
int maxLength = 0;
if (seen.contains(s.charAt(j))) break;
seen.add(s.charAt(j));
return maxLength;
Optimized (continued):
C++:
int lengthOfLongestSubstring(string s) {
charMap[s[right]] = right;
maxLength = max(maxLength, right - left + 1);
return maxLength;
}
Java:
if (charMap.containsKey(s.charAt(right))) {
}
charMap.put(s.charAt(right), right);
return maxLength;
Brute Force:
string longestPalindrome(string s) {
start = i;
maxLength = j - i + 1;
}
}
Java:
isPalindrome = false;
start = i;
maxLength = j - i + 1;
Optimized:
string longestPalindrome(string s) {
maxLength = len;
while (left >= 0 && right < s.size() && s[left] == s[right]) {
left--;
right++;
}
Java:
start = i - (len - 1) / 2;
maxLength = len;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
Brute Force:
Parse the string character by character, handling signs and edge cases manually.
C++:
int myAtoi(string s) {
index++;
}
while (index < s.size() && isdigit(s[index])) {
int digit = s[index] - '0';
index++;
}
Java:
while (index < s.length() && s.charAt(index) == ' ') index++; // Skip whitespaces
index++;
index++;
}
Optimized:
The brute force method is already optimized as it processes the string in a single
pass.
10. Minimum Window Substring
Brute Force:
Generate all substrings and check if they contain all characters of the target string.
C++:
windowFreq[s[j]]++;
valid = false;
break;
minLen = j - i + 1;
result = s.substr(i, minLen);
return result;
}
Java:
valid = false;
break;
minLen = j - i + 1;
}
}
return result;
}
Optimized (continued):
Use the sliding window technique to shrink the window once all characters from t are
found in the current window of s.
C++:
char c = s[right];
windowFreq[c]++;
start = left;
}
windowFreq[leftChar]--;
left++;
char c = s.charAt(right);
matched--;
}
left++;
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
LINKED LIST
Brute Force:
Convert the linked list into an array and check if it's a palindrome.
C++:
while (head) {
vals.push_back(head->val);
head = head->next;
left++;
right--;
}
return true;
}
Java:
vals.add(head.val);
head = head.next;
left++;
right--;
}
return true;
}
Optimized:
Use two pointers to reverse the second half of the linked list and then compare the
two halves.
C++:
bool isPalindrome(ListNode* head) {
slow = slow->next;
fast = fast->next->next;
while (secondHalf) {
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
return true;
head->next = prev;
prev = head;
head = nextNode;
}
return prev;
}
Java:
fast = fast.next.next;
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
return true;
head = nextNode;
return prev;
Brute Force:
For each node in the first list, traverse the second list and check for intersection.
C++:
while (headA) {
while (temp) {
temp = temp->next;
headA = headA->next;
return nullptr;
}
Java:
temp = temp.next;
}
headA = headA.next;
return null;
}
Optimized:
Use two pointers. Move both pointers through both lists and they will meet at the
intersection point.
C++:
while (a != b) {
a = a ? a->next : headB;
b = b ? b->next : headA;
return a;
}
Java:
while (a != b) {
}
return a;
3. LRU Cache
Brute Force:
Not applicable for brute force, as LRU cache is inherently an optimized structure
Optimized:
C++:
cpp
Copy code
class LRUCache {
public:
moveToHead(key);
return cache[key].first;
if (cache.find(key) != cache.end()) {
cache[key].first = value;
moveToHead(key);
} else {
if (cache.size() == capacity) {
cache.erase(lruKey);
keys.pop_back();
}
keys.push_front(key);
private:
int capacity;
list<int> keys;
keys.erase(cache[key].second);
keys.push_front(key);
cache[key].second = keys.begin();
};
Java:
java
Copy code
class LRUCache {
this.capacity = capacity;
order.remove(key);
order.add(key);
return cache.get(key);
if (cache.containsKey(key)) {
order.remove(key);
cache.remove(oldest);
order.remove(oldest);
cache.put(key, value);
order.add(key);
class Solution {
public:
total = carry;
if (l1) {
total += l1->val;
l1 = l1->next;
}
if (l2) {
total += l2->val;
l2 = l2->next;
dummy = dummy->next;
return res->next;
};
Java:
class Solution {
total = carry;
if (l1 != null) {
total += l1.val;
l1 = l1.next;
}
if (l2 != null) {
total += l2.val;
l2 = l2.next;
dummy = dummy.next;
return res.next;
5. Rotate List
Brute Force:
We rotate the list one step at a time for k times, moving the last node to the front
each time.
C++:
ListNode* rotateRight(ListNode* head, int k) {
int len = 0;
while (temp) {
len++;
temp = temp->next;
k = k % len;
while (k--) {
while (curr->next) {
prev = curr;
curr = curr->next;
prev->next = nullptr;
curr->next = head;
head = curr;
return head;
}
Java:
len++;
temp = temp.next;
k = k % len;
prev = curr;
curr = curr.next;
prev.next = null;
curr.next = head;
head = curr;
return head;
}
Optimized:
First, compute the length of the list. Then, rotate the list by adjusting the pointers
directly to form the new list in one pass.
C++:
int len = 1;
while (temp->next) {
temp = temp->next;
len++;
}
temp->next = head;
k = len - k % len;
head = temp->next;
temp->next = nullptr;
return head;
}
Java:
int len = 1;
temp.next = head;
k = len - k % len;
head = temp.next;
temp.next = null;
return head;
6. Reorder List
Brute Force:
Extract all nodes into a list, reorder them using two pointers, and reconstruct the list.
C++:
vector<ListNode*> nodes;
while (temp) {
nodes.push_back(temp);
temp = temp->next;
}
int i = 0, j = nodes.size() - 1;
while (i < j) {
nodes[i]->next = nodes[j];
i++;
if (i == j) break;
nodes[j]->next = nodes[i];
j--;
nodes[i]->next = nullptr;
}
Java:
nodes.add(temp);
temp = temp.next;
int i = 0, j = nodes.size() - 1;
while (i < j) {
nodes.get(i).next = nodes.get(j);
i++;
if (i == j) break;
nodes.get(j).next = nodes.get(i);
j--;
nodes.get(i).next = null;
}
Optimized:
Find the middle of the list, reverse the second half, and merge the two halves
together.
C++:
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = nullptr;
ListNode* l2 = reverseList(slow);
mergeLists(head, l2);
head->next = prev;
prev = head;
head = nextNode;
return prev;
l1->next = l2;
l1 = l1Next;
l2 = l2Next;
}
Java:
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
ListNode l2 = reverseList(slow);
mergeLists(head, l2);
head.next = prev;
prev = head;
head = nextNode;
return prev;
l1.next = l2;
if (l1Next != null) l2.next = l1Next;
l1 = l1Next;
l2 = l2Next;
}
7. Linked List Cycle II
Brute Force:
Use a hash set to track visited nodes. If a node is revisited, it's the cycle's start.
C++:
unordered_set<ListNode*> visited;
while (head) {
visited.insert(head);
head = head->next;
return nullptr;
}
Java:
visited.add(head);
head = head.next;
}
return null;
}
Optimized:
Use two pointers (slow and fast) to detect a cycle. If they meet, reset one pointer to
the head and move both pointers one step at a time until they meet again.
C++:
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
slow = head;
slow = slow->next;
fast = fast->next;
}
return slow;
return nullptr;
}
Java:
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
slow = head;
slow = slow.next;
fast = fast.next;
return slow;
return null;
}
8. Rearrange a Linked List in Zig-Zag Fashion
Brute Force & Optimized:
Traverse the linked list and for each pair of consecutive nodes, swap them if they are
not in zig-zag order (i.e., the first node should be less than the second, then greater
than the next, and so on).
C++:
if (flag) {
swap(current->val, current->next->val);
} else {
swap(current->val, current->next->val);
}
flag = !flag;
current = current->next;
}
Java:
boolean flag = true; // true means "<" relation expected, false means ">" relation
expected
if (flag) {
current.val = current.next.val;
current.next.val = temp;
} else {
current.next.val = temp;
flag = !flag;
current = current.next;
C++:
#include <bits/stdc++.h>
class Node {
public:
int data;
Node(int new_data) {
data = new_data;
};
vector<int> values;
values.push_back(temp->data);
temp = temp->bottom;
root = root->next;
sort(values.begin(), values.end());
if (head == NULL) {
head = newNode;
else {
tail->bottom = newNode;
}
tail = newNode;
return head;
temp = temp->bottom;
int main() {
| | |
V V V
7 20 22
| |
V V
8 50
30
*/
Node* head = new Node(5);
// Function call
head = flatten(head);
printList(head);
return 0;
}
Java:
// Java Program for flattening a linked list
import java.util.*;
class Node {
int data;
Node(int newData) {
data = newData;
root = root.next;
if (head == null)
head = newNode;
else
tail.bottom = newNode;
tail = newNode;
}
return head;
temp = temp.bottom;
System.out.println();
// | | |
// V V V
// 7 20 22
// | |
// V V
// 8 50
// |
// V
// 30
// Function call
head = flatten(head);
printList(head);
First, count the nodes, then reverse every k nodes by traversing the list multiple
times.
C++:
int count = 0;
while (current) {
count++;
current = current->next;
int i = 0;
next = current->next;
current->next = prev;
prev = current;
current = next;
i++;
return prev;
}
Java:
int count = 0;
current = current.next;
int i = 0;
next = current.next;
current.next = prev;
prev = current;
current = next;
i++;
return prev;
C++:
class MyStack {
public:
MyStack() {}
void push(int x) {
q1.push(x);
int pop() {
q2.push(q1.front());
q1.pop();
q1.pop();
swap(q1, q2);
return topElem;
int top() {
q2.push(q1.front());
q1.pop();
}
int topElem = q1.front();
q2.push(topElem); // keep the last element in the stack
q1.pop();
swap(q1, q2);
return topElem;
bool empty() {
return q1.empty();
}
};
Java:
class MyStack {
public MyStack() {}
q1.add(x);
q1 = q2;
q2 = temp;
return topElem;
q2.add(q1.poll());
q1 = q2;
q2 = temp;
return topElem;
return q1.isEmpty();
For each element in nums1, scan through nums2 to find the next greater element.
C++:
vector<int> res;
if (nums2[j] == nums1[i]) {
found = true;
nextGreater = nums2[j];
break;
}
}
res.push_back(nextGreater);
return res;
Java:
break;
res[i] = nextGreater;
}
return res;
}
Optimized:
Use a stack to track the next greater element in nums2 and store the result in a map
for nums1.
C++:
stack<int> s;
map[s.top()] = n;
s.pop();
s.push(n);
vector<int> res;
return res;
}
Java:
stack.push(n);
return res;
}
3. Valid Parentheses
For each closing bracket, scan backward to find its corresponding opening bracket,
validating each one.
C++:
bool isValid(string s) {
stack<char> stack;
for (char c : s) {
stack.push(c);
} else {
} else {
return false;
return stack.empty();
Java:
stack.push(c);
} else {
return stack.isEmpty();
}
4. Next Greater Element II
Brute Force:
Loop through the array twice to handle the circular nature and find the next greater
element for each number.
C++:
int n = nums.size();
break;
}
return res;
}
Java:
int n = nums.length;
Arrays.fill(res, -1);
return res;
Optimized:
Use a monotonic stack to keep track of indices of the array elements, handling the
circular nature by iterating twice through the array.
C++:
int n = nums.size();
stack<int> s;
s.pop();
if (i < n) {
s.push(i);
return res;
}
Java:
int n = nums.length;
Arrays.fill(res, -1);
if (i < n) {
stack.push(i);
return res;
5. Asteroid Collision
Brute Force:
Compare each asteroid with the next in the array to simulate the collisions, updating
the list accordingly.
C++:
vector<int> res;
res.push_back(asteroids[i]);
} else {
while (!res.empty() && res.back() > 0 && res.back() < abs(asteroids[i])) {
res.pop_back();
res.pop_back();
res.push_back(asteroids[i]);
}
}
return res;
}
Java:
res.add(asteroids[i]);
} else {
res.remove(res.size() - 1);
res.remove(res.size() - 1);
res.add(asteroids[i]);
}
}
}
Optimized:
Use a stack to handle the collisions. Push positive asteroids and resolve collisions
with negative asteroids by comparing their magnitudes.
C++:
stack<int> s;
s.pop();
alive = false;
break;
} else {
alive = false;
break;
if (alive) {
s.push(a);
}
}
vector<int> res(s.size());
res[i] = s.top();
s.pop();
return res;
}
Java:
stack.pop();
stack.pop();
alive = false;
break;
} else {
alive = false;
break;
}
if (alive) {
stack.push(a);
}
}
int[] res = new int[stack.size()];
res[i] = stack.pop();
return res;
6. Remove K Digits
Brute Force:
Generate all possible combinations by removing k digits and compare to find the
smallest number.
C++:
while (k > 0) {
int n = result.size();
int i = 0;
result.erase(i, 1);
k--;
int start = 0;
result = result.substr(start);
return result.empty() ? "0" : result;
}
Java:
while (k > 0) {
int n = result.length();
int i = 0;
result.deleteCharAt(i);
k--;
int start = 0;
}
Optimized:
k--;
result.push_back(c);
int i = 0;
result = result.substr(i);
}
Java:
stack.pop();
k--;
stack.push(c);
}
For each window of size k, find the maximum value by scanning through the window.
C++:
vector<int> result;
result.push_back(maxVal);
return result;
}
Java:
java
Copy code
int n = nums.length;
int[] result = new int[n - k + 1];
return result;
1. Fibonacci Number
C++:
int fib(int n) {
if (n <= 1) return n;
}
Java:
if (n <= 1) return n;
2. Pow(x, n)
C++:
if (n == 0) return 1;
if (n == 0) return 1;
3. Power of Three
C++:
bool isPowerOfThree(int n) {
if (n == 1) return true;
if (n == 0 || n % 3 != 0) return false;
}
Java:
if (n == 1) return true;
if (n == 0 || n % 3 != 0) return false;
4. Combination Sum
C++:
if (target == 0) {
res.push_back(curr);
return;
}
if (target < 0) return;
curr.push_back(candidates[i]);
curr.pop_back();
vector<vector<int>> res;
vector<int> curr;
return res;
}
Java:
if (target == 0) {
res.add(new ArrayList<>(curr));
return;
curr.add(candidates[i]);
curr.remove(curr.size() - 1);
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
return res;
5. Subsets
C++:
res.push_back(curr);
curr.push_back(nums[i]);
curr.pop_back();
vector<vector<int>> res;
vector<int> curr;
return res;
Java:
res.add(new ArrayList<>(curr));
for (int i = index; i < nums.length; i++) {
curr.add(nums[i]);
curr.remove(curr.size() - 1);
return res;
6. Coin Change
C++:
if (amount == 0) return 0;
}
return res;
if (amount == 0) return 0;
return res;
7. Elimination Game
C++:
int lastRemaining(int n) {
if (n == 1) return 1;
}
Java:
public int lastRemaining(int n) {
if (n == 1) return 1;
C++:
return (x >= 0 && x < n && y >= 0 && y < n && maze[x][y] == 1 && visited[x][y] ==
0);
if (x == n - 1 && y == n - 1) {
visited[x][y] = 1;
return true;
visited[x][y] = 1;
visited[x][y] = 0; // Backtrack
return false;
}
vector<vector<int>> solveMaze(vector<vector<int>>& maze, int n) {
return visited;
}
Java:
return (x >= 0 && x < n && y >= 0 && y < n && maze[x][y] == 1 && visited[x][y] ==
0);
if (x == n - 1 && y == n - 1) {
visited[x][y] = 1;
return true;
}
visited[x][y] = 1;
visited[x][y] = 0; // Backtrack
}
return false;
}
return visited;
9. Word Break
C++:
if (s.empty())return true;
return false;
}
Java:
private boolean wordBreakUtil(String s, Set<String> wordDict) {
return true;
}
return false;
10. N-Queens
C++:
if (col - (row - i) >= 0 && board[i][col - (row - i)] == 'Q') return false;
if (col + (row - i) < n && board[i][col + (row - i)] == 'Q') return false;
}
return true;
res.push_back(board);
return;
board[row][col] = 'Q';
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
return res;
Java:
if (col - (row - i) >= 0 && board.get(i).charAt(col - (row - i)) == 'Q') return false;
if (col + (row - i) < n && board.get(i).charAt(col + (row - i)) == 'Q') return false;
return true;
}
private void solveNQueensUtil(int n, int row, List<String> board, List<List<String>>
res) {
if (row == n) {
res.add(new ArrayList<>(board));
return;
sb.setCharAt(col, 'Q');
board.set(row, sb.toString());
sb.setCharAt(col, '.');
board.set(row, sb.toString());
return res;
C++:
return true;
if (board[i][j] == '.') {
if (isValid(board, i, j, c)) {
board[i][j] = c;
board[i][j] = '.';
}
return false;
return true;
return false;
return true;
if (board[i][j] == '.') {
if (isValid(board, i, j, c)) {
board[i][j] = c;
board[i][j] = '.';
return false;
return true;
}
public void solveSudoku(char[][] board) {
solveSudokuUtil(board);
12. Tug-of-War
C++:
if (idx == n) {
resSet1 = currSet1;
resSet2 = currSet2;
return;
}
if (currSet1.size() < (n + 1) / 2) {
currSet1.push_back(arr[idx]);
currSet1.pop_back();
if (currSet2.size() < (n + 1) / 2) {
currSet2.push_back(arr[idx]);
tugOfWarUtil(arr, currSet1, currSet2, idx + 1, n, minDiff, resSet1, resSet2);
currSet2.pop_back();
int n = arr.size();
}
Java:
if (idx == n) {
resSet1.clear();
resSet1.addAll(currSet1);
resSet2.clear();
resSet2.addAll(currSet2);
return;
if (currSet1.size() < (n + 1) / 2) {
currSet1.add(arr[idx]);
tugOfWarUtil(arr, currSet1, currSet2, idx + 1, n, minDiff, resSet1, resSet2);
currSet1.remove(currSet1.size() - 1);
if (currSet2.size() < (n + 1) / 2) {
currSet2.add(arr[idx]);
currSet2.remove(currSet2.size() - 1);
}
int n = arr.length;
}
DYANMIC PROGRAMMING
Fibonacci Number
C++:
class Solution {
public:
Solution() {
if (dp.empty()) {
dp.resize(31, -1);
int fib(int n) {
if (n <= 1) {
return n;
if (dp[n - 1] != -1) {
if (dp[n - 2] != -1) {
} else {
// Memoization
};
JAVA:
class Solution {
static {
Arrays.fill(dp, -1);
}
public int fib(int n) {
if (n <= 1) {
return n;
if (dp[n - 1] != -1) {
} else {
if (dp[n - 2] != -1) {
} else {
// Memoization
}
}
Climbing Stairs
C++:
JAVA:
Counting Bits
C++:
class Solution {
public:
int climbStairs(int n) {
if (n <= 3) return n;
int prev1 = 3;
int prev2 = 2;
int cur = 0;
prev2 = prev1;
prev1 = cur;
return cur;
};
JAVA:
class Solution {
if (n <= 3) return n;
int prev1 = 3;
int prev2 = 2;
int cur = 0;
prev2 = prev1;
prev1 = cur;
return cur;
Cherry Pickup II
C++:
#include <vector>
#include <algorithm>
class Solution {
public:
dp[i][j][k] = -1;
}
}
return 0;
if (dp[level][c1][c2] != -1) {
return dp[level][c1][c2];
int cherries = 0;
if (c1 == c2) {
} else {
}
return dp[level][c1][c2] = maxCherries; // Store the result in dp
}
};
JAVA:
class Solution {
int[][][] dp;
dp=new int[grid.length][grid[0].length][grid[0].length];
for(int i=0;i<dp.length;i++){
for(int j=0;j<dp[i].length;j++){
for(int k=0;k<dp[i][j].length;k++){
dp[i][j][k]=-1;
return rec(grid,0,0,grid[0].length-1);
return 0;
if(dp[level][c1][c2]!=-1)
return dp[level][c1][c2];
int max=Integer.MIN_VALUE;
for(int di=-1;di<=1;di++){
for(int dj=-1;dj<=1;dj++){
int cherry=0;
if(c1==c2){
cherry=grid[level][c1];
}else{
cherry=grid[level][c1]+grid[level][c2];
max=Math.max(max,cherry+rec(grid,level+1,c1+di,c2+dj));
}
}
return dp[level][c1][c2]=max;
C++:
#include <bits/stdc++.h>
while (n) {
if (n & 1)
cout << 1;
else
cout << 0;
n >>= 1;
len--;
}
while (len) {
cout << 0;
len--;
int sum;
int count = 0;
sum = 0;
sum += set[j];
if (sum == val) {
count++;
if (count == 0) {
int main() {
int set[] = { 1, 2, 3, 4, 5 };
printSubsetsCount(set, 5, 9);
JAVA:
import java.io.*;
class GFG {
while (n > 0) {
if ((n & 1) == 1)
System.out.print(1);
else
System.out.print(0);
n >>= 1;
len--;
System.out.print(0);
len--;
System.out.println();
int count = 0;
sum = 0;
sum += set[j];
}
if (sum == val) {
count++;
if (count == 0) {
} else {
System.out.println(count);
printSubsetsCount(set, 5, 9);
}
}
Longest Common Subsequence
C++:
class Solution {
public:
int longest = 0;
int curLength = 0;
curLength = dp[i];
} else if (c == text1[i]) {
dp[i] = curLength + 1;
return longest;
};
JAVA:
class Solution {
int longest = 0;
int curLength = 0;
curLength = dp[i];
} else if (c == text1.charAt(i)) {
dp[i] = curLength + 1;
return longest;
}
Longest Palindromic Subsequence
C++:
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.length();
// Initialize a 2D array to store the length of the longest palindromic
subsequence
// Iterate over the substrings in reverse order to fill in the dp table bottom-up
dp[i][i] = 1;
} else {
};
JAVA:
class Solution {
int n = s.length();
// Iterate over the substrings in reverse order to fill in the dp table bottom-up
for (int i = n-1; i >= 0; i--) {
dp[i][i] = 1;
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = 2 + dp[i+1][j-1];
} else {
C++:
#include <bits/stdc++.h>
int n = s1.size();
int m = s2.size();
// Create two arrays to store the previous and current rows of DP values
else
}
// Update the prev array with the current values
prev = cur;
}
// The value at prev[m] contains the length of the LCS
return prev[m];
int n = str1.size();
int m = str2.size();
// Calculate the length of the longest common subsequence between str1 and str2
return (n - k) + (m - k);
int main() {
cout << "The Minimum operations required to convert str1 to str2: " <<
canYouMake(str1, str2);
return 0;
JAVA:
import java.util.*;
class TUF {
int n = s1.length();
int m = s2.length();
else
prev = cur.clone();
return prev[m];
}
// Function to find the minimum operations required to convert str1 to str2
int n = str1.length();
int m = str2.length();
// The minimum operations required is the sum of the lengths of str1 and str2
minus twice the length of LCS
return (n - k) + (m - k);
C++:
class Solution {
public:
if(hold==1){
return dp[currIndex][hold]=max(sell,skip);
}else{
int k =prices.size();
int n = prices.size();
vector<vector<int>>dp(n+1,vector<int>(2,-1));
return solve(prices,0,k,0,dp);
};
JAVA:
class Solution {
public int solve(int[] prices, int currIndex, int left, int hold, int[][] dp) {
if (currIndex >= prices.length || left <= 0) return 0;
if (dp[currIndex][hold] != -1) return dp[currIndex][hold];
if (hold == 1) {
} else {
int k = prices.length;
int n = prices.length;
dp[i][0] = -1;
dp[i][1] = -1;
}
Burst Balloons
C++:
class Solution {
public:
int n = nums.size();
nums.insert(nums.begin(), 1);
nums.push_back(1);
if(i>j) continue;
dp[i][j] = maxi;
return dp[1][n];
};
JAVA:
```java
class Solution {
int n = nums.length;
newNums[0] = 1;
newNums[n + 1] = 1;
if (i > j) continue;
dp[i][j] = maxi;
}
return dp[1][n];
}
}
BINARY TREE AND BST-
preorder(root->right, result);
vector<int> result;
preorder(root, result);
return result;
}
Brute Force (Java):
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
preorder(root, result);
return result;
}
Optimized (C++):
vector<int> result;
stack<TreeNode*> s;
if (root) s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
result.push_back(node->val);
if (node->right) s.push(node->right);
if (node->left) s.push(node->left);
return result;
}
Optimized (Java):
while (!stack.isEmpty()) {
result.add(node.val);
return result;
inorder(root->left, result);
result.push_back(root->val);
inorder(root->right, result);
vector<int> result;
inorder(root, result);
return result;
}
Brute Force (Java):
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
inorder(root, result);
return result;
}
Optimized (C++):
stack<TreeNode*> s;
current = current->left;
current = s.top();
s.pop();
result.push_back(current->val);
current = current->right;
}
return result;
}
Optimized (Java):
stack.push(current);
current = current.left;
current = stack.pop();
result.add(current.val);
current = current.right;
return result;
vector<vector<int>> result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> currentLevel;
q.pop();
currentLevel.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
result.push_back(currentLevel);
return result;
}
Brute Force (Java):
while (!queue.isEmpty()) {
result.add(currentLevel);
return result;
}
4. Vertical Order Traversal of a Binary Tree
queue<pair<TreeNode*, int>> q;
while (!q.empty()) {
auto p = q.front();
q.pop();
vector<vector<int>> result;
result.push_back(value);
}
return result;
}
Brute Force (Java):
while (!queue.isEmpty()) {
Collections.sort(keys);
result.add(map.get(key));
return result;
vector<int> result;
queue<pair<TreeNode*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto p = q.front();
q.pop();
topNodes[hd] = node->val;
result.push_back(value);
return result;
}
Brute Force (Java):
while (!queue.isEmpty()) {
int hd = pair.getValue();
if (!topNodes.containsKey(hd)) {
topNodes.put(hd, node.val);
result.addAll(topNodes.values());
return result;
vector<int> result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
q.pop();
if (i == size - 1) result.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
return result;
}
Brute Force (Java):
queue.offer(root);
while (!queue.isEmpty()) {
if (i == size - 1) result.add(node.val);
return result;
}
7. Left View of Binary Tree
vector<int> result;
q.push(root);
while (!q.empty()) {
q.pop();
if (i == 0) result.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
return result;
}
Brute Force (Java):
queue.offer(root);
while (!queue.isEmpty()) {
if (i == 0) result.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
return result;
vector<int> result;
queue<pair<TreeNode*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto p = q.front();
q.pop();
bottomNodes[hd] = node->val;
result.push_back(value);
return result;
while (!queue.isEmpty()) {
int hd = pair.getValue();
bottomNodes.put(hd, node.val);
result.addAll(bottomNodes.values());
return result;
9. Burning Tree
Brute Force (C++):
if (left != -1) {
// Do something
if (right != -1) {
// Do something
}
}
Brute Force (Java):
if (left != -1) {
// Do something
}
if (right != -1) {
// Do something
}
10. Kth Smallest Element in a BST
if (!root) return;
inorder(root->left, result);
result.push_back(root->val);
inorder(root->right, result);
vector<int> result;
inorder(root, result);
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
inorder(root, result);
}
Optimized (C++):
if (k == 0) return left;
k--;
if (k == 0) return root->val;
k[0]--;
if (k[0] == 0) return root.val;
if (!root) return 0;
}
Brute Force (Java):
return countNodes(root);
}
Optimized (C++):
struct Info {
int size;
int min;
int max;
bool isBST;
};
Info largestBSTHelper(TreeNode* root) {
if (left.isBST && right.isBST && root->val > left.max && root->val < right.min) {
return largestBSTHelper(root).size;
}
Optimized (Java):
class Info {
int size;
int min;
int max;
boolean isBST;
if (left.isBST && right.isBST && root.val > left.max && root.val < right.min) {
return largestBSTHelper(root).size;
if (!root) return 0;
}
Brute Force (Java):
maxPathSumHelper(root, maxSum);
return maxSum[0];
}
13. Serialize and Deserialize Binary Tree
string val;
node->left = deserializeHelper(iss);
node->right = deserializeHelper(iss);
return node;
return deserializeHelper(iss);
}
Brute Force (Java):
node.left = deserializeHelper(nodes);
node.right = deserializeHelper(nodes);
return node;
}
14. Lowest Common Ancestor of a Binary Search Tree
}
Brute Force (Java):
Optimized (C++):
root = root->right;
root = root->left;
} else {
return root;
}
}
return nullptr;
}
Optimized (Java):
root = root.right;
} else {
return root;
return null;
if (!root) return;
inorder(root->left, vals);
vals.push_back(root->val);
inorder(root->right, vals);
inorder(root, vals);
unordered_set<int> seen;
seen.insert(val);
return false;
}
Brute Force (Java):
inorder(root.left, vals);
vals.add(root.val);
inorder(root.right, vals);
seen.add(val);
return false;
}
Optimized (C++):
unordered_set<int> seen;
stack<TreeNode*> stk;
while (curr) {
stk.push(curr);
curr = curr->left;
curr = stk.top();
stk.pop();
curr = curr->right;
return false;
}
Optimized (Java):
public boolean findTarget(TreeNode root, int k) {
stk.push(curr);
curr = curr.left;
curr = stk.pop();
seen.add(curr.val);
curr = curr.right;
return false;
GRAPH
1. DFS of Graph
if (!visited[neighbor]) {
if (!visited[i]) {
}
Brute Force (Java):
if (!visited[neighbor]) {
}
}
int n = graph.size();
boolean[] visited = new boolean[n]; // Initialize visited array
for (int i = 0; i < n; i++) {
if (!visited[i]) {
}
Optimized (C++): The optimized version utilizes an iterative approach to avoid stack
overflow issues with deep recursions.
int n = graph.size();
if (!visited[i]) {
stk.push(i);
while (!stk.empty()) {
stk.pop();
if (!visited[node]) {
if (!visited[neighbor]) {
}
}
}
Optimized (Java):
int n = graph.size();
if (!visited[i]) {
while (!stk.isEmpty()) {
if (!visited[node]) {
if (!visited[neighbor]) {
2. BFS of Graph
while (!q.empty()) {
q.pop();
if (!visited[neighbor]) {
int n = graph.size();
if (!visited[i]) {
}
Brute Force (Java):
q.add(start);
if (!visited[neighbor]) {
}
}
int n = graph.size();
if (!visited[i]) {
}
Optimized (C++): The optimized approach utilizes a queue for BFS, which
inherently provides efficiency.
int n = graph.size();
if (!visited[i]) {
while (!q.empty()) {
q.pop();
if (!visited[neighbor]) {
Optimized (Java): This approach utilizes a queue for efficient breadth-first traversal.
int n = graph.size();
q.add(i);
while (!q.isEmpty()) {
int node = q.poll();
if (!visited[neighbor]) {
}
}
3. Number of Triangles
Brute Force (C++): This approach checks all combinations of three vertices to count
triangles.
int count = 0;
int n = graph.size();
for (int i = 0; i < n; i++) {
}
Brute Force (Java):
int n = graph.size();
}
}
}
Optimized (C++): This approach uses adjacency sets to reduce the time complexity
for checking edges.
int count = 0;
int n = graph.size();
vector<unordered_set<int>> adj(n);
adj[i].insert(neighbor);
}
}
}
}
Optimized (Java): This version uses sets for efficient edge existence checks.
int count = 0;
int n = graph.size();
Set<Integer>[] adj = new HashSet[n];
adj[i].add(neighbor);
}
}
4. Rotting Oranges
Brute Force (C++): This approach uses BFS to propagate the rotting effect over
time.
queue<pair<int, int>> q;
int freshCount = 0;
if (grid[i][j] == 2) {
} else if (grid[i][j] == 1) {
int minutes = 0;
while (!q.empty() && freshCount > 0) {
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == 1) {
freshCount--;
}
}
return freshCount == 0 ? minutes : -1; // Return -1 if there are still fresh oranges
}
Brute Force (Java): This version uses a similar BFS approach.
int freshCount = 0;
if (grid[i][j] == 2) {
} else if (grid[i][j] == 1) {
int minutes = 0;
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == 1) {
freshCount--;
}
minutes++; // Increment minute count after processing one layer
return freshCount == 0 ? minutes : -1; // Return -1 if there are still fresh oranges
}
Optimized (C++): The optimized approach uses the same BFS but may utilize
additional space for direction vectors.
queue<pair<int, int>> q;
int freshCount = 0;
if (grid[i][j] == 2) {
} else if (grid[i][j] == 1) {
}
}
int minutes = 0;
freshCount--;
return freshCount == 0 ? minutes : -1; // Return -1 if there are still fresh oranges
}
Optimized (Java):
int freshCount = 0;
} else if (grid[i][j] == 1) {
int minutes = 0;
while (!q.isEmpty() && freshCount > 0) {
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == 1) {
freshCount--;
return freshCount == 0 ? minutes : -1; // Return -1 if there are still fresh oranges
5. Course Schedule
Brute Force (C++): This approach attempts to use BFS to check for cycles and see
if all courses can be completed.
vector<vector<int>> adj(numCourses);
adj[p[1]].push_back(p[0]);
queue<int> q;
if (inDegree[i] == 0) {
int count = 0;
while (!q.empty()) {
if (inDegree[neighbor] == 0) {
}
}
return count == numCourses; // Check if all courses can be completed
}
Brute Force (Java):
adj.get(p[1]).add(p[0]);
if (inDegree[i] == 0) {
int count = 0;
while (!q.isEmpty()) {
}
Optimized (C++): This version also uses BFS and is efficient.
vector<vector<int>> adj(numCourses);
adj[p[1]].push_back(p[0]);
queue<int> q;
if (inDegree[i] == 0) {
}
}
int count = 0;
while (!q.empty()) {
if (inDegree[neighbor] == 0) {
}
Optimized (Java): This version is similarly efficient in Java.
adj.add(new ArrayList<>());
adj.get(p[1]).add(p[0]);
if (inDegree[i] == 0) {
}
}
int count = 0;
while (!q.isEmpty()) {
if (inDegree[neighbor] == 0) {
q.add(neighbor); // Add to queue if no more prerequisites
6. Course Schedule II
Brute Force (C++): This approach utilizes a modified BFS to find a valid course
order.
vector<vector<int>> adj(numCourses);
adj[p[1]].push_back(p[0]);
queue<int> q;
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) {
vector<int> order;
while (!q.empty()) {
int course = q.front(); q.pop();
if (inDegree[neighbor] == 0) {
}
Brute Force (Java):
adj.add(new ArrayList<>());
if (inDegree[i] == 0) {
while (!q.isEmpty()) {
if (inDegree[neighbor] == 0) {
if (order.size() == numCourses) {
}
Optimized (C++):
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> adj(numCourses);
adj[p[1]].push_back(p[0]);
queue<int> q;
if (inDegree[i] == 0) {
vector<int> order;
while (!q.empty()) {
if (inDegree[neighbor] == 0) {
q.push(neighbor); // Add to queue if no more prerequisites
Optimized (Java):
adj.add(new ArrayList<>());
adj.get(p[1]).add(p[0]);
if (inDegree[i] == 0) {
while (!q.isEmpty()) {
if (inDegree[neighbor] == 0) {
if (order.size() == numCourses) {
return order.stream().mapToInt(i -> i).toArray(); // Convert to int array
}
BIT MANIPULATION
C++:
```cpp
#include <bits/stdc++.h>
while (n) {
count += n & 1;
n >>= 1;
return count;
int main()
{
int i = 9;
return 0;
}
JAVA:
import java.io.*;
class countSetBits {
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
return count;
int i = 9;
System.out.println(countSetBits(i));
Power of Two
C++:
class Solution {
public:
bool isPowerOfTwo(int n) {
int x =1;
while(x<=n){
if(x==n)return true;
x = x<<1;
return false;
};
JAVA:
int x = 1;
while (x <= n) {
if (x == n) return true;
x = x << 1;
return false;
Single Number
C++:
class Solution {
public:
int ans=0;
for(auto i:nums){
ans^=i;
}
return ans;
};
JAVA:
import java.util.List;
class Solution {
public int singleNumber(List<Integer> nums) {
int ans = 0;
ans ^= num;
return ans;
C++:
```cpp
#include <bits/stdc++.h>
int isPowerOfTwo(unsigned n) {
if (!isPowerOfTwo(n))
return -1;
unsigned i = 1, pos = 1;
++pos;
return pos;
int main(void) {
int n = 16;
(pos == -1)
? cout << "n = " << n << ", Invalid number" << endl
: cout << "n = " << n << ", Position " << pos << endl;
n = 12;
pos = findPosition(n);
(pos == -1)
? cout << "n = " << n << ", Invalid number" << endl
: cout << "n = " << n << ", Position " << pos << endl;
n = 128;
pos = findPosition(n);
(pos == -1)
? cout << "n = " << n << ", Invalid number" << endl
: cout << "n = " << n << ", Position " << pos << endl;
return 0;
JAVA:
```java
class GFG {
if (!isPowerOfTwo(n))
return -1;
int i = 1, pos = 1;
i = i << 1;
++pos;
}
return pos;
int n = 16;
if (pos == -1)
n = 12;
pos = findPosition(n);
if (pos == -1)
else
n = 128;
pos = findPosition(n);
if (pos == -1)
else
C++:
#include <iostream>
using namespace std;
class Solution {
public:
int count = 0;
while (xorValue) {
return count;
};
int main() {
Solution sol;
cout << "Number of bits to flip to convert " << A << " to " << B << ": " <<
sol.countBitsToFlip(A, B) << endl;
return 0;
}
JAVA:
while (xorValue != 0) {
return count;
C++:
#include <vector>
#include <climits>
#include <iostream>
// Check if n is
// congruent to 1 modulo 4
if(n%4 == 1){
return 1;
// Check if n is congruent
// to 2 modulo 4
return n+1;
// Check if n is
// congruent to 3 modulo 4
return 0;
// Return condition
// when n is a multiple
else{
return n;
int main() {
int L = 3;
int R = 19;
cout << " to " << R << ": "<< ans << endl;
return 0;
JAVA:
// Check if n is
// congruent to 1 modulo 4
if (n % 4 == 1) {
return 1;
// Check if n is congruent
// to 2 modulo 4
else if (n % 4 == 2) {
return n + 1;
}
// Check if n is
// congruent to 3 modulo 4
else if (n % 4 == 3) {
return 0;
// Return condition
// when n is a multiple
else {
return n;
int L = 3;
int R = 19;
#include <bits/stdc++.h>
int square(int n)
{
// Base case
if (n == 0)
return 0;
if (n < 0)
n = -n;
int x = n >> 1;
// If n is odd
if (n & 1)
else // If n is even
// Driver Code
int main()
// Function calls
cout << "n = " << n << ", n^2 = " << square(n)
<< endl;
return 0;
}
JAVA:
// bitwise operators
class GFG {
// Base case
if (n == 0)
return 0;
// right shift
int x = n >> 1;
// If n is odd
;
if (n % 2 != 0)
else // If n is even
// Driver code
// Function calls
System.out.println("n = " + n
Divide two integers without using multiplication, division and mod operator
C++:
#include <limits.h>
// Handle overflow
return INT_MAX;
a = abs(a);
b = abs(b);
a -= (b << i);
int main() {
return 0;
}
JAVA:
class GfG {
// Handle overflow
a = Math.abs(a);
b = Math.abs(b);
long quotient = 0;
a -= (b << i);
Subsets
C++:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int n=nums.size();
int Mask=1<<n;
vector<vector<int>> powerSet(Mask);
powerSet[m].reserve(popcount(m));
if (m& 1<<i)
powerSet[m].push_back(nums[i]);
return powerSet;
};
JAVA:
import java.util.ArrayList;
import java.util.List;
class Solution {
int n = nums.length;
int mask = 1 << n; // Total number of subsets
List<List<Integer>> powerSet = new ArrayList<>(mask);
powerSet.add(new ArrayList<>());
powerSet.get(m).add(nums[i]);
return powerSet;
System.out.println(subset);
}
}
}
Count Primes
C++:
class Solution {
public:
int countPrimes(int n) {
vector<bool> prime(n+1,true);
for(int i=2;i*i<=n;i++){
if(prime[i]){
prime[j]=false;
int cnt=0;
for(int i=2;i<n;i++){
if(prime[i]==true) cnt++;
}
return cnt;
}
};
JAVA:
class Solution {
if (prime[i]) {
int count = 0;
if (prime[i]) {
}
}
return count; // Return the count of primes
}
BINARY SEARCH
Binary Search
C++:
class Solution {
public:
int low = 0;
if (nums[mid] == target) {
return mid;
else
high = mid - 1;
return -1;
}
};
JAVA:
class Solution {
if (nums[mid] == target) {
return mid;
left = mid + 1;
else {
right = mid - 1;
return -1;
}
}
C++:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left = 0;
if (nums[mid] == target) {
return mid;
right = mid - 1;
} else {
left = mid + 1;
return left;
};
JAVA:
class Solution {
int left = 0;
int right = nums.length - 1;
if (nums[mid] == target) {
return mid;
right = mid - 1;
} else {
left = mid + 1;
return left;
Sqrt(x) USING BS
C++:
class Solution {
public:
int mySqrt(int x) {
if (x == 0 || x == 1)
return x;
int start = 1;
int end = x;
// Calculate the middle point using "start + (end - start) / 2" to avoid integer
overflow.
mid = start + (end - start) / 2;
// If the square of the middle value is greater than x, move the "end" to the left
(mid - 1).
if (square > x)
end = mid - 1;
else if (square == x)
// If the square of the middle value is equal to x, we found the square root.
return mid;
else
// If the square of the middle value is less than x, move the "start" to the
right (mid + 1).
start = mid + 1;
// The loop ends when "start" becomes greater than "end", and "end" is the
integer value of the square root.
// However, since we might have been using integer division in the calculations,
// we round down the value of "end" to the nearest integer to get the correct
square root.
return static_cast<int>(std::round(end));
};
JAVA:
class Solution {
return x;
int start = 1;
int end = x;
// Calculate the middle point using "start + (end - start) / 2" to avoid integer
overflow.
// If the square of the middle value is greater than x, move the "end" to the left
(mid - 1).
end = mid - 1;
return mid;
else
// If the square of the middle value is less than x, move the "start" to the
right (mid + 1).
start = mid + 1;
// The loop ends when "start" becomes greater than "end", and "end" is the
integer value of the square root.
// However, since we might have been using integer division in the calculations,
// we round down the value of "end" to the nearest integer to get the correct
square root.
return Math.round(end);
}
class Solution {
public:
int left = 0;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] >= nums[left]) {
right = mid - 1;
} else {
left = mid + 1;
} else {
} else {
right = mid - 1;
}
return -1;
};
JAVA:
class Solution {
int left = 0;
if (nums[mid] == target) {
return mid;
right = mid - 1;
} else {
left = mid + 1;
}
} else {
left = mid + 1;
} else {
right = mid - 1;
}
return -1;
class Solution {
public:
result[0] = left;
result[1] = right;
return result;
int left = 0;
right = mid - 1;
left = mid + 1;
} else {
idx = mid;
if (isSearchingLeft) {
right = mid - 1;
} else {
left = mid + 1;
return idx;
};
JAVA:
class Solution {
result[1] = right;
return result;
left = mid + 1;
} else {
idx = mid;
if (isSearchingLeft) {
right = mid - 1;
} else {
left = mid + 1;
return idx;
class Solution
{
public:
int r = nums.size() - 1;
while (l <= r)
break;
int mid = l + (r - l) / 2;
res = min(res, nums[mid]);
{
l = mid + 1; // try to move closer to right sorted array
}
else
r = mid - 1;
};
JAVA:
class Solution {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
break;
} else {
r = mid - 1;
}
System.out.println("The minimum value in the rotated sorted array is: " + result);
class Solution {
int start = 0;
end = mid;
else{
}
}
return start;
}
JAVA:
class Solution {
int start = 0;
} else {
}
}
// When start == end, we've found the peak element
return start;
Search a 2D Matrix
C++:
class Solution {
public:
int top = 0;
break;
} else if (matrix[mid][0] > target) {
bot = mid - 1;
} else {
top = mid + 1;
int left = 0;
if (matrix[row][mid] == target) {
return true;
right = mid - 1;
} else {
left = mid + 1;
return false;
};
JAVA:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int top = 0;
break;
} else if (matrix[mid][0] > target) {
bot = mid - 1;
} else {
top = mid + 1;
int left = 0;
if (matrix[row][mid] == target) {
return true;
right = mid - 1;
} else {
left = mid + 1;
}
return false;
C++:
class Solution {
public:
int n = mat.size();
int m = mat[0].size();
int maxRow = 0;
maxRow = row;
}
high = midCol - 1;
else{
low = midCol + 1;
}
}
};
JAVA:
class Solution {
int n = mat.length;
int m = mat[0].length;
int maxRow = 0;
maxRow = row;
}
}
int currElement = mat[maxRow][midCol];
high = midCol - 1;
} else {
low = midCol + 1;
}
C++:
class Solution {
public:
hi = mid - 1;
id = mid;
else lo = mid + 1;
return id;
};
JAVA:
class Solution {
else {
++cnt;
curr = v[i];
}
}
return cnt <= d;
id = mid;
} else {
lo = mid + 1;
return id;
#include <iostream>
int total = 0;
total += arr[i];
return total;
// base cases
if (k == 1) // one partition
if (n == 1) // one board
return arr[0];
sum(arr, i, n - 1)));
return best;
}
int main()
int k = 3;
return 0;
}
JAVA:
import java.io.*;
import java.util.*;
class GFG {
// in array
int total = 0;
return total;
// base cases
if (k == 1) // one partition
if (n == 1) // one board
return arr[0];
// partition
best = Math.min(
sum(arr, i, n - 1)));
return best;
// Driver code
public static void main(String args[])
System.out.println(partition(arr, n, k));
C++:
#include <bits/stdc++.h>
int cnt = 0;
numberInBetween--;
cnt += numberInBetween;
return cnt;
if (cnt > k) {
low = mid;
else {
high = mid;
return high;
int main()
cout << "The answer is: " << ans << "\n";
return 0;
}
JAVA:
import java.util.*;
int cnt = 0;
numberInBetween--;
cnt += numberInBetween;
return cnt;
double low = 0;
double high = 0;
if (cnt > k) {
low = mid;
} else {
high = mid;
}
}
return high;
int k = 4;
Allocate Books
C++:
#include <bits/stdc++.h>
int students = 1;
pagesStudent += arr[i];
}
else {
students++;
pagesStudent = arr[i];
return students;
if (students > m) {
low = mid + 1;
}
else {
high = mid - 1;
return low;
int main()
int n = 5;
int m = 4;
cout << "The answer is: " << ans << "\n";
return 0;
JAVA:
import java.util.*;
int students = 1;
long pagesStudent = 0;
for (int i = 0; i < n; i++) {
pagesStudent += arr.get(i);
} else {
students++;
pagesStudent = arr.get(i);
}
return students;
if (m > n)
return -1;
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
int n = 5;
int m = 4;
Aggressive Cows
C++:
#include <bits/stdc++.h>
return false;
sort(stalls.begin(), stalls.end());
low = mid + 1;
return high;
int main()
{
vector<int> stalls = {0, 3, 4, 7, 10, 9};
int k = 4;
cout << "The maximum possible minimum distance is: " << ans << "\n";
return 0;
}
JAVA:
import java.util.*;
return false;
Arrays.sort(stalls);
low = mid + 1;
} else high = mid - 1;
}
return high;
int k = 4;