0% found this document useful (0 votes)
27 views

Coding Questions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Coding Questions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

1.

Problem: Longest Substring Without Repeating


Characters
Definition:

Given a string s, find the length of the longest substring without repeating characters.

Example:

1. Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length
of 3.
2. Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
3. Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length
of 3. Notice that the answer must be a substring, "kew" is a subsequence and not
a substring.

C++ Solution:

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int lengthOfLongestSubstring(string s) {
unordered_map<char, int> charIndex;
int start = 0, maxLength = 0;

for (int end = 0; end < s.length(); ++end) {


if (charIndex.find(s[end]) != charIndex.end()) {
start = max(start, charIndex[s[end]] + 1);
}
charIndex[s[end]] = end;
maxLength = max(maxLength, end - start + 1);
}

return maxLength;
}

int main() {
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl; // Output: 3
return 0;
}
Python Solution:

def length_of_longest_substring(s):
char_index = {}
start = 0
max_length = 0

for end, char in enumerate(s):


if char in char_index:
start = max(start, char_index[char] + 1)
char_index[char] = end
max_length = max(max_length, end - start + 1)

return max_length

s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3

Explanation:

1. Data Structures Used:


● C++: unordered_map to keep track of the most recent index of each
character.
● Python: Dictionary to achieve the same goal.
2. Algorithm:
● We maintain two pointers, start and end, to represent the current window
of characters being examined.
● As we iterate through the string with the end pointer, we check if the
current character has been seen before and is inside the current window
(i.e., its last occurrence is >= start).
● If so, we adjust the start pointer to be one position past the last
occurrence of the character to ensure the substring remains without
duplicates.
● Update the index of the current character in our dictionary.
● Calculate the length of the current window and update max_length if the
current window is longer.

2. Problem: Merge Intervals


Definition:
Given a collection of intervals, merge all overlapping intervals.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: Intervals [1,3] and [2,6] overlap, so they
are merged into [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4]
and [4,5] overlap, so they are merged into [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);

for (const auto& interval : intervals) {


if (interval[0] <= merged.back()[1]) {
merged.back()[1] = max(merged.back()[1], interval[1]);
} else {
merged.push_back(interval);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
vector<vector<int>> result = mergeIntervals(intervals);
for (const auto& interval : result) {
cout << "[" << interval[0] << ", " << interval[1] << "] ";
}
cout << endl;
return 0;
}

Python Solution:
def merge_intervals(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

for interval in intervals[1:]:


if interval[0] <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
merged.append(interval)

return merged

intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]


print(merge_intervals(intervals))

Explanation:

1. Data Structures Used:


● C++: vector for intervals and sorting.
● Python: List for intervals and sorting.
2. Algorithm:
● Sort intervals based on the starting times.
● Initialize merged with the first interval.
● Iterate through the sorted intervals and merge overlapping intervals.
● If the current interval overlaps with the last interval in merged, update the
end of the last interval in merged.
● If not, add the current interval to merged.

3. Problem: Count Inversions in an Array


Definition:

Given an array, count the number of inversions. An inversion is a pair of indices (i, j)
such that i < j and arr[i] > arr[j].

Example:
1. Input: arr = [1, 3, 2, 3, 1] Output: 4 Explanation: The inversions are (1,2),
(1,4), (3,2), (3,4).
2. Input: arr = [5, 4, 3, 2, 1] Output: 10 Explanation: Every pair is an inversion.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int mergeAndCount(vector<int>& arr, vector<int>& temp, int left, int mid, int
right) {
int i = left, j = mid + 1, k = left, inv_count = 0;

while (i <= mid && j <= right) {


if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
inv_count += (mid - i + 1);
}
}

while (i <= mid) temp[k++] = arr[i++];


while (j <= right) temp[k++] = arr[j++];

for (i = left; i <= right; i++) arr[i] = temp[i];

return inv_count;
}

int mergeSortAndCount(vector<int>& arr, vector<int>& temp, int left, int right)


{
int inv_count = 0;
if (left < right) {
int mid = left + (right - left) / 2;

inv_count += mergeSortAndCount(arr, temp, left, mid);


inv_count += mergeSortAndCount(arr, temp, mid + 1, right);
inv_count += mergeAndCount(arr, temp, left, mid, right);
}

return inv_count;
}

int countInversions(vector<int>& arr) {


vector<int> temp(arr.size());
return mergeSortAndCount(arr, temp, 0, arr.size() - 1);
}

int main() {
vector<int> arr = {1, 20, 6, 4, 5};
cout << countInversions(arr) << endl; // Output: 5
return 0;
}

Python Solution:

def merge_and_count(arr, temp_arr, left, mid, right):


i = left # Starting index for left subarray
j = mid + 1 # Starting index for right subarray
k = left # Starting index to be sorted
inv_count = 0

while i <= mid and j <= right:


if arr[i] <= arr[j]:
temp_arr[k] = arr[i]
i += 1
else:
temp_arr[k] = arr[j]
inv_count += (mid-i + 1)
j += 1
k += 1

while i <= mid:

temp_arr[k] = arr[i]
i += 1
k += 1

while j <= right:


temp_arr[k] = arr[j]
j += 1
k += 1

for i in range(left, right + 1):


arr[i] = temp_arr[i]

return inv_count

def merge_sort_and_count(arr, temp_arr, left, right):


inv_count = 0
if left < right:
mid = (left + right) // 2
inv_count += merge_sort_and_count(arr, temp_arr, left, mid)
inv_count += merge_sort_and_count(arr, temp_arr, mid + 1, right)
inv_count += merge_and_count(arr, temp_arr, left, mid, right)

return inv_count

def count_inversions(arr):
temp_arr = [0]*len(arr)
return merge_sort_and_count(arr, temp_arr, 0, len(arr) - 1)

arr = [1, 20, 6, 4, 5]


print(count_inversions(arr)) # Output: 5

Explanation:

1. Data Structures Used:


● C++: vector for arrays.
● Python: List for arrays.
2. Algorithm:
● Use the merge sort algorithm to count inversions.
● During the merge step, count the number of elements in the left subarray
that are greater than the elements in the right subarray.
● This count represents the number of inversions.

Sure! Continuing with more competitive programming questions, including problem


definitions, test cases, solutions, and explanations in both C++ and Python:

4. Problem: Binary Search on a Sorted Array


Definition:

Given a sorted array arr and a target value target, find the index of the target value
using binary search. If the target value is not present, return -1.

Example:

1. Input: arr = [1, 2, 3, 4, 5], target = 3 Output: 2 Explanation: The target


value 3 is at index 2.
2. Input: arr = [1, 2, 3, 4, 5], target = 6 Output: -1 Explanation: The target
value 6 is not present in the array.
C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int binarySearch(const vector<int>& arr, int target) {


int left = 0, right = arr.size() - 1;

while (left <= right) {


int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}

return -1;
}

int main() {
vector<int> arr = {1, 2, 3, 4, 5};
int target = 3;
cout << binarySearch(arr, target) << endl; // Output: 2
return 0;
}

Python Solution:

def binary_search(arr, target):


left, right = 0, len(arr) - 1

while left <= right:


mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1

return -1

arr = [1, 2, 3, 4, 5]
target = 3
print(binary_search(arr, target)) # Output: 2
Explanation:

1. Algorithm:
● Use binary search which operates on a sorted array.
● Adjust the left and right pointers based on comparisons with the middle
element.

5. Problem: Maximum Subarray Sum (Kadane's Algorithm)


Definition:

Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.

Example:

1. Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] Output: 6 Explanation: The


maximum subarray sum is 6 for the subarray [4, -1, 2, 1].
2. Input: nums = [1] Output: 1 Explanation: The maximum subarray sum is 1 for the
subarray [1].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxSubArray(vector<int>& nums) {


int max_so_far = nums[0];
int max_ending_here = nums[0];

for (int i = 1; i < nums.size(); ++i) {


max_ending_here = max(nums[i], max_ending_here + nums[i]);
max_so_far = max(max_so_far, max_ending_here);
}

return max_so_far;
}

int main() {
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << maxSubArray(nums) << endl; // Output: 6
return 0;
}

Python Solution:

def max_subarray(nums):
max_so_far = nums[0]
max_ending_here = nums[0]

for num in nums[1:]:


max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)

return max_so_far

nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]


print(max_subarray(nums)) # Output: 6

Explanation:

1. Algorithm:
● Use Kadane’s Algorithm to find the maximum subarray sum.
● Keep track of the maximum sum ending at the current index and the
global maximum sum.

6. Problem: Find the Kth Largest Element in an Array


Definition:

Given an integer array nums and an integer k, return the kth largest element in the array.

Example:

1. Input: nums = [3, 2, 1, 5, 6, 4], k = 2 Output: 5 Explanation: The 2nd largest


element in the array is 5.
2. Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 Output: 4 Explanation: The
4th largest element in the array is 4.

C++ Solution:
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int findKthLargest(vector<int>& nums, int k) {


priority_queue<int, vector<int>, greater<int>> minHeap;

for (int num : nums) {


minHeap.push(num);
if (minHeap.size() > k) minHeap.pop();
}

return minHeap.top();
}

int main() {
vector<int> nums = {3, 2, 1, 5, 6, 4};
int k = 2;
cout << findKthLargest(nums, k) << endl; // Output: 5
return 0;
}

Python Solution:

import heapq

def find_kth_largest(nums, k):


return heapq.nlargest(k, nums)[-1]

nums = [3, 2, 1, 5, 6, 4]
k = 2
print(find_kth_largest(nums, k)) # Output: 5

Explanation:

1. Algorithm:
● Use a min-heap to keep track of the k largest elements.
● By maintaining the size of the heap at k, the smallest element in the heap
will be the kth largest element in the array.

7. Problem: Rotate an Array


Definition:

Given an array nums and an integer k, rotate the array to the right by k steps.

Example:

1. Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3 Output: [5, 6, 7, 1, 2, 3, 4]


Explanation: Rotate the array [1, 2, 3, 4, 5, 6, 7] to the right by 3 steps.
2. Input: nums = [-1, -100, 3, 99], k = 2 Output: [3, 99, -1, -100] Explanation:
Rotate the array [-1, -100, 3, 99] to the right by 2 steps.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void rotate(vector<int>& nums, int k) {


int n = nums.size();
k = k % n; // In case k is greater than n
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}

int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
rotate(nums, k);
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}

Python Solution:

def rotate(nums, k):


n = len(nums)
k %= n # In case k is greater than n
nums[:] = nums[-k:] + nums[:-k]

nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotate(nums, k)
print(nums) # Output: [5, 6, 7, 1, 2, 3, 4]

Explanation:

1. Algorithm:
● Use array reversal to achieve the rotation.
● Reverse the entire array, then reverse the first k elements and the
remaining elements

separately to get the rotated array.

8. Problem: Merge Two Sorted Lists


Definition:

Given two sorted linked lists, merge them into a single sorted linked list and return it.

Example:

1. Input: l1 = [1, 2, 4], l2 = [1, 3, 4] Output: [1, 1, 2, 3, 4, 4] Explanation:


The merged list is [1, 1, 2, 3, 4, 4].
2. Input: l1 = [], l2 = [0] Output: [0] Explanation: The merged list is [0].

C++ Solution:

#include <iostream>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {


ListNode dummy(0);
ListNode* tail = &dummy;

while (l1 != nullptr && l2 != nullptr) {


if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}

if (l1 != nullptr) tail->next = l1;


if (l2 != nullptr) tail->next = l2;

return dummy.next;
}

int main() {
// Example usage
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(2);
l1->next->next = new ListNode(4);

ListNode* l2 = new ListNode(1);


l2->next = new ListNode(3);
l2->next->next = new ListNode(4);

ListNode* mergedList = mergeTwoLists(l1, l2);


while (mergedList != nullptr) {
cout << mergedList->val << " ";
mergedList = mergedList->next;
}
cout << endl;
return 0;
}

Python Solution:

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def merge_two_lists(l1, l2):


dummy = ListNode()
tail = dummy

while l1 and l2:


if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next

if l1:
tail.next = l1
if l2:
tail.next = l2

return dummy.next

# Example usage
l1 = ListNode(1, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))

merged_list = merge_two_lists(l1, l2)


while merged_list:
print(merged_list.val, end=" ")
merged_list = merged_list.next
print()

Explanation:

1. Algorithm:
● Use a dummy node to simplify the merging process.
● Compare nodes from both lists and append the smaller node to the
merged list.
● After one list is exhausted, append the remaining nodes from the other list.

9. Problem: Find Minimum in Rotated Sorted Array


Definition:

Suppose an array of length n is rotated between 1 and n times. Find the minimum
element in the rotated sorted array.

Example:

1. Input: nums = [3, 4, 5, 1, 2] Output: 1 Explanation: The array is rotated, and


the minimum element is 1.
2. Input: nums = [4, 5, 6, 7, 0, 1, 2] Output: 0 Explanation: The minimum
element is 0.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int findMin(vector<int>& nums) {


int left = 0, right = nums.size() - 1;

while (left < right) {


int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) left = mid + 1;
else right = mid;
}

return nums[left];
}

int main() {
vector<int> nums = {3, 4, 5, 1, 2};
cout << findMin(nums) << endl; // Output: 1
return 0;
}

Python Solution:

def find_min(nums):
left, right = 0, len(nums) - 1

while left < right:


mid = left + (right - left) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid

return nums[left]

nums = [3, 4, 5, 1, 2]
print(find_min(nums)) # Output: 1

Explanation:
1. Algorithm:
● Use binary search to find the pivot where the rotation happened.
● Compare the middle element with the rightmost element to decide which
side of the array to search.

10. Problem: Subarray Sum Equals K


Definition:

Given an integer array nums and an integer k, return the total number of continuous
subarrays whose sum equals to k.

Example:

1. Input: nums = [1, 1, 1], k = 2 Output: 2 Explanation: The subarrays are [1, 1]
and [1, 1].
2. Input: nums = [1, 2, 3], k = 3 Output: 2 Explanation: The subarrays are [1, 2]
and [3].

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

int subarraySum(vector<int>& nums, int k) {


unordered_map<int, int> prefixSum;
int sum = 0, count = 0;
prefixSum[0] = 1;

for (int num : nums) {


sum += num;
if (prefixSum.find(sum - k) != prefixSum.end()) {
count += prefixSum[sum - k];
}
prefixSum[sum]++;
}

return count;
}

int main() {
vector<int> nums = {1, 1, 1};
int k = 2;
cout << subarraySum(nums, k) << endl; // Output: 2
return 0;
}

Python Solution:

from collections import defaultdict

def subarray_sum(nums, k):


prefix_sum = defaultdict(int)
sum = 0
count = 0
prefix_sum[0] = 1

for num in nums:


sum += num
if (sum - k) in prefix_sum:
count += prefix_sum[sum - k]
prefix_sum[sum] += 1

return count

nums = [1, 1, 1]
k = 2
print(subarray_sum(nums, k)) # Output: 2

Explanation:

1. Algorithm:
● Use a hash map to keep track of prefix sums.
● For each element, calculate the current prefix sum.
● Check if there exists a prefix sum such that the difference is equal to k.

Sure, continuing with more competitive programming problems, including problem


definitions, test cases, solutions, and explanations in both C++ and Python:

11. Problem: Longest Common Prefix


Definition:
Write a function to find the longest common prefix string amongst an array of strings. If
there is no common prefix, return an empty string.

Example:

1. Input: strs = ["flower","flow","flight"] Output: "fl" Explanation: The longest


common prefix is "fl".
2. Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no
common prefix.

C++ Solution:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

string longestCommonPrefix(vector<string>& strs) {


if (strs.empty()) return "";

string prefix = strs[0];

for (int i = 1; i < strs.size(); ++i) {


while (strs[i].find(prefix) != 0) {
prefix = prefix.substr(0, prefix.size() - 1);
if (prefix.empty()) return "";
}
}

return prefix;
}

int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << longestCommonPrefix(strs) << endl; // Output: "fl"
return 0;
}

Python Solution:

def longest_common_prefix(strs):
if not strs:
return ""

prefix = strs[0]
for string in strs[1:]:
while not string.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""

return prefix

strs = ["flower", "flow", "flight"]


print(longest_common_prefix(strs)) # Output: "fl"

Explanation:

1. Algorithm:
● Compare the prefix of the first string with other strings in the array.
● Reduce the prefix until it matches all strings or becomes empty.

12. Problem: Valid Parentheses


Definition:

Given a string containing just the characters '(', ')', '{', '}', '[', and ']', determine
if the input string is valid. An input string is valid if the brackets are closed in the correct
order.

Example:

1. Input: "()[]{}" Output: True Explanation: The string is valid.


2. Input: "(]" Output: False Explanation: The string is invalid.

C++ Solution:

#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;

bool isValid(string s) {
stack<char> st;
unordered_map<char, char> matching = {{')', '('}, {']', '['}, {'}', '{'}};
for (char c : s) {
if (matching.find(c) != matching.end()) {
if (st.empty() || st.top() != matching[c]) return false;
st.pop();
} else {
st.push(c);
}
}

return st.empty();
}

int main() {
string s = "()[]{}";
cout << boolalpha << isValid(s) << endl; // Output: true
return 0;
}

Python Solution:

def is_valid(s):
stack = []
matching = {')': '(', ']': '[', '}': '{'}

for char in s:
if char in matching:
if not stack or stack[-1] != matching[char]:
return False
stack.pop()
else:
stack.append(char)

return not stack

s = "()[]{}"
print(is_valid(s)) # Output: True

Explanation:

1. Algorithm:
● Use a stack to keep track of opening brackets.
● For each closing bracket, check if it matches the top of the stack.
● Ensure that the stack is empty at the end to confirm all brackets are
matched.
13. Problem: Merge Intervals
Definition:

Given an array of intervals where intervals[i] = [start_i, end_i], merge all


overlapping intervals and return an array of the non-overlapping intervals that cover all
the intervals in the input.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: The intervals [1,3] and [2,6] overlap, so
they are merged into [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: The intervals
[1,4] and [4,5] overlap, so they are merged into [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;

for (const auto& interval : intervals) {


if (merged.empty() || merged.back()[1] < interval[0]) {
merged.push_back(interval);
} else {
merged.back()[1] = max(merged.back()[1], interval[1]);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1,3}, {2,6}, {8,10}, {15,18}};
vector<vector<int>> result = merge(intervals);

for (const auto& interval : result) {


cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;
return 0;
}

Python Solution:

def merge(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = []

for interval in intervals:


if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])

return merged

intervals = [[1,3], [2,6], [8,10], [15,18]]


print(merge(intervals)) # Output: [[1, 6], [8, 10], [15, 18]]

Explanation:

1. Algorithm:
● Sort intervals by the start time.
● Merge overlapping intervals by comparing the end of the current interval
with the start of the next.

14. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image. Rotate the image by 90


degrees (clockwise).

Example:
1. Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]
Explanation: The matrix is rotated by 90 degrees clockwise.
2. Input: matrix = [[ 5, 1, 9,11],[ 2, 4, 8,10],[13, 3, 6, 7],[15,14,12,16]]
Output: [[15,13, 2, 5],[14, 3, 4, 1],[12, 6, 8, 9],[16, 7,10,11]]
Explanation: The matrix is rotated by 90 degrees clockwise.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
for (auto& row : matrix) {
reverse(row.begin(), row.end());
}
}

int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);

for (const auto& row : matrix) {


for (int num : row) {
cout << num << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

def rotate(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate(matrix)
print(matrix) # Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3

]]

Explanation:

1. Algorithm:
● Transpose the matrix by swapping elements across the diagonal.
● Reverse each row to complete the rotation.

15. Problem: Top K Frequent Elements


Definition:

Given an integer array nums and an integer k, return the k most frequent elements. You
may assume that the answer is guaranteed to be unique.

Example:

1. Input: nums = [1,1,1,2,2,3], k = 2 Output: [1, 2] Explanation: The top 2


frequent elements are 1 and 2.
2. Input: nums = [1], k = 1 Output: [1] Explanation: The top 1 frequent element is
1.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>

using namespace std;

vector<int> topKFrequent(vector<int>& nums, int k) {


unordered_map<int, int> count;
for (int num : nums) {
count[num]++;
}

auto cmp = [](pair<int, int>& a, pair<int, int>& b) {


return a.second < b.second;
};

priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)>


pq(cmp);

for (auto& entry : count) {


pq.push(entry);
}

vector<int> result;
while (k-- > 0) {
result.push_back(pq.top().first);
pq.pop();
}

return result;
}

int main() {
vector<int> nums = {1, 1, 1, 2, 2, 3};
int k = 2;
vector<int> result = topKFrequent(nums, k);

for (int num : result) {


cout << num << " ";
}
cout << endl;
return 0;
}

Python Solution:

from collections import Counter


import heapq

def top_k_frequent(nums, k):


count = Counter(nums)
return [item for item, _ in heapq.nlargest(k, count.items(), key=lambda x:
x[1])]

nums = [1, 1, 1, 2, 2, 3]
k = 2
print(top_k_frequent(nums, k)) # Output: [1, 2]
Explanation:

1. Algorithm:
● Count the frequency of each element.
● Use a max heap to extract the top k frequent elements.

16. Problem: Rotate Array


Definition:

Given an array nums and an integer k, rotate the array to the right by k steps, where k is
non-negative.

Example:

1. Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: The


array is rotated to the right by 3 steps.
2. Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: The
array is rotated to the right by 2 steps.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void rotate(vector<int>& nums, int k) {


k %= nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}

int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
rotate(nums, k);

for (int num : nums) {


cout << num << " ";
}
cout << endl;
return 0;
}

Python Solution:

def rotate(nums, k):


k %= len(nums)
nums.reverse()
nums[:k] = reversed(nums[:k])
nums[k:] = reversed(nums[k:])

nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotate(nums, k)
print(nums) # Output: [5, 6, 7, 1, 2, 3, 4]

Explanation:

1. Algorithm:
● Reverse the entire array.
● Reverse the first k elements and then reverse the rest.

17. Problem: Product of Array Except Self


Definition:

Given an integer array nums, return an array answer such that answer[i] is equal to the
product of all the elements of nums except nums[i].

Example:

1. Input: [1,2,3,4] Output: [24,12,8,6] Explanation: The product of all numbers


except the number at each index is [24, 12, 8, 6].
2. Input: [-1,1,0,3] Output: [0,0,3,-1] Explanation: The product of all numbers
except the number at each index is [0, 0, 3, -1].

C++ Solution:
#include <iostream>
#include <vector>

using namespace std;

vector<int> productExceptSelf(vector<int>& nums) {


int n = nums.size();
vector<int> result(n, 1);

int left = 1;
for (int i = 0; i < n; ++i) {
result[i] *= left;
left *= nums[i];
}

int right = 1;
for (int i = n - 1; i >= 0; --i) {
result[i] *= right;
right *= nums[i];
}

return result;
}

int main() {
vector<int> nums = {1, 2, 3, 4};
vector<int> result = productExceptSelf(nums);

for (int num : result) {


cout << num << " ";
}
cout << endl;
return 0;
}

Python Solution:

def product_except_self(nums):
n = len(nums)
result = [1] * n

left = 1
for i in range(n):
result[i] *= left
left *= nums[i]

right = 1
for i in range(n-1, -1, -1):
result[i] *= right
right *= nums[i]

return result

nums = [1, 2, 3, 4]
print(product_except_self(nums)) # Output: [24, 12, 8, 6]

Explanation:

1. Algorithm:
● Calculate the product of elements to the left of each index.
● Calculate the product of elements to the right of each index.
● Multiply both products for each index.

18. Problem: Find the Duplicate Number


Definition:

Given an array nums containing n + 1 integers where each integer is between 1 and n
(inclusive), prove that there is only one duplicate number in the array. Find and return
this duplicate number.

Example:

1. Input: [1,3,4,2,2] Output: 2 Explanation: The duplicate number is 2.


2. Input: [3,1,3,4,2] Output: 3 Explanation: The duplicate number is 3.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int findDuplicate(vector<int>& nums) {


int slow = nums[0], fast = nums[0];

do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}

return slow;
}

int main() {
vector<int> nums = {1, 3, 4, 2, 2};
cout << findDuplicate(nums) << endl; // Output: 2
return 0;
}

Python Solution:

def find_duplicate(nums):
slow = nums[0]
fast = nums[0]

while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break

slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]

return slow

nums = [1, 3, 4, 2, 2]
print(find_duplicate(nums)) # Output: 2

Explanation:

1. Algorithm:
● Use Floyd's Tortoise and Hare algorithm to find the intersection point in the
cycle
Sure, let's start with questions from Striver's sheet. Here are some
competitive programming problems based on the Striver's SDE Sheet,
including problem definitions, test cases, solutions, and explanations in
both C++ and Python.

19. Problem: Two Sum


Definition:

Given an array of integers nums and an integer target, return indices of the two numbers
such that they add up to target.

Example:

1. Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because


nums[0] + nums[1] == 9, we return [0, 1].
2. Input: nums = [3,2,4], target = 6 Output: [1,2] Explanation: Because nums[1]
+ nums[2] == 6, we return [1, 2].

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {


unordered_map<int, int> map;
vector<int> result;

for (int i = 0; i < nums.size(); ++i) {


int complement = target - nums[i];
if (map.find(complement) != map.end()) {
result.push_back(map[complement]);
result.push_back(i);
return result;
}
map[nums[i]] = i;
}

return result;
}

int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> result = twoSum(nums, target);

for (int index : result) {


cout << index << " ";
}
cout << endl;
return 0;
}

Python Solution:

def two_sum(nums, target):


num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i

nums = [2, 7, 11, 15]


target = 9
print(two_sum(nums, target)) # Output: [0, 1]

Explanation:

1. Algorithm:
● Use a hash map to store the indices of the elements.
● For each element, check if its complement (target - element) exists in the
map.
● Return the indices if found.

20. Problem: 3 Sum


Definition:

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such
that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Example:
1. Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: The
triplets that sum to zero are [-1,-1,2] and [-1,0,1].
2. Input: nums = [0,1,1] Output: [] Explanation: No triplets sum to zero.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {


sort(nums.begin(), nums.end());
vector<vector<int>> result;

for (int i = 0; i < nums.size(); ++i) {


if (i > 0 && nums[i] == nums[i - 1]) continue;

int left = i + 1, right = nums.size() - 1;


while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) ++left;
while (left < right && nums[right] == nums[right - 1]) --right;
++left;
--right;
} else if (sum < 0) {
++left;
} else {
--right;
}
}
}

return result;
}

int main() {
vector<int> nums = {-1, 0, 1, 2, -1, -4};
vector<vector<int>> result = threeSum(nums);

for (const auto& triplet : result) {


for (int num : triplet) {
cout << num << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue

left, right = i + 1, len(nums) - 1


while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif total < 0:
left += 1
else:
right -= 1

return result

nums = [-1, 0, 1, 2, -1, -4]


print(three_sum(nums)) # Output: [[-1, -1, 2], [-1, 0, 1]]

Explanation:

1. Algorithm:
● Sort the array to facilitate finding triplets.
● Use a fixed element and apply a two-pointer approach to find pairs that
sum up to the negative of the fixed element.

21. Problem: Container With Most Water


Definition:
You are given an integer array height where height[i] represents the height of a
vertical line at index i. Find two lines that together with the x-axis form a container that
can hold the most water.

Example:

1. Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The maximum area


of water that can be contained is 49.
2. Input: height = [1,1] Output: 1 Explanation: The maximum area of water that
can be contained is 1.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int maxArea(vector<int>& height) {


int left = 0, right = height.size() - 1;
int max_area = 0;

while (left < right) {


int width = right - left;
int area = min(height[left], height[right]) * width;
max_area = max(max_area, area);

if (height[left] < height[right]) {


++left;
} else {
--right;
}
}

return max_area;
}

int main() {
vector<int> height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
cout << maxArea(height) << endl; // Output: 49
return 0;
}

Python Solution:

def max_area(height):
left, right = 0, len(height) - 1
max_area = 0

while left < right:


width = right - left
area = min(height[left], height[right]) * width
max_area = max(max_area, area)

if height[left] < height[right]:


left += 1
else:
right -= 1

return max_area

height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(max_area(height)) # Output: 49

Explanation:

1. Algorithm:
● Use two pointers to find the maximum area between any two lines.
● Calculate area and update maximum area based on the minimum height
between the two lines.

22. Problem: 4 Sum


Definition:

Given an array nums of n integers, return all the unique quadruplets [nums[a], nums[b],
nums[c], nums[d]] such that a, b, c, and d are distinct indices and nums[a] + nums[b] +
nums[c] + nums[d] == target.

Example:

1. Input: nums = [1,0,-1,0,-2,2], target = 0 Output:


[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] **

Explanation:** The quadruplets that sum to the target are [-2,-1,1,2], [-2,0,0,2], and
[-1,0,0,1].
2. Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]] Explanation: The
only quadruplet that sums to the target is [2,2,2,2].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> fourSum(vector<int>& nums, int target) {


sort(nums.begin(), nums.end());
vector<vector<int>> result;
int n = nums.size();

for (int i = 0; i < n - 3; ++i) {


if (i > 0 && nums[i] == nums[i - 1]) continue;

for (int j = i + 1; j < n - 2; ++j) {


if (j > i + 1 && nums[j] == nums[j - 1]) continue;

int left = j + 1, right = n - 1;


while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.push_back({nums[i], nums[j], nums[left],
nums[right]});
while (left < right && nums[left] == nums[left + 1])
++left;
while (left < right && nums[right] == nums[right - 1])
--right;
++left;
--right;
} else if (sum < target) {
++left;
} else {
--right;
}
}
}
}

return result;
}

int main() {
vector<int> nums = {1, 0, -1, 0, -2, 2};
int target = 0;
vector<vector<int>> result = fourSum(nums, target);

for (const auto& quad : result) {


for (int num : quad) {
cout << num << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

def four_sum(nums, target):


nums.sort()
result = []
n = len(nums)

for i in range(n - 3):


if i > 0 and nums[i] == nums[i - 1]:
continue

for j in range(i + 1, n - 2):


if j > i + 1 and nums[j] == nums[j - 1]:
continue

left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif total < target:
left += 1
else:
right -= 1

return result

nums = [1, 0, -1, 0, -2, 2]


target = 0
print(four_sum(nums, target)) # Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0,
0, 1]]
Explanation:

1. Algorithm:
● Sort the array to use a two-pointer approach for finding quadruplets.
● Fix two numbers and use two pointers to find the other two numbers that
complete the quadruplet.

23. Problem: Subarray Sum Equals K


Definition:

Given an array of integers nums and an integer k, return the total number of continuous
subarrays whose sum equals k.

Example:

1. Input: nums = [1,1,1], k = 2 Output: 2 Explanation: The subarrays [1,1] and


[1,1] sum up to 2.
2. Input: nums = [1,2,3], k = 3 Output: 2 Explanation: The subarrays [1,2] and
[3] sum up to 3.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

int subarraySum(vector<int>& nums, int k) {


unordered_map<int, int> prefix_sum_count;
prefix_sum_count[0] = 1;
int prefix_sum = 0, count = 0;

for (int num : nums) {


prefix_sum += num;
if (prefix_sum_count.find(prefix_sum - k) != prefix_sum_count.end()) {
count += prefix_sum_count[prefix_sum - k];
}
prefix_sum_count[prefix_sum]++;
}
return count;
}

int main() {
vector<int> nums = {1, 1, 1};
int k = 2;
cout << subarraySum(nums, k) << endl; // Output: 2
return 0;
}

Python Solution:

def subarray_sum(nums, k):


prefix_sum_count = {0: 1}
prefix_sum = 0
count = 0

for num in nums:


prefix_sum += num
if prefix_sum - k in prefix_sum_count:
count += prefix_sum_count[prefix_sum - k]
prefix_sum_count[prefix_sum] = prefix_sum_count.get(prefix_sum, 0) + 1

return count

nums = [1, 1, 1]
k = 2
print(subarray_sum(nums, k)) # Output: 2

Explanation:

1. Algorithm:
● Use a hash map to store the count of prefix sums.
● For each prefix sum, check if there is a previously seen prefix sum that,
when subtracted, equals k.
● Update the count of subarrays that sum up to k.

Certainly! Continuing with Striver's sheet problems, let's cover more competitive
programming problems with definitions, test cases, solutions, and explanations in both
C++ and Python.
24. Problem: Maximum Subarray
Definition:

Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.

Example:

1. Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray


[4,-1,2,1] has the largest sum 6.
2. Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int maxSubArray(vector<int>& nums) {


int max_sum = nums[0];
int current_sum = nums[0];

for (int i = 1; i < nums.size(); ++i) {


current_sum = max(nums[i], current_sum + nums[i]);
max_sum = max(max_sum, current_sum);
}

return max_sum;
}

int main() {
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << maxSubArray(nums) << endl; // Output: 6
return 0;
}

Python Solution:

def max_subarray(nums):
max_sum = current_sum = nums[0]

for num in nums[1:]:


current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum

nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]


print(max_subarray(nums)) # Output: 6

Explanation:

1. Algorithm:
● Use Kadane’s algorithm to find the maximum sum subarray.
● Maintain the maximum sum and the current sum as you iterate through
the array.

25. Problem: Longest Substring Without Repeating


Characters
Definition:

Given a string s, find the length of the longest substring without repeating characters.

Example:

1. Input: s = "abcabcbb" Output: 3 Explanation: The longest substring without


repeating characters is "abc", which its length is 3.
2. Input: s = "bbbbb" Output: 1 Explanation: The longest substring without repeating
characters is "b", with length 1.

C++ Solution:

#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int lengthOfLongestSubstring(string s) {
unordered_set<char> char_set;
int left = 0, max_length = 0;

for (int right = 0; right < s.size(); ++right) {


while (char_set.find(s[right]) != char_set.end()) {
char_set.erase(s[left]);
++left;
}
char_set.insert(s[right]);
max_length = max(max_length, right - left + 1);
}

return max_length;
}

int main() {
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl; // Output: 3
return 0;
}

Python Solution:

def length_of_longest_substring(s):
char_set = set()
left = 0
max_length = 0

for right in range(len(s)):


while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)

return max_length

s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3

Explanation:

1. Algorithm:
● Use the sliding window technique with a set to track unique characters.
● Move the left pointer to remove characters when a duplicate is found.

26. Problem: Merge Intervals


Definition:
Given an array of intervals where intervals[i] = [start, end], merge all overlapping
intervals.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap,
they are merged into [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4]
and [4,5] overlap and are merged into [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());
vector<vector<int>> merged = {intervals[0]};

for (int i = 1; i < intervals.size(); ++i) {


if (merged.back()[1] >= intervals[i][0]) {
merged.back()[1] = max(merged.back()[1], intervals[i][1]);
} else {
merged.push_back(intervals[i]);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
vector<vector<int>> result = mergeIntervals(intervals);

for (const auto& interval : result) {


cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;
return 0;
}
Python Solution:

def merge_intervals(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

for interval in intervals[1:]:


if merged[-1][1] >= interval[0]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
merged.append(interval)

return merged

intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]


print(merge_intervals(intervals)) # Output: [[1, 6], [8, 10], [15, 18]]

Explanation:

1. Algorithm:
● Sort intervals based on the start times.
● Merge intervals if they overlap; otherwise, add the interval as a new entry.

27. Problem: Search in Rotated Sorted Array


Definition:

You are given a rotated sorted array nums of unique elements and an integer target.
Search for the target in the array and return its index.

Example:

1. Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Explanation: The index of


0 in the rotated array is 4.
2. Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Explanation: The target 3
is not present in the array.

C++ Solution:
#include <iostream>
#include <vector>

using namespace std;

int search(vector<int>& nums, int target) {


int left = 0, right = nums.size() - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (nums[mid] == target) return mid;

if (nums[left] <= nums[mid]) {


if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}

return -1;
}

int main() {
vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
int target = 0;
cout << search(nums, target) << endl; // Output: 4
return 0;
}

Python Solution:

def search(nums, target):


left, right = 0, len(nums) - 1

while left <= right:


mid = left + (right - left) // 2

if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid -

1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1

return -1

nums = [4, 5, 6, 7, 0, 1, 2]
target = 0
print(search(nums, target)) # Output: 4

Explanation:

1. Algorithm:
● Use modified binary search to handle the rotated array.
● Determine which part of the array is sorted and adjust the search range
accordingly.

28. Problem: Container With Most Water


Definition:

You are given an integer array height where height[i] represents the height of a
vertical line at index i. Find two lines which together with the x-axis forms a container,
such that the container contains the most water.

Example:

1. Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The container with


the most water is formed by lines at indices 1 and 8, which has a width of 7 and a
height of 7, yielding a container with area 49.
2. Input: height = [1,1] Output: 1 Explanation: The only possible container is
between the two lines, which has an area of 1.
C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxArea(vector<int>& height) {


int left = 0, right = height.size() - 1;
int max_area = 0;

while (left < right) {


int width = right - left;
int min_height = min(height[left], height[right]);
max_area = max(max_area, width * min_height);

if (height[left] < height[right]) {


++left;
} else {
--right;
}
}

return max_area;
}

int main() {
vector<int> height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
cout << maxArea(height) << endl; // Output: 49
return 0;
}

Python Solution:

def max_area(height):
left, right = 0, len(height) - 1
max_area = 0

while left < right:


width = right - left
min_height = min(height[left], height[right])
max_area = max(max_area, width * min_height)

if height[left] < height[right]:


left += 1
else:
right -= 1
return max_area

height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(max_area(height)) # Output: 49

Explanation:

1. Algorithm:
● Use two pointers to calculate the area between lines and move pointers to
find the maximum area.
● The pointer with the smaller height is moved to potentially find a taller line.

29. Problem: Group Anagrams


Definition:

Given an array of strings, group the anagrams together.

Example:

1. Input: strs = ["eat","tea","tan","ate","nat","bat"] Output:


[["eat","tea","ate"],["tan","nat"],["bat"]] Explanation: All anagrams are
grouped together.
2. Input: strs = [""] Output: [[""]] Explanation: The input contains a single empty
string.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<vector<string>> groupAnagrams(vector<string>& strs) {


unordered_map<string, vector<string>> anagram_map;

for (const string& str : strs) {


string sorted_str = str;
sort(sorted_str.begin(), sorted_str.end());
anagram_map[sorted_str].push_back(str);
}

vector<vector<string>> result;
for (auto& pair : anagram_map) {
result.push_back(pair.second);
}

return result;
}

int main() {
vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> result = groupAnagrams(strs);

for (const auto& group : result) {


for (const string& str : group) {
cout << str << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

from collections import defaultdict

def group_anagrams(strs):
anagram_map = defaultdict(list)

for str_ in strs:


sorted_str = ''.join(sorted(str_))
anagram_map[sorted_str].append(str_)

return list(anagram_map.values())

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]


print(group_anagrams(strs)) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'],
['bat']]

Explanation:

1. Algorithm:
● Sort each string and use it as a key in a hash map.
● Group strings with the same sorted key.
30. Problem: Valid Parentheses
Definition:

Given a string s containing just the characters '(', ')', '{', '}', '[', and ']',
determine if the input string is valid. An input string is valid if the brackets are closed in
the correct order.

Example:

1. Input: s = "()" Output: True Explanation: The string contains a pair of valid
parentheses.
2. Input: s = "()[]{}" Output: True Explanation: The string contains valid
parentheses of different types.

C++ Solution:

#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;

bool isValid(string s) {
unordered_map<char, char> bracket_map = {{')', '('}, {']', '['}, {'}',
'{'}};
stack<char> stack;

for (char c : s) {
if (bracket_map.find(c) != bracket_map.end()) {
char top = stack.empty() ? '#' : stack.top();
if (top == bracket_map[c]) {
stack.pop();
} else {
return false;
}
} else {
stack.push(c);
}
}

return stack.empty();
}
int main() {
string s = "()[]{}";
cout << isValid(s) << endl; // Output: 1 (true)
return 0;
}

Python Solution:

def is_valid(s):
bracket_map = {')': '(', ']': '[', '}': '{'}
stack = []

for char in s:
if char in bracket_map:
top_element = stack.pop() if stack else '#'
if bracket_map[char] != top_element:
return False
else:
stack.append(char)

return not stack

s = "()[]{}"
print(is_valid(s)) # Output: True

Explanation:

1. Algorithm:
● Use a stack to keep track of opening brackets.
● When encountering a closing bracket, check if it matches the top of the
stack.

31. Problem: Merge Two Sorted Lists


Definition:

Merge two sorted linked lists and return it as a new sorted list. The new list should be
made by splicing together the nodes of the first two lists.

Example:
1. Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Explanation: The two
lists are merged into one sorted list.
2. Input: l1 = [], l2 = [0] Output: [0] Explanation: The second list is returned as
the result.

C++ Solution:

#include <iostream>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {


ListNode dummy(0);
ListNode* tail = &dummy;

while (l1 != nullptr && l2 != nullptr) {


if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}

tail->next = (l1 != nullptr) ? l1 : l2;

return dummy.next;
}

int main() {
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(2);
l1->next->next = new ListNode(4

);

ListNode* l2 = new ListNode(1);


l2->next = new ListNode(3);
l2->next->next = new ListNode(4);
ListNode* result = mergeTwoLists(l1, l2);

while (result != nullptr) {


cout << result->val << " ";
result = result->next;
}
cout << endl;

return 0;
}

Python Solution:

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def merge_two_lists(l1, l2):


dummy = ListNode()
tail = dummy

while l1 and l2:


if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next

tail.next = l1 if l1 else l2

return dummy.next

# Helper function to create list nodes


def print_list(node):
while node:
print(node.val, end=" ")
node = node.next
print()

l1 = ListNode(1, ListNode(2, ListNode(4)))


l2 = ListNode(1, ListNode(3, ListNode(4)))
result = merge_two_lists(l1, l2)
print_list(result) # Output: 1 1 2 3 4 4
Explanation:

1. Algorithm:
● Use a dummy node to simplify list merging.
● Compare nodes from both lists and append the smaller one to the result
list.

32. Problem: Linked List Cycle


Definition:

Given a linked list, determine if it has a cycle in it.

Example:

1. Input: head = [3,2,0,-4] with cycle at node index 1 Output: True Explanation:
The list has a cycle.
2. Input: head = [1,2] with no cycle Output: False Explanation: The list does not
have a cycle.

C++ Solution:

#include <iostream>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

bool hasCycle(ListNode *head) {


ListNode *slow = head, *fast = head;

while (fast != nullptr && fast->next != nullptr) {


slow = slow->next;
fast = fast->next->next;

if (slow == fast) return true;


}

return false;
}
int main() {
ListNode* head = new ListNode(3);
head->next = new ListNode(2);
head->next->next = new ListNode(0);
head->next->next->next = new ListNode(-4);
head->next->next->next->next = head->next; // Creating a cycle

cout << hasCycle(head) << endl; // Output: 1 (true)

return 0;
}

Python Solution:

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def has_cycle(head):
slow, fast = head, head

while fast and fast.next:


slow = slow.next
fast = fast.next.next

if slow == fast:
return True

return False

# Helper function to create list nodes


def create_cycle_list():
head = ListNode(3)
head.next = ListNode(2)
head.next.next = ListNode(0)
head.next.next.next = ListNode(-4)
head.next.next.next.next = head.next # Creating a cycle
return head

head = create_cycle_list()
print(has_cycle(head)) # Output: True

Explanation:

1. Algorithm:
● Use Floyd’s Tortoise and Hare algorithm with two pointers.
● If pointers meet, there is a cycle; otherwise, there isn't.

33. Problem: Climbing Stairs


Definition:

You are climbing a staircase. It takes n steps to reach the top. Each time you can either
climb 1 or 2 steps. Calculate how many distinct ways you can climb to the top.

Example:

1. Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top: [1,1]
and [2].
2. Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top:
[1,1,1], [1,2], and [2,1].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int climbStairs(int n) {
if (n == 1) return 1;
int first = 1, second = 2;

for (int i = 3; i <= n; ++i) {


int temp = first + second;
first = second;
second = temp;
}

return second;
}

int main() {
int n = 3;
cout << climbStairs(n) << endl; // Output: 3
return 0;
}
Python Solution:

def climb_stairs(n):
if n == 1:
return 1
first, second = 1, 2

for _ in range(3, n + 1):


first, second = second, first + second

return second

n = 3
print(climb_stairs(n)) # Output: 3

Explanation:

1. Algorithm:
● Use dynamic programming to keep track of the number of ways to reach
the current step.
● Update the count based on the previous two steps.

34. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image. Rotate the image by 90


degrees (clockwise).

Example:

Input:
[[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[[7,4,1],
[8,5,2],
[9,6,3]]
1. Explanation: The image is rotated 90 degrees clockwise.
Input:
[[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]]
Output:
[[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]]
2. Explanation: The image is rotated 90 degrees clockwise.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();

// Transpose the matrix


for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}

// Reverse each row


for (int i = 0; i < n; ++i) {
reverse(matrix[i].begin(), matrix[i].end());
}
}

int main() {
vector<vector<int>> matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
rotate(matrix);

for (const auto& row : matrix) {


for (int val : row) {
cout << val << " ";
}
cout << endl;
}

return 0;
}
Python Solution:

def rotate(matrix):
n = len(matrix)

# Transpose the matrix


for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

# Reverse each row


for i in range(n):
matrix[i].reverse()

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


rotate(matrix)
for row in matrix:
print(row)
# Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Explanation:

1. Algorithm:
● First, transpose the matrix (swap matrix[i][j] with matrix[j][i]).
● Then, reverse each row to get the final rotated image.

35. Problem: Remove Duplicates from Sorted Array


Definition:

Given a sorted array nums, remove the duplicates in-place such that

each element appears only once and return the new length. Do not use extra space for
another array.

Example:

1. Input: nums = [1,1,2] Output: 2 Explanation: The array after removing duplicates
is [1,2].
2. Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5 Explanation: The array after
removing duplicates is [0,1,2,3,4].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int removeDuplicates(vector<int>& nums) {


if (nums.empty()) return 0;

int unique_index = 0;

for (int i = 1; i < nums.size(); ++i) {


if (nums[i] != nums[unique_index]) {
++unique_index;
nums[unique_index] = nums[i];
}
}

return unique_index + 1;
}

int main() {
vector<int> nums = {1,1,2};
int length = removeDuplicates(nums);
cout << length << endl; // Output: 2

for (int i = 0; i < length; ++i) {


cout << nums[i] << " ";
}
cout << endl;

return 0;
}

Python Solution:

def remove_duplicates(nums):
if not nums:
return 0

unique_index = 0

for i in range(1, len(nums)):


if nums[i] != nums[unique_index]:
unique_index += 1
nums[unique_index] = nums[i]

return unique_index + 1

nums = [1,1,2]
length = remove_duplicates(nums)
print(length) # Output: 2
print(nums[:length]) # Output: [1, 2]

Explanation:

1. Algorithm:
● Use a pointer to keep track of the position of the last unique element.
● Iterate through the array and update the position when a new unique
element is found.

36. Problem: Longest Substring Without Repeating


Characters
Definition:

Given a string s, find the length of the longest substring without repeating characters.

Example:

1. Input: s = "abcabcbb" Output: 3 Explanation: The longest substring without


repeating characters is "abc", which has a length of 3.
2. Input: s = "bbbbb" Output: 1 Explanation: The longest substring without repeating
characters is "b", which has a length of 1.

C++ Solution:

#include <iostream>
#include <unordered_map>
#include <algorithm>

using namespace std;

int lengthOfLongestSubstring(string s) {
unordered_map<char, int> char_map;
int left = 0, max_length = 0;

for (int right = 0; right < s.size(); ++right) {


if (char_map.find(s[right]) != char_map.end()) {
left = max(left, char_map[s[right]] + 1);
}
char_map[s[right]] = right;
max_length = max(max_length, right - left + 1);
}

return max_length;
}

int main() {
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl; // Output: 3
return 0;
}

Python Solution:

def length_of_longest_substring(s):
char_map = {}
left = 0
max_length = 0

for right in range(len(s)):


if s[right] in char_map:
left = max(left, char_map[s[right]] + 1)
char_map[s[right]] = right
max_length = max(max_length, right - left + 1)

return max_length

s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3

Explanation:

1. Algorithm:
● Use a sliding window approach with a hashmap to track the last seen
index of each character.
● Adjust the left pointer when a duplicate character is found.
37. Problem: Merge Intervals
Definition:

Given an array of intervals where intervals[i] = [start_i, end_i], merge all


overlapping intervals and return an array of the non-overlapping intervals that cover all
the intervals in the input.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: Intervals [1,3] and [2,6] overlap and are
merged into [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4]
and [4,5] overlap and are merged into [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());

vector<vector<int>> merged;
merged.push_back(intervals[0]);

for (int i = 1; i < intervals.size(); ++i) {


if (merged.back()[1] >= intervals[i][0]) {
merged.back()[1] = max(merged.back()[1], intervals[i][1]);
} else {
merged.push_back(intervals[i]);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);
for (const auto& interval : result) {
cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;

return 0;
}

Python Solution:

def merge(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

for i in range(1, len(intervals)):


if merged[-1][1] >= intervals[i][0]:
merged[-1][1] = max(merged[-1][1], intervals[i][1])
else:
merged.append(intervals[i])

return merged

intervals = [[1,3],[2,6],[8,10],[15,18]]
print(merge(intervals)) # Output: [[1, 6], [8, 10], [15, 18]]

Explanation:

1. Algorithm:
● Sort the intervals based on the starting point.
● Iterate through the intervals and merge overlapping ones.

38. Problem: 3Sum


Definition:

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such
that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Example:

1. Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: The


two unique triplets that sum up to zero are [-1,-1,2] and [-1,0,1].
2. Input: nums = [] Output: [] Explanation: There are no triplets in an empty list.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {


vector<vector<int>> result;
sort(nums.begin(), nums.end());

for (int i = 0; i < nums.size(); ++i) {


if (i > 0 && nums[i] == nums[i-1]) continue; // Skip duplicates

int left = i + 1, right = nums.size() - 1;


while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
++left;
} else if (sum > 0) {
--right;
} else {
result.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) ++left; //
Skip duplicates
while (left < right && nums[right] == nums[right - 1]) --right;
// Skip duplicates
++left;
--right;
}
}
}

return result;
}

int main() {
vector<int> nums = {-1, 0, 1, 2, -1, -4};
vector<vector<int>> result = threeSum(nums);

for (const auto& triplet : result) {


cout << "[";
for (int num : triplet) {
cout << num << " ";
}
cout << "] ";
}
cout << endl;

return 0;
}

Python Solution:

def three_sum(nums):
nums.sort()
result = []

for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue

left, right = i + 1, len(nums) - 1


while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1

return result

nums = [-1, 0, 1, 2, -1, -4]


print(three_sum(nums)) # Output: [[-1, -1, 2], [-1, 0, 1]]

Explanation:

1. Algorithm:
● Sort the array to use two-pointer technique.
● Skip duplicates to ensure unique triplets.
● Adjust the pointers based on the sum of the triplet.

39. Problem: Letter Combinations of a Phone Number


Definition:

Given a string digits containing digits from 2 to 9, return all possible letter combinations
that the number could represent.

Example:

1. Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]


Explanation: The mapping of digits to letters is like on a phone keypad.
2. Input: digits = "" Output: [] Explanation: There are no combinations if there are
no digits.

C++ Solution:

#include

<iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> letterCombinations(string digits) {


vector<string> result;
if (digits.empty()) return result;

vector<string> phone = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs",
"tuv", "wxyz"};

string combination;
function<void(int)> backtrack = [&](int index) {
if (index == digits.size()) {
result.push_back(combination);
return;
}

string letters = phone[digits[index] - '0'];


for (char letter : letters) {
combination.push_back(letter);
backtrack(index + 1);
combination.pop_back();
}
};

backtrack(0);
return result;
}

int main() {
string digits = "23";
vector<string> result = letterCombinations(digits);

for (const auto& combo : result) {


cout << combo << " ";
}
cout << endl;

return 0;
}

Python Solution:

def letter_combinations(digits):
if not digits:
return []

phone = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
result = []

def backtrack(index, path):


if index == len(digits):
result.append(''.join(path))
return

letters = phone[int(digits[index])]
for letter in letters:
path.append(letter)
backtrack(index + 1, path)
path.pop()

backtrack(0, [])
return result

digits = "23"
print(letter_combinations(digits)) # Output: ['ad', 'ae', 'af', 'bd', 'be',
'bf', 'cd', 'ce', 'cf']
Explanation:

1. Algorithm:
● Use backtracking to generate all possible combinations.
● Map digits to letters and recursively build combinations.

40. Problem: Generate Parentheses


Definition:

Given n pairs of parentheses, generate all combinations of well-formed parentheses.

Example:

1. Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]


Explanation: There are five combinations of well-formed parentheses for n = 3.
2. Input: n = 1 Output: ["()"] Explanation: Only one combination for n = 1.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void backtrack(vector<string>& result, string current, int open, int close, int
n) {
if (current.size() == 2 * n) {
result.push_back(current);
return;
}

if (open < n) {
backtrack(result, current + '(', open + 1, close, n);
}
if (close < open) {
backtrack(result, current + ')', open, close + 1, n);
}
}

vector<string> generateParenthesis(int n) {
vector<string> result;
backtrack(result, "", 0, 0, n);
return result;
}

int main() {
int n = 3;
vector<string> result = generateParenthesis(n);

for (const auto& combo : result) {


cout << combo << " ";
}
cout << endl;

return 0;
}

Python Solution:

def generate_parentheses(n):
def backtrack(current, open, close):
if len(current) == 2 * n:
result.append(current)
return

if open < n:
backtrack(current + '(', open + 1, close)
if close < open:
backtrack(current + ')', open, close + 1)

result = []
backtrack("", 0, 0)
return result

n = 3
print(generate_parentheses(n)) # Output: ['((()))', '(()())', '(())()',
'()(())', '()()()']

Explanation:

1. Algorithm:
● Use backtracking to build valid parentheses combinations.
● Ensure that the number of closing parentheses does not exceed the
number of opening parentheses.

41. Problem: Valid Sudoku


Definition:

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated
according to the Sudoku rules.

Example:

Input:
[["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".",".","2",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4",".",".",".",".","5"],
[".",".",".",".","8",".",".","7","9"]]
1. Output: True Explanation: The board is valid according to the Sudoku rules.

Input:
[["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".",".","2",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4",".",".",".",".","5"],
[".",".",".",".","8",".",".","7","9"]]
2. Output: False Explanation: The board is invalid due to a duplicate 8 in the first
row.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

bool isValidSudoku(vector<vector<char>>& board) {


unordered_set<string> seen;

for (int i = 0; i < 9; ++i) {


for (int j = 0; j < 9; ++j) {
if (board[i][j] != '.') {
char num = board[i][j];
if (!seen.insert(to_string(num) + " in row " +
to_string(i)).second ||
!seen.insert(to_string(num) + " in column " +
to_string(j)).second ||
!seen.insert(to_string(num) + " in block " + to_string(i /
3) + "-" + to_string(j / 3)).second) {
return false;
}
}
}
}

return true;
}

int main() {
vector<vector<char>> board = {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','.','2','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','.','.','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}
};

cout << isValidSudoku(board) << endl; // Output: 1 (true)

return 0;
}

Python Solution:

def is_valid_sudoku(board):
seen = set()

for i in range(9):
for j in range(9):
if board[i][j] != '.':
num = board[i][j]
if (num, 'row', i) in seen or (num, 'column', j) in seen or
(num, 'block', i // 3, j // 3) in seen:
return False
seen.add((num, 'row', i))
seen.add((num, 'column', j))
seen.add((num, 'block', i // 3, j // 3))
return True

board = [
['5','3','.','.','7','.','.','.','.'],
['6','.','.','1','9','5','.','.','.'],
['.','9','8','.','.','.','.','6','.'],
['8','.','.','.','6','.','.','.','3'],
['4','.','.','8','.','3','.','.','1'],
['7','.','.','.','.','2','.','.','6'],
['.','6','.','.','.','.','2','8','.'],
['.','.','.','4','.','.','.','.','5'],
['.','.','.','.','8','.','.','7','9']
]
print(is_valid_sudoku(board)) # Output: True

Explanation:

1. Algorithm:
● Use a set to track seen numbers in rows, columns,

and 3x3 subgrids.

● Check for duplicates by verifying against the set.

42. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image. Rotate the image by 90


degrees (clockwise).

Example:

Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
1. Explanation: Rotate the matrix 90 degrees clockwise.

Input:
[
[1,2],
[3,4]
]
Output:
[
[3,1],
[4,2]
]
2. Explanation: Rotate the matrix 90 degrees clockwise.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();

for (int i = 0; i < n; ++i) {


for (int j = i; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}

for (int i = 0; i < n; ++i) {


reverse(matrix[i].begin(), matrix[i].end());
}
}

int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);

for (const auto& row : matrix) {


for (int num : row) {
cout << num << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

def rotate(matrix):
n = len(matrix)

# Transpose the matrix


for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

# Reverse each row


for row in matrix:
row.reverse()

matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
rotate(matrix)
for row in matrix:
print(row) # Output: [7, 4, 1] [8, 5, 2] [9, 6, 3]

Explanation:

1. Algorithm:
● Transpose the matrix (swap rows with columns).
● Reverse each row to get the rotated matrix.

43. Problem: Spiral Matrix


Definition:

Given an m x n matrix, return all elements of the matrix in spiral order.

Example:
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
1. Output: [1,2,3,6,9,8,7,4,5] Explanation: The elements in spiral order are
[1,2,3,6,9,8,7,4,5].

Input:
[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
2. Output: [1,2,3,4,8,12,11,10,9,5,6,7] Explanation: The elements in spiral order
are [1,2,3,4,8,12,11,10,9,5,6,7].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

vector<int> spiralOrder(vector<vector<int>>& matrix) {


vector<int> result;
if (matrix.empty()) return result;

int top = 0, bottom = matrix.size() - 1;


int left = 0, right = matrix[0].size() - 1;

while (top <= bottom && left <= right) {


for (int i = left; i <= right; ++i) result.push_back(matrix[top][i]);
++top;

for (int i = top; i <= bottom; ++i) result.push_back(matrix[i][right]);


--right;

if (top <= bottom) {


for (int i = right; i >= left; --i)
result.push_back(matrix[bottom][i]);
--bottom;
}

if (left <= right) {


for (int i = bottom; i >= top; --i)
result.push_back(matrix[i][left]);
++left;
}
}

return result;
}

int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
vector<int> result = spiralOrder(matrix);

for (int num : result) {


cout << num << " ";
}
cout << endl;

return 0;
}

Python Solution:

def spiral_order(matrix):
result = []
if not matrix:
return result

top, bottom = 0, len(matrix) - 1


left, right = 0, len(matrix[0]) - 1

while top <= bottom and left <= right:


result.extend(matrix[top][left:right+1])
top += 1

result.extend(matrix[i][right] for i in range(top, bottom + 1))


right -= 1

if top <= bottom:


result.extend(reversed(matrix[bottom][left:right+1]))
bottom -= 1

if left <= right:


result.extend(matrix[i][left] for i in range(bottom, top - 1, -1))
left += 1

return result

matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(spiral_order(matrix)) # Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Explanation:

1. Algorithm:
● Use four pointers to track the boundaries of the spiral order.
● Iterate and adjust boundaries as you collect elements.

44. Problem: Search in Rotated Sorted Array


Definition:

Suppose an array of length n sorted in ascending order is rotated between 1 and n


times. Given the array, find the target value in O(log n) time.

Example:

1. Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Explanation: The target 0


is located at index 4.
2. Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Explanation: The target 3
is not in the array.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int search(vector<int>& nums, int target) {


int left = 0, right = nums.size() - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (nums[mid] == target) return mid;

if (nums[left] <= nums[mid]) {


if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}

return -1;
}

int main() {
vector<int> nums = {4,5,6,7,0,1,2};
int target = 0;
cout << search(nums, target) << endl; // Output: 4

target = 3;
cout << search(nums, target) << endl; // Output: -1

return 0;
}

Python Solution:

def search(nums, target):


left, right = 0, len(nums) - 1

while left <= right:


mid = left + (right - left) // 2

if nums[mid] == target:
return mid

if nums[left] <= nums[mid]:


if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1

nums = [4,5,6,7,0,1,2]
target = 0
print(search(nums, target)) # Output: 4

target = 3
print(search(nums, target)) # Output: -

Explanation:

1. Algorithm:
● Use binary search while accounting for the rotation.
● Adjust search boundaries based on the sorted portion.

45. Problem: Number of Islands


Definition:

Given a 2D grid map of '1's (land) and '0's (water), count the number of islands. An
island is surrounded by water and is formed by connecting adjacent lands horizontally
or vertically.

Example:

Input:
[
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
1. Output: 1 Explanation: There is only one island in the grid.

Input:
[
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
2. Output: 3 Explanation: There are three islands in the grid.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void dfs(vector<vector<char>>& grid, int i, int j) {


if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j]
== '0') {
return;
}

grid[i][j] = '0'; // Mark as visited

dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}

int numIslands(vector<vector<char>>& grid) {


if (grid.empty()) return 0;

int count = 0;

for (int i = 0; i < grid.size(); ++i) {


for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j] == '1') {
++count;
dfs(grid, i, j);
}
}
}

return count;
}

int main() {
vector<vector<char>> grid = {
{'1','1','1','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','0'},
{'0','0','0','0','0'}
};
cout << numIslands(grid) << endl; // Output: 1

grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};

cout << numIslands(grid) << endl; // Output: 3

return 0;
}

Python Solution:

def num_islands(grid):
def dfs(i, j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j]
== '0':
return

grid[i][j] = '0' # Mark as visited

dfs(i + 1, j)
dfs(i - 1, j)
dfs(i, j + 1)
dfs(i, j - 1)

if not grid:
return 0

count = 0

for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
count += 1
dfs(i, j)

return count

grid = [
['1','1','1','1','0'],
['1','1','0','1','0'],
['1','1','0','0','0'],
['0','0','0','0','0']
]
print(num_islands(grid)) # Output: 1

grid = [
['1','1','0','0','0'],
['1','1','0','0','0'],
['0','0','1','0','0'],
['0','0','0','1','1']
]
print(num_islands(grid)) # Output: 3

Explanation:

1. Algorithm:
● Use Depth-First Search (DFS) to mark all connected land as visited.
● Count islands by initiating DFS when encountering an unvisited land cell.

Certainly! Here’s a continuation of the list of problems, starting from problem 46 and
continuing up to problem 100.

46. Problem: Container With Most Water


Definition:

You are given an array height where height[i] is the height of a vertical line at index i.
Find two lines which together with the x-axis form a container, such that the container
contains the most water.

Example:

1. Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The container with


the most water is between indices 1 and 8 (height = min(8, 7) * (8 - 1) = 49).
2. Input: height = [1,1] Output: 1 Explanation: The container with the most water is
between indices 0 and 1 (height = min(1, 1) * (1 - 0) = 1).

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;


int maxArea(vector<int>& height) {
int left = 0, right = height.size() - 1;
int max_area = 0;

while (left < right) {


int width = right - left;
int min_height = min(height[left], height[right]);
max_area = max(max_area, width * min_height);

if (height[left] < height[right]) {


++left;
} else {
--right;
}
}

return max_area;
}

int main() {
vector<int> height = {1,8,6,2,5,4,8,3,7};
cout << maxArea(height) << endl; // Output: 49

return 0;
}

Python Solution:

def max_area(height):
left, right = 0, len(height) - 1
max_area = 0

while left < right:


width = right - left
min_height = min(height[left], height[right])
max_area = max(max_area, width * min_height)

if height[left] < height[right]:


left += 1
else:
right -= 1

return max_area

height = [1,8,6,2,5,4,8,3,7]
print(max_area(height)) # Output: 49
Explanation:

1. Algorithm:
● Use two pointers to traverse the array from both ends.
● Calculate the area with the current pair of lines and update the maximum
area found.
● Move the pointer that points to the shorter line to potentially find a better
pair.

47. Problem: Longest Substring Without Repeating


Characters
Definition:

Given a string s, find the length of the longest substring without repeating characters.

Example:

1. Input: s = "abcabcbb" Output: 3 Explanation: The longest substring without


repeating characters is "abc" which has a length of 3.
2. Input: s = "bbbbb" Output: 1 Explanation: The longest substring without repeating
characters is "b" which has a length of 1.

C++ Solution:

#include <iostream>
#include <unordered_map>
#include <string>

using namespace std;

int lengthOfLongestSubstring(string s) {
unordered_map<char, int> char_map;
int left = 0, max_len = 0;

for (int right = 0; right < s.length(); ++right) {


if (char_map.find(s[right]) != char_map.end()) {
left = max(left, char_map[s[right]] + 1);
}
char_map[s[right]] = right;
max_len = max(max_len, right - left + 1);
}
return max_len;
}

int main() {
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl; // Output: 3

return 0;
}

Python Solution:

def length_of_longest_substring(s):
char_map = {}
left = 0
max_len = 0

for right in range(len(s)):


if s[right] in char_map:
left = max(left, char_map[s[right]] + 1)
char_map[s[right]] = right
max_len = max(max_len, right - left + 1)

return max_len

s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3

Explanation:

1. Algorithm:
● Use a sliding window with two pointers to maintain a substring without
repeating characters.
● Update the left pointer when a repeating character is found to ensure the
substring remains valid.

48. Problem: Maximum Subarray


Definition:
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.

Example:

1. Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray


[4,-1,2,1] has the largest sum of 6.
2. Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum of
1.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxSubArray(vector<int>& nums) {


int max_sum = nums[0], current_sum = nums[0];

for (int i = 1; i < nums.size(); ++i) {


current_sum = max(nums[i], current_sum + nums[i]);
max_sum = max(max_sum, current_sum);
}

return max_sum;
}

int main() {
vector<int> nums = {-2,1,-3,4,-1,2,1,-5,4};
cout << maxSubArray(nums) << endl; // Output: 6

return 0;
}

Python Solution:

def max_sub_array(nums):
max_sum = current_sum = nums[0]

for num in nums[1:]:


current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)

return max_sum
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(max_sub_array(nums)) # Output: 6

Explanation:

1. Algorithm:
● Use Kadane’s Algorithm to keep track of the maximum sum ending at
each position.
● Update the maximum sum found as you iterate through the array.

49. Problem: Merge Intervals


Definition:

Given an array of intervals where intervals[i] = [start_i, end_i], merge all


overlapping intervals.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: The intervals [1,3] and [2,6] overlap, so
they are merged to [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: The intervals
[1,4] and [4,5] overlap, so they are merged to [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);

for (int i = 1; i < intervals.size(); ++i) {


if (merged.back()[1] >= intervals[i][0]) {
merged.back()[1] = max(merged.back()[1], intervals[i][1]);
} else {
merged.push_back(intervals[i]);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);

for (const auto& interval : result) {


cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;

return 0;
}

Python Solution:

def merge(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

for interval in intervals[1:]:


if merged[-1][1] >= interval[0]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
merged.append(interval)

return merged

intervals =

[[1,3],[2,6],[8,10],[15,18]]
result = merge(intervals)
print(result) # Output: [[1,6],[8,10],[15,18]]

Explanation:
1. Algorithm:
● Sort intervals based on the start times.
● Merge overlapping intervals as you iterate through the sorted list.

50. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image, rotate the image by 90


degrees (clockwise).

Example:

Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
1.

Input:
[
[5,1,9,11],
[2,4,8,10],
[13,3,6,7],
[15,14,12,16]
]
Output:
[
[15,13,2,5],
[14,3,4,1],
[12,6,8,9],
[16,7,10,11]
]
2.
C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();
// Transpose the matrix
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
// Reverse each row
for (int i = 0; i < n; ++i) {
reverse(matrix[i].begin(), matrix[i].end());
}
}

int main() {
vector<vector<int>> matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};

rotate(matrix);

for (const auto& row : matrix) {


for (const auto& val : row) {
cout << val << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def rotate(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()

matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
rotate(matrix)
for row in matrix:
print(row) # Output: [7,4,1] [8,5,2] [9,6,3]

Explanation:

1. Algorithm:
● Transpose the matrix by swapping elements across the main diagonal.
● Reverse each row to achieve the 90-degree rotation.

Certainly! Continuing from problem 51:

51. Problem: Longest Increasing Subsequence


Definition:

Given an integer array nums, return the length of the longest strictly increasing
subsequence.

Example:

1. Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest


increasing subsequence is [2, 3, 7, 101].
2. Input: nums = [0,1,0,3,2,3] Output: 4 Explanation: The longest increasing
subsequence is [0, 1, 2, 3].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int lengthOfLIS(vector<int>& nums) {


if (nums.empty()) return 0;

vector<int> dp(nums.size(), 1);


int max_len = 1;

for (int i = 1; i < nums.size(); ++i) {


for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
max_len = max(max_len, dp[i]);
}

return max_len;
}

int main() {
vector<int> nums = {10,9,2,5,3,7,101,18};
cout << lengthOfLIS(nums) << endl; // Output: 4

return 0;
}

Python Solution:

def length_of_lis(nums):
if not nums:
return 0

dp = [1] * len(nums)
max_len = 1

for i in range(1, len(nums)):


for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
max_len = max(max_len, dp[i])

return max_len

nums = [10,9,2,5,3,7,101,18]
print(length_of_lis(nums)) # Output: 4
Explanation:

1. Algorithm:
● Use a dynamic programming array dp where dp[i] represents the length
of the longest increasing subsequence ending at index i.
● Iterate through the array and update dp based on previously computed
values.

52. Problem: Word Break


Definition:

Given a string s and a dictionary of strings wordDict, determine if s can be segmented


into a space-separated sequence of one or more dictionary words.

Example:

1. Input: s = "leetcode", wordDict = ["leet", "code"] Output: True Explanation:


The string "leetcode" can be segmented as "leet code".
2. Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: True
Explanation: The string "applepenapple" can be segmented as "apple pen
apple".

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

bool wordBreak(string s, vector<string>& wordDict) {


unordered_set<string> word_set(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
dp[0] = true;

for (int i = 1; i <= s.size(); ++i) {


for (int j = 0; j < i; ++j) {
if (dp[j] && word_set.find(s.substr(j, i - j)) != word_set.end()) {
dp[i] = true;
break;
}
}
}

return dp[s.size()];
}

int main() {
string s = "leetcode";
vector<string> wordDict = {"leet", "code"};
cout << (wordBreak(s, wordDict) ? "True" : "False") << endl; // Output:
True

return 0;
}

Python Solution:

def word_break(s, word_dict):


word_set = set(word_dict)
dp = [False] * (len(s) + 1)
dp[0] = True

for i in range(1, len(s) + 1):


for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break

return dp[len(s)]

s = "leetcode"
word_dict = ["leet", "code"]
print(word_break(s, word_dict)) # Output: True

Explanation:

1. Algorithm:
● Use a dynamic programming array dp where dp[i] is true if the substring
s[0:i] can be segmented into dictionary words.
● Update dp[i] based on previously computed values and the presence of
substrings in the word dictionary.

53. Problem: Combination Sum


Definition:

Given an array of candidates and a target number target, find all unique combinations
in candidates where the candidate numbers sum to target. The same number may be
chosen from candidates an unlimited number of times.

Example:

1. Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation:


The combination [2,2,3] adds up to 7, and the combination [7] adds up to 7.
2. Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Explanation: The combinations that add up to 8 are [2,2,2,2], [2,3,3], and
[3,5].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void backtrack(vector<int>& candidates, int target, int start, vector<int>&


current, vector<vector<int>>& result) {
if (target == 0) {
result.push_back(current);
return;
}
if (target < 0) return;

for (int i = start; i < candidates.size(); ++i) {


current.push_back(candidates[i]);
backtrack(candidates, target - candidates[i], i, current, result);
current.pop_back();
}
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {


vector<vector<int>> result;
vector<int> current;
backtrack(candidates, target, 0, current, result);
return result;
}

int main() {
vector<int> candidates = {2,3,6,7};
int target = 7;
vector<vector<int>> result = combinationSum(candidates, target);
for (const auto& combination : result) {
for (int num : combination) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def combination_sum(candidates, target):


def backtrack(start, target, path):
if target == 0:
result.append(path)
return
if target < 0:
return

for i in range(start, len(candidates)):


backtrack(i, target - candidates[i], path + [candidates[i]])

result = []
backtrack(0, target, [])
return result

candidates = [2,3,6,7]
target = 7
print(combination_sum(candidates, target)) # Output: [[2,2,3],[7]]

Explanation:

1. Algorithm:
● Use a recursive backtracking approach to explore all possible
combinations.
● Keep track of the current combination and update the result when a valid
combination is found.

54. Problem: Subset Sum


Definition:

Given a set of integers, find all possible subsets (the power set).

Example:

1. Input: nums = [1,2,3] Output: [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]


Explanation: The power set of [1,2,3] includes all possible subsets.
2. Input: nums = [0] Output: [[],[0]] Explanation: The power set of [0] includes []
and [0].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

vector<vector<int>> subsets(vector<int>& nums) {


vector<vector<int>> result;
int n = nums.size();
int subset_count = 1 << n; // 2^n subsets

for (int i = 0; i < subset_count; ++i) {


vector<int> subset;
for (int j = 0; j < n; ++j) {
if (i & (1 << j)) {

subset.push_back(nums[j]);
}
}
result.push_back(subset);
}

return result;
}

int main() {
vector<int> nums = {1,2,3};
vector<vector<int>> result = subsets(nums);

for (const auto& subset : result) {


for (int num : subset) {
cout << num << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

def subsets(nums):
result = []
n = len(nums)
subset_count = 1 << n # 2^n subsets

for i in range(subset_count):
subset = []
for j in range(n):
if i & (1 << j):
subset.append(nums[j])
result.append(subset)

return result

nums = [1,2,3]
print(subsets(nums)) # Output: [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]

Explanation:

1. Algorithm:
● Generate all possible subsets using bitwise operations.
● For each subset, use bits to determine which elements are included.

55. Problem: Unique Paths


Definition:

A robot is located at the top-left corner of a m x n grid. The robot can only move down or
right. Calculate the number of unique paths to the bottom-right corner.

Example:

1. Input: m = 3, n = 7 Output: 28 Explanation: There are 28 unique paths from the


top-left to the bottom-right.
2. Input: m = 3, n = 2 Output: 3 Explanation: There are 3 unique paths from the
top-left to the bottom-right.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int uniquePaths(int m, int n) {


vector<vector<int>> dp(m, vector<int>(n, 1));

for (int i = 1; i < m; ++i) {


for (int j = 1; j < n; ++j) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}

return dp[m-1][n-1];
}

int main() {
int m = 3, n = 7;
cout << uniquePaths(m, n) << endl; // Output: 28

return 0;
}

Python Solution:

def unique_paths(m, n):


dp = [[1] * n for _ in range(m)]

for i in range(1, m):


for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]

return dp[m-1][n-1]

m = 3
n = 7
print(unique_paths(m, n)) # Output: 28

Explanation:
1. Algorithm:
● Use a dynamic programming table dp where dp[i][j] represents the
number of unique paths to cell (i, j).
● Update each cell based on paths coming from the top and left.

56. Problem: Coin Change


Definition:

Given a list of coin denominations and an amount, compute the minimum number of
coins needed to make up that amount. If the amount cannot be made up by any
combination of the coins, return -1.

Example:

1. Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: The minimum


number of coins needed is 3 (11 = 5 + 5 + 1).
2. Input: coins = [2], amount = 3 Output: -1 Explanation: It's not possible to make
the amount 3 with only 2-cent coins.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int coinChange(vector<int>& coins, int amount) {


vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;

for (int i = 1; i <= amount; ++i) {


for (const int& coin : coins) {
if (i - coin >= 0) {
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
}

return dp[amount] > amount ? -1 : dp[amount];


}
int main() {
vector<int> coins = {1,2,5};
int amount = 11;
cout << coinChange(coins, amount) << endl; // Output: 3

return 0;
}

Python Solution:

def coin_change(coins, amount):


dp = [float('inf')] * (amount + 1)
dp[0] = 0

for i in range(1, amount + 1):


for coin in coins:
if i - coin >= 0:
dp[i] = min(dp[i], dp[i - coin] + 1)

return dp[amount] if dp[amount] != float('inf') else -1

coins = [1,2,5]
amount = 11
print(coin_change(coins, amount)) # Output: 3

Explanation:

1. Algorithm:
● Use dynamic programming to find the minimum number of coins required
for each amount from 0 to amount.
● Update the minimum number of coins for each amount based on
previously computed values.

57. Problem: Kth Largest Element in an Array


Definition:

Given an integer array nums and an integer k, return the kth largest element in the array.

Example:
1. Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Explanation: The 2nd largest
element is 5.
2. Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 Explanation: The 4th largest
element is 4.

C++ Solution:

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int findKthLargest(vector<int>& nums, int k) {


priority_queue<int, vector<int>, greater<int>> min_heap;

for (const int& num : nums) {


min_heap.push(num);
if (min_heap.size() > k) {
min_heap.pop();
}
}

return min_heap.top();
}

int main() {
vector<int> nums = {3,2,1,5,6,4};
int k = 2;
cout << findKthLargest(nums, k) << endl; // Output: 5

return 0;
}

Python Solution:

import heapq

def find_kth_largest(nums, k):


return heapq.nlargest(k, nums)[-1]

nums = [3,2,1,5,6,4]
k = 2
print(find_kth_largest(nums, k)) # Output: 5

Explanation:
1. Algorithm:
● Use a min-heap of size k to keep track of the k largest elements seen so
far.
● The top of the heap will be the kth largest element.

58. Problem: Merge Intervals


Definition:

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping
intervals.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: The intervals [1,3] and [2,6] overlap, so
they are merged into [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: The intervals
[1,4] and [4,5] overlap and are merged into [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
vector<int> current = intervals[0];

for (const auto& interval : intervals) {


if (interval[0] <= current[1]) {
current[1] = max(current[1], interval[1]);
} else {
merged.push_back(current);
current = interval;
}
}
merged.push_back(current);

return merged;
}

int main() {
vector<vector<int>> intervals = {{

1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);

for (const auto& interval : result) {


cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;

return 0;
}

Python Solution:

def merge(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = []
current = intervals[0]

for interval in intervals:


if interval[0] <= current[1]:
current[1] = max(current[1], interval[1])
else:
merged.append(current)
current = interval

merged.append(current)
return merged

intervals = [[1,3],[2,6],[8,10],[15,18]]
print(merge(intervals)) # Output: [[1,6],[8,10],[15,18]]

Explanation:

1. Algorithm:
● Sort intervals based on the start time.
● Merge intervals that overlap by keeping track of the current interval and
updating its end time.

59. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image. Rotate the image by 90


degrees (clockwise).

Example:

1. Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]


Explanation: Rotating the matrix 90 degrees clockwise results in the output.
2. Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] Output:
[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] Explanation: Rotating the
matrix 90 degrees clockwise results in the output.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();
for (int i = 0; i < n / 2; ++i) {
for (int j = i; j < n - i - 1; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
matrix[j][n - i - 1] = temp;
}
}
}

int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);

for (const auto& row : matrix) {


for (int num : row) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def rotate(matrix):
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - i - 1):
temp = matrix[i][j]
matrix[i][j] = matrix[n - j - 1][i]
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]
matrix[j][n - i - 1] = temp

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate(matrix)
for row in matrix:
print(row)

Explanation:

1. Algorithm:
● Perform a layer-by-layer rotation.
● Swap elements in a cyclic manner to achieve the 90 degrees rotation.

60. Problem: Validate Binary Search Tree


Definition:

Given a binary tree, determine if it is a valid binary search tree (BST).

Example:

1. Input: [2,1,3] Output: True Explanation: The binary tree [2,1,3] is a valid BST.
2. Input: [5,1,4,null,null,3,6] Output: False Explanation: The binary tree
[5,1,4,null,null,3,6] is not a valid BST.
C++ Solution:

#include <iostream>
#include <climits>

using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

bool isValidBST(TreeNode* root, long long min_val = LLONG_MIN, long long


max_val = LLONG_MAX) {
if (!root) return true;
if (root->val <= min_val || root->val >= max_val) return false;
return isValidBST(root->left, min_val, root->val) &&
isValidBST(root->right, root->val, max_val);
}

int main() {
TreeNode* root = new TreeNode(2);
root->left = new TreeNode(1);
root->right = new TreeNode(3);

cout << (isValidBST(root) ? "True" : "False") << endl; // Output: True

return 0;
}

Python Solution:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

def is_valid_bst(root, min_val=float('-inf'), max_val=float('inf')):


if not root:
return True
if root.val <= min_val or root.val >= max_val:
return False
return is_valid_bst(root.left, min_val, root.val) and
is_valid_bst(root.right, root.val, max_val)
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)

print(is_valid_bst(root)) # Output: True

Explanation:

1. Algorithm:
● Use recursion to check the validity of the BST by ensuring that all nodes
satisfy the BST property within given bounds.

61. Problem: Minimum Path Sum


Definition:

Given a m x n grid filled with non-negative numbers, find a path from the top-left to the
bottom-right, which minimizes the sum of all numbers along its path.

Example:

1. Input: grid = [[1,3,1],[1,5,1],[4,2,1]] Output: 7 Explanation: The path 1 → 3


→ 1 → 1 → 1 has the minimum sum of 7.
2. Input: grid = [[1,2,3],[4,5,6]] Output: 12 Explanation: The path 1 → 2 → 3 → 6
has the minimum sum of 12.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int minPathSum(vector<vector<int>>& grid) {


int m = grid.size();
int n = grid[0].size();

for (int i = 1; i < m; ++i) {


grid[i][0] += grid[i-1][0];
}

for (int j = 1; j < n; ++j) {


grid[0][j] += grid[0][j-1];
}

for (int i = 1; i < m; ++i) {


for (int j = 1; j < n; ++j) {
grid[i][j] += min(grid[i-1][j], grid[i][j-1]);
}
}

return grid[m-1][n-1];
}

int main() {
vector<vector<int>> grid = {{1,3,1},{1,5,1},{4,2,1}};
cout << minPathSum(grid) << endl; // Output: 7

return 0;
}

Python Solution:

def min_path_sum(grid):
m, n = len(grid), len(grid[0])

for i in range(1, m):


grid[i][0] += grid[i-1][0]

for j in range(1, n):


grid[0][j] += grid[0][j-1]

for i in range(1, m):


for j in range(1, n):
grid[i][j] += min(grid[i-1][j], grid[i][j-1])

return grid[m-1][n-1]

grid = [[1,3,1],[1,5,1],[4,2,1

]]
print(min_path_sum(grid)) # Output: 7

Explanation:

1. Algorithm:
● Use dynamic programming to calculate the minimum path sum to each
cell.
● Update each cell's value to be the minimum path sum to that cell.

62. Problem: Binary Tree Level Order Traversal


Definition:

Given a binary tree, return the level order traversal of its nodes' values. (i.e., from left to
right, level by level).

Example:

1. Input: [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Explanation: The


level order traversal is [[3],[9,20],[15,7]].
2. Input: [1] Output: [[1]] Explanation: The level order traversal is [[1]].

C++ Solution:

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

vector<vector<int>> levelOrder(TreeNode* root) {


vector<vector<int>> result;
if (!root) return result;

queue<TreeNode*> q;
q.push(root);

while (!q.empty()) {
vector<int> level;
int size = q.size();

for (int i = 0; i < size; ++i) {


TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}

result.push_back(level);
}

return result;
}

int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);

vector<vector<int>> result = levelOrder(root);

for (const auto& level : result) {


for (int num : level) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

from collections import deque

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

def level_order(root):
result = []
if not root:
return result

q = deque([root])

while q:
level = []
size = len(q)

for _ in range(size):
node = q.popleft()
level.append(node.val)

if node.left:
q.append(node.left)
if node.right:
q.append(node.right)

result.append(level)

return result

root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)

print(level_order(root)) # Output: [[3],[9,20],[15,7]]

Explanation:

1. Algorithm:
● Use a queue to perform level-order traversal.
● Collect nodes at each level and append to the result list.

These problems are commonly encountered in coding interviews and competitive


programming. They cover various topics including arrays, dynamic prog

63. Problem: Container With Most Water


Definition:

Given n non-negative integers representing the height of bars. Find two lines that
together with the x-axis form a container, such that the container contains the most
water.

Example:
1. Input: [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The container with the most
water is between the lines at index 1 and 8 with height 7 and width 7, which
contains 49 units of water.
2. Input: [1,1] Output: 1 Explanation: The container with the most water is between
the lines at index 0 and 1 with height 1 and width 1, which contains 1 unit of water.

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxArea(vector<int>& height) {


int left = 0, right = height.size() - 1;
int max_area = 0;

while (left < right) {


int width = right - left;
int current_height = min(height[left], height[right]);
max_area = max(max_area, width * current_height);

if (height[left] < height[right]) {


++left;
} else {
--right;
}
}

return max_area;
}

int main() {
vector<int> height = {1,8,6,2,5,4,8,3,7};
cout << maxArea(height) << endl; // Output: 49

return 0;
}

Python Solution:

def max_area(height):
left, right = 0, len(height) - 1
max_area = 0

while left < right:


width = right - left
current_height = min(height[left], height[right])
max_area = max(max_area, width * current_height)

if height[left] < height[right]:


left += 1
else:
right -= 1

return max_area

height = [1,8,6,2,5,4,8,3,7]
print(max_area(height)) # Output: 49

Explanation:

1. Algorithm:
● Use two pointers starting from both ends of the array.
● Calculate the area between the two lines and update the maximum area.
● Move the pointer pointing to the shorter line to find potentially larger areas.

64. Problem: Find Minimum in Rotated Sorted Array


Definition:

Suppose an array of length n sorted in ascending order is rotated between 1 and n


times. Given the rotated array, find the minimum element.

Example:

1. Input: [3,4,5,1,2] Output: 1 Explanation: The minimum element in the rotated


sorted array is 1.
2. Input: [4,5,6,7,0,1,2] Output: 0 Explanation: The minimum element in the
rotated sorted array is 0.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;


int findMin(vector<int>& nums) {
int left = 0, right = nums.size() - 1;

while (left < right) {


int mid = left + (right - left) / 2;

if (nums[mid] > nums[right]) {


left = mid + 1;
} else {
right = mid;
}
}

return nums[left];
}

int main() {
vector<int> nums = {3,4,5,1,2};
cout << findMin(nums) << endl; // Output: 1

return 0;
}

Python Solution:

def find_min(nums):
left, right = 0, len(nums) - 1

while left < right:


mid = left + (right - left) // 2

if nums[mid] > nums[right]:


left = mid + 1
else:
right = mid

return nums[left]

nums = [3,4,5,1,2]
print(find_min(nums)) # Output: 1

Explanation:

1. Algorithm:
● Use binary search to find the pivot point where the array is rotated.
● The minimum element will be at the pivot point.
65. Problem: Longest Substring Without Repeating
Characters
Definition:

Given a string, find the length of the longest substring without repeating characters.

Example:

1. Input: "abcabcbb" Output: 3 Explanation: The longest substring without repeating


characters is "abc", which has length 3.
2. Input: "bbbbb" Output: 1 Explanation: The longest substring without repeating
characters is "b", which has length 1.

C++ Solution:

#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int lengthOfLongestSubstring(string s) {
unordered_set<char> chars;
int left = 0, max_length = 0;

for (int right = 0; right < s.length(); ++right) {


while (chars.find(s[right]) != chars.end()) {
chars.erase(s[left]);
++left;
}
chars.insert(s[right]);
max_length = max(max_length, right - left + 1);
}

return max_length;
}

int main() {
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl; // Output: 3

return 0;
}
Python Solution:

def length_of_longest_substring(s):
chars = set()
left, max_length = 0, 0

for right in range(len(s)):


while s[right] in chars:
chars.remove(s[left])
left += 1
chars.add(s[right])
max_length = max(max_length, right - left + 1)

return max_length

s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3

Explanation:

1. Algorithm:
● Use a sliding window approach with a set to keep track of characters.
● Expand the window by moving the right pointer and adjust the left pointer
to avoid duplicates.

66. Problem: Word Ladder


Definition:

Given two words (beginWord and endWord), and a dictionary's word list, find the length of
the shortest transformation sequence from beginWord to endWord, such that:

● Only one letter can be changed at a time.


● Each transformed word must exist in the word list.

Example:

1. Input: beginWord = "hit", endWord = "cog", wordList =


["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: One shortest
transformation is "hit" → "hot" → "dot" → "dog" → "cog", which has length 5.
2. Input: beginWord = "hit", endWord = "cog", wordList =
["hot","dot","dog","lot","log"] Output: 0 Explanation: There is no possible
transformation.

C++ Solution:

#include <iostream>
#include <unordered_set>
#include <queue>
#include <string>

using namespace std;

int ladderLength(string beginWord, string endWord, unordered_set<string>&


wordList) {
if (wordList.find(endWord) == wordList.end()) return 0;

unordered_set<string> visited;
queue<string> q;
q.push(beginWord);
visited.insert(beginWord);
int level = 1;

while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
string word = q.front();
q.pop();

if (word == endWord) return level;

for (int j = 0; j < word.length(); ++j) {


char original = word[j];
for (char c = 'a'; c <= 'z'; ++c) {
word[j] = c;
if (wordList.find(word) != wordList.end() &&
visited.find(word) == visited.end()) {
q.push(word);
visited.insert(word);
}
}
word[j] = original;
}
}
++level;
}

return 0;
}
int main() {
unordered_set<string> wordList = {"hot","dot","dog","lot","log","cog"};
cout << ladderLength("hit", "cog", wordList) << endl; // Output: 5

return 0;
}

Python Solution:

from collections import deque

def ladder_length(begin_word, end_word, word_list):


if end_word not in word_list:
return 0

visited = set()
q = deque([begin_word])
visited.add(begin_word)
level = 1

while

q:
size = len(q)
for _ in range(size):
word = q.popleft()
if word == end_word:
return level

for i in range(len(word)):
original_char = word[i]
for c in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + c + word[i+1:]
if new_word in word_list and new_word not in visited:
q.append(new_word)
visited.add(new_word)
word = word[:i] + original_char + word[i+1:]

level += 1

return 0

word_list = {"hot","dot","dog","lot","log","cog"}
print(ladder_length("hit", "cog", word_list)) # Output: 5

Explanation:
1. Algorithm:
● Use BFS to explore all possible one-letter transformations.
● Keep track of visited words to avoid cycles.
● Return the level (number of transformations) when endWord is found.

67. Problem: Serialize and Deserialize Binary Tree


Definition:

Design an algorithm to serialize and deserialize a binary tree. Serialization is converting


a tree to a string, and deserialization is converting a string back to a tree.

Example:

1. Input: root = [1,2,3,null,null,4,5] Output: Serialized:


"1,2,#,#,3,4,#,#,5,#,#" / Deserialized: [1,2,3,null,null,4,5]
2. Input: root = [] Output: Serialized: "#" / Deserialized: []

C++ Solution:

#include <iostream>
#include <string>
#include <queue>
#include <sstream>

using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Codec {
public:
string serialize(TreeNode* root) {
if (!root) return "#";
return to_string(root->val) + "," + serialize(root->left) + "," +
serialize(root->right);
}

TreeNode* deserialize(const string& data) {


istringstream ss(data);
return deserializeHelper(ss);
}

private:
TreeNode* deserializeHelper(istringstream& ss) {
string val;
getline(ss, val, ',');

if (val == "#") return NULL;

TreeNode* node = new TreeNode(stoi(val));


node->left = deserializeHelper(ss);
node->right = deserializeHelper(ss);
return node;
}
};

int main() {
Codec codec;
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->right->left = new TreeNode(4);
root->right->right = new TreeNode(5);

string serialized = codec.serialize(root);


cout << "Serialized: " << serialized << endl;

TreeNode* deserialized = codec.deserialize(serialized);


cout << "Deserialized: " << (deserialized->val) << endl; // Output root
value

return 0;
}

Python Solution:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Codec:
def serialize(self, root):
def dfs(node):
if not node:
return "#,"
return str(node.val) + "," + dfs(node.left) + dfs(node.right)

return dfs(root)

def deserialize(self, data):


def dfs():
val = next(vals)
if val == "#":
return None
node = TreeNode(int(val))
node.left = dfs()
node.right = dfs()
return node

vals = iter(data.split(','))
return dfs()

codec = Codec()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)

serialized = codec.serialize(root)
print(f"Serialized: {serialized}")

deserialized = codec.deserialize(serialized)
print(f"Deserialized: {deserialized.val}") # Output root value

Explanation:

1. Algorithm:
● Use DFS to serialize the tree by traversing each node and recording its
value or a marker for None.
● For deserialization, reconstruct the tree using a queue of values from the
serialized string.

68. Problem: Combination Sum


Definition:
Given an array of distinct integers and a target number, find all unique combinations of
numbers that sum up to the target. Each number in the array can be used multiple
times.

Example:

1. Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation:


The combinations that sum up to 7 are [2,2,3] and [7].
2. Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Explanation: The combinations that sum up to 8 are [2,2,2,2], [2,3,3], and
[3,5].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void combinationSumHelper(vector<int>& candidates, int target,


vector<vector<int>>& result, vector<int>& combination, int start) {
if (target == 0) {
result.push_back(combination);
return;
}

for (int i = start; i < candidates.size(); ++i) {


if (candidates[i] <= target) {
combination.push_back(candidates[i]);
combinationSumHelper(candidates, target - candidates[i], result,
combination, i);
combination.pop_back();
}
}
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {


vector<vector<int>> result;
vector<int> combination;
combinationSumHelper(candidates, target, result, combination, 0);
return result;
}

int main() {
vector<int> candidates = {2,3,6,7};
int target = 7;
vector<vector<int>> result = combinationSum(candidates, target);
for (const auto& combination : result) {
for (int num : combination) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def combination_sum(candidates, target):


def backtrack(start, target, path):
if target == 0:
result.append(path)
return
for i in range(start, len(candidates)):
if candidates[i] <= target:
backtrack(i, target - candidates[i], path + [candidates[i]])

result = []
backtrack(0, target, [])
return result

candidates = [2,3,6,7]
target = 7
print(combination_sum(candidates, target)) # Output: [[2,2,3],[7]]

Explanation:

1. Algorithm:
● Use backtracking to explore all possible combinations.
● Recursively try to include each candidate and adjust the target
accordingly.

69. Problem: Valid Parentheses


Definition:
Given a string containing just the characters '(', ')', '{', '}', '[', and ']', determine
if the input string is valid. An input string is valid if the brackets are closed in the correct
order.

Example:

1. Input: "()[]{}" Output: true Explanation: The parentheses are valid.


2. Input: "([)]" Output: false Explanation: The parentheses are not valid.

C++ Solution:

#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;

bool isValid(string s) {
stack<char> stk;
unordered_map<char, char> mappings = {{')', '('}, {']', '['}, {'}', '{'}};

for (char c : s) {
if (mappings.find(c) != mappings.end()) {
char top_element = stk.empty() ? '#' : stk.top();
stk.pop();

if (mappings[c] != top_element) {
return false;
}
} else {
stk.push(c);
}
}

return stk.empty();
}

int main() {
string s = "()[]{}";
cout << isValid(s) << endl; // Output: 1 (true)

return 0;
}

Python Solution:

def is_valid(s):
stack = []
mappings = {')': '(', ']': '[', '}': '{'}

for char in s:
if char in mappings:
top_element = stack.pop() if stack else '#'
if mappings[char] != top_element:
return False
else:
stack.append(char)

return not stack

s = "()[]{}"
print(is_valid(s)) # Output: True

Explanation:

1. Algorithm:
● Use a stack to keep track of opening brackets.
● For each closing bracket, check if it matches the top of the stack.
● If the stack is empty after processing, the string is valid.

70. Problem: Merge Intervals


Definition:

Given a collection of intervals, merge all overlapping intervals.

Example:

1. Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]]


Explanation: The intervals [1,3] and [2,6] overlap, so they are merged into
[1,6].
2. Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: The intervals [1,4] and [4,5]
overlap, so they are merged into [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);

for (const auto& interval : intervals) {


if (merged.back()[1] >= interval[0]) {
merged.back()[1] = max(merged.back()[1], interval[1]);
} else {
merged.push_back(interval);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);

for (const auto& interval : result) {


cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;

return 0;
}

Python Solution:

def merge(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

for interval in intervals[1:]:


if merged[-1][1] >= interval[0]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
merged.append(interval)
return merged

intervals = [[1,3],[2,6],[8,10],[15,18]]
print(merge(intervals)) # Output: [[1,6],[8,10],[15,18]]

Explanation:

1. Algorithm:
● Sort the intervals based on their start times.
● Iterate through the intervals and merge overlapping ones.

71. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image. Rotate the image by 90


degrees (clockwise).

Example:

1. Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]


Explanation: The image is rotated 90 degrees clockwise.
2. Input: [[1,2],[3,4]] Output: [[3,1],[4,2]] Explanation: The image is rotated 90
degrees clockwise.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}

for (auto& row : matrix) {


reverse(row.begin(), row.end());
}
}

int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);

for (const auto& row : matrix) {


for (int num : row) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def rotate(matrix):
n = len(matrix)

for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

for row in matrix:


row.reverse()

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate(matrix)

for row in matrix:


print(row) # Output: [7,4,1], [8,5,2], [9,6,3]

Explanation:

1. Algorithm:
● Transpose the matrix (swap rows with columns).
● Reverse each row to achieve a 90 degree rotation.

72. Problem: Group Anagrams


Definition:

Given an array of strings, group the anagrams together.

Example:

1. Input: ["eat","tea","tan","ate","nat","bat"] Output:


[["bat"],["nat","tan"],["ate","eat","tea"]] Explanation: All anagrams are
grouped together.
2. Input: [""] Output: [[""]] Explanation: Single empty string.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<vector<string>> groupAnagrams(vector<string>& strs) {


unordered_map<string, vector<string>> anagrams;

for (const auto& str : strs) {


string key = str;
sort(key.begin(), key.end());
anagrams[key].push_back(str);
}

vector<vector<string>> result;
for (auto& [key, group] : anagrams) {
result.push_back(move(group));
}

return result;
}

int main() {
vector<string> strs = {"eat","tea","tan","ate","nat","bat"};
vector<vector<string>> result = groupAnagrams(strs);

for (const auto& group : result) {


for (const auto& str : group) {
cout << str << " ";
}
cout << endl;
}
return 0;
}

Python Solution:

from collections import defaultdict

def group_anagrams(strs):
anagrams = defaultdict(list)

for s in strs:
key = ''.join(sorted(s))
anagrams[key].append(s)

return list(anagrams.values())

strs = ["eat","tea","tan","ate","nat","bat"]
print(group_anagrams(strs)) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'],
['bat']]

Explanation:

1. Algorithm:
● Use a hashmap where keys are sorted characters of the strings.
● Group strings with the same sorted key.

73. Problem: Subset


Definition:

Given a set of distinct integers, nums, return all possible subsets (the power set).

Example:

1. Input: [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]


Explanation: All subsets of [1,2,3].
2. Input: [0] Output: [[],[0]] Explanation: All subsets of [0].

C++ Solution:

#include <iostream>
#include <vector>
using namespace std;

void backtrack(vector<int>& nums, vector<vector<int>>& result, vector<int>&


subset, int start) {
result.push_back(subset);

for (int i = start; i < nums.size(); ++i) {


subset.push_back(nums[i]);
backtrack(nums, result, subset, i + 1);
subset.pop_back();
}
}

vector<vector<int>> subsets(vector<int>& nums) {


vector<vector<int>> result;
vector<int> subset;
backtrack(nums, result, subset, 0);
return result;
}

int main() {
vector<int> nums = {1,2,3};
vector<vector<int>> result = subsets(nums);

for (const auto& subset : result) {


for (int num : subset) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def subsets(nums):
def backtrack(start, path):
result.append(path)
for i in range(start, len(nums)):
backtrack(i + 1, path + [nums[i]])

result = []
backtrack(0, [])
return result

nums = [1,2,3]
print(subsets(nums)) # Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Explanation:

1. Algorithm:
● Use backtracking

to generate all possible subsets by including and excluding each element.

74. Problem: Combination Sum II


Definition:

Given a collection of candidate numbers and a target number, find all unique
combinations in the candidates where the candidate numbers sum to the target. Each
number in candidates may only be used once in the combination.

Example:

1. Input: candidates = [10,1,2,7,6,5], target = 8 Output: [[1,2,5],[1,7],[2,6]]


Explanation: The combinations that sum up to 8 are [1,2,5], [1,7], and [2,6].
2. Input: candidates = [2,5,2,1,2], target = 5 Output: [[1,2,2],[5]]
Explanation: The combinations that sum up to 5 are [1,2,2] and [5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void backtrack(vector<int>& candidates, int target, vector<vector<int>>&


result, vector<int>& combination, int start) {
if (target == 0) {
result.push_back(combination);
return;
}

for (int i = start; i < candidates.size(); ++i) {


if (i > start && candidates[i] == candidates[i - 1]) continue;
if (candidates[i] > target) break;
combination.push_back(candidates[i]);
backtrack(candidates, target - candidates[i], result, combination, i +
1);
combination.pop_back();
}
}

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {


vector<vector<int>> result;
vector<int> combination;
sort(candidates.begin(), candidates.end());
backtrack(candidates, target, result, combination, 0);
return result;
}

int main() {
vector<int> candidates = {10,1,2,7,6,5};
int target = 8;
vector<vector<int>> result = combinationSum2(candidates, target);

for (const auto& combination : result) {


for (int num : combination) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def combination_sum2(candidates, target):


def backtrack(start, target, path):
if target == 0:
result.append(path)
return
for i in range(start, len(candidates)):
if i > start and candidates[i] == candidates[i - 1]:
continue
if candidates[i] > target:
break
backtrack(i + 1, target - candidates[i], path + [candidates[i]])

result = []
candidates.sort()
backtrack(0, target, [])
return result

candidates = [10,1,2,7,6,5]
target = 8
print(combination_sum2(candidates, target)) # Output: [[1,2,5],[1,7],[2,6]]

Explanation:

1. Algorithm:
● Use backtracking to find all unique combinations.
● Avoid duplicates by skipping consecutive same elements in the sorted list.

75. Problem: Sudoku Solver


Definition:

Write a program to solve a Sudoku puzzle by filling the empty cells. A Sudoku puzzle is
represented as a 9 x 9 2D board where '.' represents an empty cell.

Example:

1. Input:
[['5','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','
.'],['.','9','8','.','.','.','.','6','.'],['8','.','.','.','6','.','.','.
','3'],['4','.','.','8','.','3','.','.','1'],['7','.','.','.','2','.','.'
,'.','6'],['.','6','.','.','.','.','2','8','.'],['.','.','.','4','.','.',
'.','.','5'],['.','.','.','.','.','.','.','.','9']] Output:
[['5','3','4','6','7','8','9','1','2'],['6','7','2','1','9','5','3','4','
8'],['1','9','8','3','4','2','5','6','7'],['8','5','9','7','6','1','4','2
','3'],['4','2','6','8','5','3','7','9','1'],['7','1','3','9','2','4','8'
,'5','6'],['9','6','1','5','3','7','2','8','4'],['2','8','7','4','1','9',
'6','3','5'],['3','4','5','2','8','6','1','7','9']] Explanation: The
Sudoku is solved correctly.
2. Input:
[['5','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','
.'],['.','9','8','.','.','.','.','6','.'],['8','.','.','.','6','.','.','.
','3'],['4','.','.','8','.','3','.','.','1'],['7','.','.','.','2','.','.'
,'.','6'],['.','6','.','.','.','.','2','8','.'],['.','.','.','4','.','.',
'.','.','5'],['.','.','.','.','.','.','.','.','9']] Output:
[['5','3','4','6','7','8','9','1','2'],['6','7','2','1','9','5','3','4','
8'],['1','9','8','3','4','2','5','6','7'],['8','5','9','7','6','1','4','2
','3'],['4','2','6','8','5','3','7','9','1'],['7','1','3','9','2','4','8'
,'5','6'],['9','6','1','5','3','7','2','8','4'],['2','8','7','4','1','9',
'6','3','5'],['3','4','5','2','8','6','1','7','9']] Explanation: The
Sudoku is solved correctly.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

bool isValid(vector<vector<char>>& board, int row, int col, char num) {


for (int i = 0; i < 9; ++i) {
if (board[row][i] == num || board[i][col] == num ||
board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num) {
return false;
}
}
return true;
}

bool solveSudoku(vector<vector<char>>& board) {


for (int row = 0; row < 9; ++row) {
for (int col = 0; col < 9; ++col) {
if (board[row][col] == '.') {
for (char num = '1'; num <= '9'; ++num) {
if (isValid(board, row, col, num)) {
board[row][col] = num;
if (solveSudoku(board)) {
return true;
}
board[row][col] = '.';
}
}
return false;
}
}
}
return true;
}

int main() {
vector<vector<char>> board = {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','.','.','.','.','5'},
{'.','.','.','.','.','.','.','.','9'}
};

solveSudoku(board);

for (const auto& row : board) {


for (char num : row) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def solve_sudoku(board):
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num or \
board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == num:
return False
return True

def solve(board):
for row in range(9):
for col in range(9):
if board[row][col] == '.':
for num in '123456789':
if is_valid(board, row, col, num):

board[row][col] = num
if solve(board):
return True
board[row][col] = '.'
return False
return True

solve(board)
return board

board =
[['5','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','.'],['
.','9','8','.','.','.','.','6','.'],['8','.','.','.','6','.','.','.','3'],['4',
'.','.','8','.','3','.','.','1'],['7','.','.','.','2','.','.','.','6'],['.','6'
,'.','.','.','.','2','8','.'],['.','.','.','4','.','.','.','.','5'],['.','.','.
','.','.','.','.','.','9']]
result = solve_sudoku(board)

for row in result:


print(row)

Explanation:

1. Algorithm:
● Use backtracking to fill empty cells.
● Check for validity of each number in the current cell considering rows,
columns, and 3x3 grids.

76. Problem: Word Search


Definition:

Given a m x n board and a word, find if the word exists in the grid. The word can be
constructed from letters of sequentially adjacent cells.

Example:

1. Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],


word = "ABCCED" Output: True Explanation: The word "ABCCED" can be
constructed from the given board.
2. Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],
word = "SEE" Output: True Explanation: The word "SEE" can be constructed from
the given board.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

bool dfs(vector<vector<char>>& board, string& word, int index, int row, int
col) {
if (index == word.size()) return true;
if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() ||
board[row][col] != word[index]) return false;

char temp = board[row][col];


board[row][col] = '#'; // Mark the cell as visited

bool found = dfs(board, word, index + 1, row + 1, col) ||


dfs(board, word, index + 1, row - 1, col) ||
dfs(board, word, index + 1, row, col + 1) ||
dfs(board, word, index + 1, row, col - 1);

board[row][col] = temp; // Unmark the cell


return found;
}

bool exist(vector<vector<char>>& board, string word) {


if (board.empty() || board[0].empty()) return false;

for (int i = 0; i < board.size(); ++i) {


for (int j = 0; j < board[0].size(); ++j) {
if (dfs(board, word, 0, i, j)) return true;
}
}
return false;
}

int main() {
vector<vector<char>> board = {
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
string word = "ABCCED";

cout << (exist(board, word) ? "True" : "False") << endl;

return 0;
}

Python Solution:

def exist(board, word):


def dfs(board, word, index, row, col):
if index == len(word):
return True
if (row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or
board[row][col] != word[index]):
return False
temp = board[row][col]
board[row][col] = '#' # Mark as visited

found = (dfs(board, word, index + 1, row + 1, col) or


dfs(board, word, index + 1, row - 1, col) or
dfs(board, word, index + 1, row, col + 1) or
dfs(board, word, index + 1, row, col - 1))

board[row][col] = temp # Unmark the cell


return found

if not board or not board[0]:


return False

for i in range(len(board)):
for j in range(len(board[0])):
if dfs(board, word, 0, i, j):
return True
return False

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
word = "ABCCED"
print(exist(board, word)) # Output: True

Explanation:

1. Algorithm:
● Use Depth-First Search (DFS) to explore possible paths in the board.
● Mark cells as visited and backtrack if necessary.

77. Problem: Combination Sum


Definition:

Given an array of candidates and a target number, find all unique combinations in
candidates where the candidate numbers sum to the target. The same repeated number
may be chosen multiple times.

Example:

1. Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation:


The combinations that sum up to 7 are [2,2,3] and [7].
2. Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Explanation: The combinations that sum up to 8 are [2,2,2,2], [2,3,3], and
[3,5].

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void backtrack(vector<int>& candidates, int target, vector<vector<int>>&


result, vector<int>& combination, int start) {
if (target == 0) {
result.push_back(combination);
return;
}

for (int i = start; i < candidates.size(); ++i) {


if (candidates[i] > target) continue;

combination.push_back(candidates[i]);
backtrack(candidates, target - candidates[i], result, combination, i);
combination.pop_back();
}
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {


vector<vector<int>> result;
vector<int> combination;
backtrack(candidates, target, result, combination, 0);
return result;
}

int main() {
vector<int> candidates = {2,3,6,7};
int target = 7;
vector<vector<int>> result = combinationSum(candidates, target);

for (const auto& combination : result) {


for (int num : combination) {
cout << num << " ";
}
cout << endl;
}

return 0;
}
Python Solution:

def combination_sum(candidates, target):


def backtrack(start, target, path):
if target == 0:
result.append(path)
return
for i in range(start, len(candidates)):
if candidates[i] > target:
continue
backtrack(i, target - candidates[i], path + [candidates[i]])

result = []
backtrack(0, target, [])
return result

candidates = [2,3,6,7]
target = 7
print(combination_sum(candidates, target)) # Output: [[2,2,3],[7]]

Explanation:

1. Algorithm:
● Use backtracking to explore all combinations that sum up to the target.
● Allow repeated use of the same candidate by keeping the same start
index.

78. Problem: Permutations


Definition:

Given an array of distinct integers, return all possible permutations.

Example:

1. Input: [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]


Explanation: All permutations of [1,2,3].
2. Input: [0,1] Output: [[0,1],[1,0]] Explanation: All permutations of [0,1].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void backtrack(vector<int>& nums, vector<vector<int>>& result, int start) {


if (start == nums.size()) {
result.push_back(nums);
return;
}

for (int i = start; i < nums.size(); ++i) {


swap(nums[start], nums[i]);
backtrack(nums, result, start + 1);
swap

(nums[start], nums[i]);
}
}

vector<vector<int>> permute(vector<int>& nums) {


vector<vector<int>> result;
backtrack(nums, result, 0);
return result;
}

int main() {
vector<int> nums = {1,2,3};
vector<vector<int>> result = permute(nums);

for (const auto& permutation : result) {


for (int num : permutation) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def permute(nums):
def backtrack(start):
if start == len(nums):
result.append(nums[:])
return
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start]
backtrack(start + 1)
nums[start], nums[i] = nums[i], nums[start]

result = []
backtrack(0)
return result

nums = [1,2,3]
print(permute(nums)) # Output:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Explanation:

1. Algorithm:
● Use backtracking to generate all permutations.
● Swap elements and backtrack to generate new permutations.

79. Problem: Word Search II


Definition:

Given an m x n board of characters and a list of strings words, return all the words on
the board.

Example:

1. Input: board =
[["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
, words = ["oath","pea","eat","rain"] Output: ["eat","oath"] Explanation:
The words "eat" and "oath" can be constructed from the given board.
2. Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Explanation: The word "abcb" cannot be constructed from the given board.

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <string>

using namespace std;


struct TrieNode {
unordered_map<char, TrieNode*> children;
bool isEndOfWord;
TrieNode() : isEndOfWord(false) {}
};

void buildTrie(vector<string>& words, TrieNode* root) {


for (const string& word : words) {
TrieNode* node = root;
for (char ch : word) {
if (node->children.find(ch) == node->children.end()) {
node->children[ch] = new TrieNode();
}
node = node->children[ch];
}
node->isEndOfWord = true;
}
}

void dfs(vector<vector<char>>& board, int row, int col, TrieNode* node, string&
path, unordered_set<string>& result) {
if (node->isEndOfWord) {
result.insert(path);
node->isEndOfWord = false; // Avoid duplicate results
}

if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() ||
board[row][col] == '#') return;

char ch = board[row][col];
if (node->children.find(ch) == node->children.end()) return;

board[row][col] = '#'; // Mark as visited


path.push_back(ch);

dfs(board, row + 1, col, node->children[ch], path, result);


dfs(board, row - 1, col, node->children[ch], path, result);
dfs(board, row, col + 1, node->children[ch], path, result);
dfs(board, row, col - 1, node->children[ch], path, result);

board[row][col] = ch; // Unmark


path.pop_back();
}

vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {


TrieNode* root = new TrieNode();
buildTrie(words, root);
unordered_set<string> result;
string path;

for (int i = 0; i < board.size(); ++i) {


for (int j = 0; j < board[0].size(); ++j) {
dfs(board, i, j, root, path, result);
}
}

delete root; // Clean up


return vector<string>(result.begin(), result.end());
}

int main() {
vector<vector<char>> board = {
{'o','a','a','n'},
{'e','t','a','e'},
{'i','h','k','r'},
{'i','f','l','v'}
};
vector<string> words = {"oath","pea","eat","rain"};

vector<string> result = findWords(board, words);

for (const string& word : result) {


cout << word << endl;
}

return 0;
}

Python Solution:

def find_words(board, words):


class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False

def build_trie(words):
root = TrieNode()
for word in words:
node = root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end_of_word = True
return root

def dfs(board, row, col, node, path):


if node.is_end_of_word:
result.add(path)
node.is_end_of_word = False # Avoid duplicate results

if (row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or
board[row][col] == '#'):
return

ch = board[row][col]
if ch not in node.children:
return

board[row][col] = '#' # Mark as visited


path += ch

dfs(board, row + 1, col, node.children[ch], path)


dfs(board, row - 1, col, node.children[ch], path)
dfs(board, row, col + 1, node.children[ch], path)
dfs(board, row, col - 1, node.children[ch], path)

board[row][col] = ch # Unmark
path = path[:-1]

root = build_trie(words)
result = set()
path = ''

for i in range(len(board)):
for j in range(len(board[0])):
dfs(board, i, j, root, path)

return list(result)

board =
[["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
words = ["oath","pea","eat","rain"]
print(find_words(board, words)) # Output: ['eat', 'oath']

Explanation:

1. Algorithm:
● Use a Trie to store the words and perform DFS on the board.
● Mark cells as visited and backtrack as needed.
80. Problem: Word Break
Definition:

Given a string s and a dictionary of words wordDict, determine if s can be segmented


into a space-separated sequence of one or more dictionary words.

Example:

1. Input: s = "leetcode", wordDict = ["leet","code"] Output: True Explanation:


The string "leetcode" can be segmented as "leet code".
2. Input: s = "applepenapple", wordDict = ["apple","pen"] Output: True
Explanation: The string "applepenapple" can be segmented as "apple pen
apple".

C++ Solution:

#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

bool wordBreak(string s, vector<string>& wordDict) {


unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
dp[0] = true;

for (int i = 1; i <= s.size(); ++i) {


for (int j = 0; j < i; ++j) {
if (dp[j] && wordSet.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}

return dp[s.size()];
}

int main() {
string s = "leetcode";
vector<string> wordDict = {"leet","code"};
cout << (wordBreak(s, wordDict) ? "True" : "False") << endl;

return 0;
}

Python Solution:

def word_break(s, word_dict):


word_set = set(word_dict)
dp = [False] * (len(s) + 1)
dp[0] = True

for i in range(1, len(s) + 1):


for j in range(i):
if dp

[j] and s[j:i] in word_set:


dp[i] = True
break

return dp[len(s)]

s = "leetcode"
word_dict = ["leet","code"]
print(word_break(s, word_dict)) # Output: True

Explanation:

1. Algorithm:
● Use dynamic programming to check if each substring can be formed by
words in the dictionary.
● Update the DP table based on previous results and dictionary checks.

81. Problem: Unique Paths


Definition:

A robot is located at the top-left corner of a m x n grid and needs to reach the
bottom-right corner. The robot can only move either down or right. Find the number of
unique paths the robot can take to reach the destination.

Example:
1. Input: m = 3, n = 7 Output: 28 Explanation: There are 28 unique paths from the
top-left to the bottom-right corner.
2. Input: m = 3, n = 2 Output: 3 Explanation: There are 3 unique paths from the
top-left to the bottom-right corner.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

int uniquePaths(int m, int n) {


vector<vector<int>> dp(m, vector<int>(n, 1));

for (int i = 1; i < m; ++i) {


for (int j = 1; j < n; ++j) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}

return dp[m - 1][n - 1];


}

int main() {
int m = 3, n = 7;

cout << uniquePaths(m, n) << endl;

return 0;
}

Python Solution:

def unique_paths(m, n):


dp = [[1] * n for _ in range(m)]

for i in range(1, m):


for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

return dp[m - 1][n - 1]

m = 3
n = 7
print(unique_paths(m, n)) # Output: 28
Explanation:

1. Algorithm:
● Use dynamic programming to calculate the number of unique paths from
the top-left to the bottom-right corner.
● Each cell (i, j) can be reached from either the cell above it (i-1, j) or
the cell to its left (i, j-1).

82. Problem: Merge Intervals


Definition:

Given a collection of intervals, merge all overlapping intervals.

Example:

1. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output:


[[1,6],[8,10],[15,18]] Explanation: The intervals [1,3] and [2,6] overlap and
can be merged to form [1,6].
2. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: The intervals
[1,4] and [4,5] overlap and can be merged to form [1,5].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {


if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());

vector<vector<int>> merged;
merged.push_back(intervals[0]);

for (int i = 1; i < intervals.size(); ++i) {


if (merged.back()[1] >= intervals[i][0]) {
merged.back()[1] = max(merged.back()[1], intervals[i][1]);
} else {
merged.push_back(intervals[i]);
}
}

return merged;
}

int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);

for (const auto& interval : result) {


cout << "[" << interval[0] << "," << interval[1] << "] ";
}
cout << endl;

return 0;
}

Python Solution:

def merge(intervals):
if not intervals:
return []

intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

for interval in intervals[1:]:


if merged[-1][1] >= interval[0]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
merged.append(interval)

return merged

intervals = [[1,3],[2,6],[8,10],[15,18]]
print(merge(intervals)) # Output: [[1,6],[8,10],[15,18]]

Explanation:

1. Algorithm:
● Sort intervals based on the start times.
● Merge overlapping intervals while traversing the sorted list.
83. Problem: Longest Substring Without Repeating
Characters
Definition:

Given a string, find the length of the longest substring without repeating characters.

Example:

1. Input: "abcabcbb" Output: 3 Explanation: The longest substring without repeating


characters is "abc" which has a length of 3.
2. Input: "bbbbb" Output: 1 Explanation: The longest substring without repeating
characters is "b" which has a length of 1.

C++ Solution:

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int lengthOfLongestSubstring(string s) {
unordered_map<char, int> charIndex;
int left = 0, maxLength = 0;

for (int right = 0; right < s.length(); ++right) {


if (charIndex.find(s[right]) != charIndex.end()) {
left = max(left, charIndex[s[right]] + 1);
}
charIndex[s[right]] = right;
maxLength = max(maxLength, right - left + 1);
}

return maxLength;
}

int main() {
string s = "abcabcbb";
cout << lengthOfLongestSubstring(s) << endl;

return 0;
}

Python Solution:
def length_of_longest_substring(s):
char_index = {}
left = 0
max_length = 0

for right in range(len(s)):


if s[right] in char_index:
left = max(left, char_index[s[right]] + 1)
char_index[s[right]] = right
max_length = max(max_length, right - left + 1)

return max_length

s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3

Explanation:

1. Algorithm:
● Use a sliding window approach with two pointers.
● Use a hash map to track the last index of each character and adjust the
left pointer to avoid repeats.

84. Problem: Valid Parentheses


Definition:

Given a string containing just the characters '(',')','{','}','[',']', determine if the


input string is valid. An input string is valid if the brackets are closed in the correct order.

Example:

1. Input: "()" Output: True Explanation: The string is valid.


2. Input: "(]" Output: False Explanation: The string is not valid.

C++ Solution:

#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;


bool isValid(string s) {
unordered_map<char, char> matching = {{')', '('}, {']', '['}, {'}', '{'}};
stack<char> stk;

for (char c : s) {
if (matching.count(c)) {
if (stk.empty() || stk.top() != matching[c]) return false;
stk.pop();
} else {
stk.push(c);
}
}

return stk.empty();
}

int main() {
string s = "()";
cout << (isValid(s) ? "True" : "False") << endl;

return 0;
}

Python Solution:

def is_valid(s):
matching = {')': '(', ']': '[', '}': '{'}
stack = []

for c in s:
if c in matching:
if not stack or stack[-1] != matching[c]:
return False
stack.pop()
else:
stack.append(c)

return not stack

s = "()"
print(is_valid(s)) # Output: True

Explanation:

1. Algorithm:
● Use a stack to keep track of opening brackets.
● When encountering a closing bracket, check for a matching opening
bracket.

85. Problem: Maximum Subarray


**Definition:

**

Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.

Example:

1. Input: [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The contiguous subarray


[4,-1,2,1] has the largest sum = 6.
2. Input: [-1,-2,-3,-4] Output: -1 Explanation: The largest subarray is [-1].

C++ Solution:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxSubArray(vector<int>& nums) {


int maxSum = nums[0];
int currentSum = nums[0];

for (int i = 1; i < nums.size(); ++i) {


currentSum = max(nums[i], currentSum + nums[i]);
maxSum = max(maxSum, currentSum);
}

return maxSum;
}

int main() {
vector<int> nums = {-2,1,-3,4,-1,2,1,-5,4};
cout << maxSubArray(nums) << endl;

return 0;
}
Python Solution:

def max_sub_array(nums):
max_sum = current_sum = nums[0]

for num in nums[1:]:


current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)

return max_sum

nums = [-2,1,-3,4,-1,2,1,-5,4]
print(max_sub_array(nums)) # Output: 6

Explanation:

1. Algorithm:
● Use dynamic programming to keep track of the maximum sum ending at
each position.
● Update the maximum sum as you iterate through the array.

86. Problem: Remove Duplicates from Sorted Array


Definition:

Given a sorted array nums, remove the duplicates in-place such that each element
appears only once and return the new length.

Example:

1. Input: [1,1,2] Output: 2 Explanation: The array after removing duplicates is


[1,2], with length 2.
2. Input: [0,0,1,1,1,2,2,3,3,4] Output: 5 Explanation: The array after removing
duplicates is [0,1,2,3,4], with length 5.

C++ Solution:

#include <iostream>
#include <vector>
using namespace std;

int removeDuplicates(vector<int>& nums) {


if (nums.empty()) return 0;

int uniqueIndex = 0;

for (int i = 1; i < nums.size(); ++i) {


if (nums[i] != nums[uniqueIndex]) {
++uniqueIndex;
nums[uniqueIndex] = nums[i];
}
}

return uniqueIndex + 1;
}

int main() {
vector<int> nums = {1,1,2};
cout << removeDuplicates(nums) << endl;

return 0;
}

Python Solution:

def remove_duplicates(nums):
if not nums:
return 0

unique_index = 0

for i in range(1, len(nums)):


if nums[i] != nums[unique_index]:
unique_index += 1
nums[unique_index] = nums[i]

return unique_index + 1

nums = [1,1,2]
print(remove_duplicates(nums)) # Output: 2

Explanation:

1. Algorithm:
● Use a two-pointer approach to maintain the position of unique elements
and replace duplicates in-place.

87. Problem: Rotate Image


Definition:

You are given an n x n 2D matrix representing an image. Rotate the image by 90


degrees (clockwise).

Example:

1. Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]


Explanation: The matrix is rotated by 90 degrees clockwise.
2. Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] Output:
[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] Explanation: The matrix is
rotated by 90 degrees clockwise.

C++ Solution:

#include <iostream>
#include <vector>
using namespace std;

void rotate(vector<vector<int>>& matrix) {


int n = matrix.size();

// Transpose the matrix


for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}

// Reverse each row


for (int i = 0; i < n; ++i) {
reverse(matrix[i].begin(), matrix[i].end());
}
}

int main() {
vector<vector<int>> matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};

rotate(matrix);

for (const auto& row : matrix) {


for (int num : row) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def rotate(matrix):
n = len(matrix)

# Transpose the matrix


for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

# Reverse each row


for i in range(n):
matrix[i].reverse()

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate(matrix)
print(matrix) # Output: [[7,4,1],[8,5,2],[9,6,3]]

Explanation:

1. Algorithm:
● First, transpose the matrix.
● Then, reverse each row to achieve the final 90-degree rotation.

88. Problem: Merge Sorted Array


Definition:
You are given two sorted integer arrays nums1 and nums2, and nums1 has a size of m + n
where m is the number of elements initialized in nums1 and n is the number of elements
initialized in nums2. Merge nums2 into nums1 in sorted order.

Example:

1. Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output:


[1,2,2,3,5,6] Explanation: The result is the merged sorted array.
2. Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The
result is the same as nums1 since nums2 is empty.

C++ Solution:

#include <iostream>
#include <vector>

using namespace std;

void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {


int i = m - 1, j = n - 1, k = m + n - 1;

while (i >= 0 && j >= 0) {


if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}

while (j >= 0) {
nums1[k--] = nums2[j--];
}
}

int main() {
vector<int> nums1 = {1,2,3,0,0,0};
vector<int> nums2 = {2,5,6};
merge(nums1, 3, nums2, 3);

for (int num : nums1) {


cout << num << " ";
}
cout << endl;

return 0;
}
Python Solution:

def merge(nums1, m, nums2, n):


i, j, k = m - 1, n - 1, m + n - 1

while i >= 0 and j >= 0:


if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1

while j >= 0:
nums1[k] = nums2[j]
j -= 1
k -= 1

nums1 = [

1,2,3,0,0,0]
nums2 = [2,5,6]
merge(nums1, 3, nums2, 3)
print(nums1) # Output: [1,2,2,3,5,6]

Explanation:

1. Algorithm:
● Merge two sorted arrays starting from the end to avoid overwriting
elements in nums1.
● Use two pointers to compare elements from the end of both arrays and
place the larger element at the end of nums1.

89. Problem: Set Matrix Zeroes


Definition:

Given an m x n matrix, if an element is 0, set its entire row and column to 0.

Example:
1. Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]]
Explanation: The element at (1,1) is 0, so the entire row and column are set to 0.
2. Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] Output:
[[0,0,0,0],[0,4,5,0],[0,3,1,0]] Explanation: The elements at (0,0) and (0,3)
are 0, so their entire rows and columns are set to 0.

C++ Solution:

#include <iostream>
#include <vector>
using namespace std;

void setZeroes(vector<vector<int>>& matrix) {


bool firstRowZero = false, firstColZero = false;

for (int i = 0; i < matrix.size(); ++i) {


if (matrix[i][0] == 0) {
firstColZero = true;
break;
}
}

for (int j = 0; j < matrix[0].size(); ++j) {


if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}
}

for (int i = 1; i < matrix.size(); ++i) {


for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}

for (int i = 1; i < matrix.size(); ++i) {


for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}

if (firstRowZero) {
for (int j = 0; j < matrix[0].size(); ++j) {
matrix[0][j] = 0;
}
}

if (firstColZero) {
for (int i = 0; i < matrix.size(); ++i) {
matrix[i][0] = 0;
}
}
}

int main() {
vector<vector<int>> matrix = {
{1,1,1},
{1,0,1},
{1,1,1}
};

setZeroes(matrix);

for (const auto& row : matrix) {


for (int num : row) {
cout << num << " ";
}
cout << endl;
}

return 0;
}

Python Solution:

def set_zeroes(matrix):
m, n = len(matrix), len(matrix[0])
first_row_zero = any(matrix[0][j] == 0 for j in range(n))
first_col_zero = any(matrix[i][0] == 0 for i in range(m))

for i in range(1, m):


for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0

for i in range(1, m):


for j in range(1, n):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if first_row_zero:
for j in range(n):
matrix[0][j] = 0

if first_col_zero:
for i in range(m):
matrix[i][0] = 0

matrix = [[1,1,1],[1,0,1],[1,1,1]]
set_zeroes(matrix)
print(matrix) # Output: [[1,0,1],[0,0,0],[1,0,1]]

Explanation:

1. Algorithm:
● Use the first row and column as markers to record which rows and
columns need to be zeroed.
● Process the matrix to update the elements based on these markers.
● Handle the first row and column separately if they contain zeros.

90. Problem: Search in Rotated Sorted Array


Definition:

You are given an integer array nums sorted in ascending order, and an integer target.
The array is rotated at some pivot unknown to you beforehand. Find the index of target
in the array. If not found, return -1.

Example:

1. Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Explanation: The target 0


is at index 4.
2. Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Explanation: The target 3
is not in the array.

C++ Solution:

#include <iostream>
#include <vector>
using namespace std;

int search(vector<int>& nums, int target) {


int left = 0, right = nums.size() - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (nums[mid] == target) {
return mid;
}

if (nums[left] <= nums[mid]) {


if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}

return -1;
}

int main() {
vector<int> nums = {4,5,6,7,0,1,2};
int target = 0;
cout << search(nums, target) << endl;

return 0;
}

Python Solution:

def search(nums, target):


left, right = 0, len(nums) - 1

while left <= right:


mid = left + (right - left) // 2

if nums[mid] == target:
return mid

if nums[left] <= nums[mid]:


if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1

return -1

nums = [4,5,6,7,0,1,2]
target = 0
print(search(nums, target)) # Output: 4

Explanation:

1. Algorithm:
● Use binary search to efficiently locate the target in the rotated sorted array.
● Adjust the search range based on the rotation and the relative position of
the target.

You might also like