Coding Questions
Coding Questions
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;
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
return max_length
s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3
Explanation:
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
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]]
return merged
Explanation:
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>
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;
return inv_count;
}
return inv_count;
}
int main() {
vector<int> arr = {1, 20, 6, 4, 5};
cout << countInversions(arr) << endl; // Output: 5
return 0;
}
Python Solution:
temp_arr[k] = arr[i]
i += 1
k += 1
return inv_count
return inv_count
def count_inversions(arr):
temp_arr = [0]*len(arr)
return merge_sort_and_count(arr, temp_arr, 0, len(arr) - 1)
Explanation:
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:
#include <iostream>
#include <vector>
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:
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.
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
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]
return max_so_far
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.
Given an integer array nums and an integer k, return the kth largest element in the array.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <queue>
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
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.
Given an array nums and an integer k, rotate the array to the right by k steps.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
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:
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
Given two sorted linked lists, merge them into a single sorted linked list and return it.
Example:
C++ Solution:
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
return dummy.next;
}
int main() {
// Example usage
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(2);
l1->next->next = new ListNode(4);
Python Solution:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = 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)))
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.
Suppose an array of length n is rotated between 1 and n times. Find the minimum
element in the rotated sorted array.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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
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.
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>
return count;
}
int main() {
vector<int> nums = {1, 1, 1};
int k = 2;
cout << subarraySum(nums, k) << endl; // Output: 2
return 0;
}
Python Solution:
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <string>
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
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.
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:
C++ Solution:
#include <iostream>
#include <stack>
#include <unordered_map>
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)
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:
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
return merged;
}
int main() {
vector<vector<int>> intervals = {{1,3}, {2,6}, {8,10}, {15,18}};
vector<vector<int>> result = merge(intervals);
Python Solution:
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = []
return merged
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.
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>
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
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);
Python Solution:
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.
Given an array nums and an integer k, rotate the array to the right by k steps, where k is
non-negative.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
rotate(nums, k);
Python Solution:
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
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);
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
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.
Given an array of integers nums and an integer target, return indices of the two numbers
such that they add up to target.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_map>
return result;
}
int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> result = twoSum(nums, target);
Python Solution:
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.
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>
return result;
}
int main() {
vector<int> nums = {-1, 0, 1, 2, -1, -4};
vector<vector<int>> result = threeSum(nums);
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
return result
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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
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.
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:
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>
return result;
}
int main() {
vector<int> nums = {1, 0, -1, 0, -2, 2};
int target = 0;
vector<vector<int>> result = fourSum(nums, target);
Python Solution:
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
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.
Given an array of integers nums and an integer k, return the total number of continuous
subarrays whose sum equals k.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_map>
int main() {
vector<int> nums = {1, 1, 1};
int k = 2;
cout << subarraySum(nums, k) << endl; // Output: 2
return 0;
}
Python Solution:
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:
C++ Solution:
#include <iostream>
#include <vector>
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]
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.
Given a string s, find the length of the longest substring without repeating characters.
Example:
C++ Solution:
#include <iostream>
#include <unordered_set>
#include <string>
int lengthOfLongestSubstring(string s) {
unordered_set<char> char_set;
int left = 0, max_length = 0;
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
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged = {intervals[0]};
return merged;
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
vector<vector<int>> result = mergeIntervals(intervals);
def merge_intervals(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
return merged
Explanation:
1. Algorithm:
● Sort intervals based on the start times.
● Merge intervals if they overlap; otherwise, add the interval as a new entry.
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:
C++ Solution:
#include <iostream>
#include <vector>
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:
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.
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:
#include <iostream>
#include <vector>
#include <algorithm>
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
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
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);
Python Solution:
def group_anagrams(strs):
anagram_map = defaultdict(list)
return list(anagram_map.values())
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>
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)
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.
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>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
return dummy.next;
}
int main() {
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(2);
l1->next->next = new ListNode(4
);
return 0;
}
Python Solution:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
tail.next = l1 if l1 else l2
return dummy.next
1. Algorithm:
● Use a dummy node to simplify list merging.
● Compare nodes from both lists and append the smaller one to the result
list.
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>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
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
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
if slow == fast:
return True
return False
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.
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>
int climbStairs(int n) {
if (n == 1) return 1;
int first = 1, second = 2;
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
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.
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>
int main() {
vector<vector<int>> matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
rotate(matrix);
return 0;
}
Python Solution:
def rotate(matrix):
n = len(matrix)
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.
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>
int unique_index = 0;
return unique_index + 1;
}
int main() {
vector<int> nums = {1,1,2};
int length = removeDuplicates(nums);
cout << length << endl; // Output: 2
return 0;
}
Python Solution:
def remove_duplicates(nums):
if not nums:
return 0
unique_index = 0
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.
Given a string s, find the length of the longest substring without repeating characters.
Example:
C++ Solution:
#include <iostream>
#include <unordered_map>
#include <algorithm>
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> char_map;
int left = 0, max_length = 0;
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
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:
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);
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]]
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
return result;
}
int main() {
vector<int> nums = {-1, 0, 1, 2, -1, -4};
vector<vector<int>> result = threeSum(nums);
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
return result
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.
Given a string digits containing digits from 2 to 9, return all possible letter combinations
that the number could represent.
Example:
C++ Solution:
#include
<iostream>
#include <vector>
#include <string>
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;
}
backtrack(0);
return result;
}
int main() {
string digits = "23";
vector<string> result = letterCombinations(digits);
return 0;
}
Python Solution:
def letter_combinations(digits):
if not digits:
return []
phone = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
result = []
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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);
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.
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>
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'}
};
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,
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>
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
Python Solution:
def rotate(matrix):
n = len(matrix)
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.
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>
return result;
}
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
vector<int> result = spiralOrder(matrix);
return 0;
}
Python Solution:
def spiral_order(matrix):
result = []
if not matrix:
return result
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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:
if nums[mid] == target:
return mid
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.
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>
dfs(grid, i + 1, j);
dfs(grid, i - 1, j);
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
}
int count = 0;
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'}
};
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
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
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
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.
Given a string s, find the length of the longest substring without repeating characters.
Example:
C++ Solution:
#include <iostream>
#include <unordered_map>
#include <string>
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> char_map;
int left = 0, max_len = 0;
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
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
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]
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);
return merged;
}
int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);
return 0;
}
Python Solution:
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
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.
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>
int main() {
vector<vector<int>> matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
rotate(matrix);
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.
Given an integer array nums, return the length of the longest strictly increasing
subsequence.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
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
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_set>
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:
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
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:
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.
Given a set of integers, find all possible subsets (the power set).
Example:
C++ Solution:
#include <iostream>
#include <vector>
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);
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
return dp[m-1][n-1];
}
int main() {
int m = 3, n = 7;
cout << uniquePaths(m, n) << endl; // Output: 28
return 0;
}
Python Solution:
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
return 0;
}
Python Solution:
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.
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>
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
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.
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping
intervals.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
vector<int> current = intervals[0];
return merged;
}
int main() {
vector<vector<int>> intervals = {{
1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);
return 0;
}
Python Solution:
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = []
current = intervals[0]
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
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.
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>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
TreeNode* root = new TreeNode(2);
root->left = new TreeNode(1);
root->right = new TreeNode(3);
return 0;
}
Python Solution:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
Explanation:
1. Algorithm:
● Use recursion to check the validity of the BST by ensuring that all nodes
satisfy the BST property within given bounds.
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:
C++ Solution:
#include <iostream>
#include <vector>
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])
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.
Given a binary tree, return the level order traversal of its nodes' values. (i.e., from left to
right, level by level).
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <queue>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> level;
int size = q.size();
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);
return 0;
}
Python Solution:
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)
Explanation:
1. Algorithm:
● Use a queue to perform level-order traversal.
● Collect nodes at each level and append to the result list.
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>
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
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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
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:
C++ Solution:
#include <iostream>
#include <unordered_set>
#include <string>
int lengthOfLongestSubstring(string s) {
unordered_set<char> chars;
int left = 0, max_length = 0;
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
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.
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:
Example:
C++ Solution:
#include <iostream>
#include <unordered_set>
#include <queue>
#include <string>
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();
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:
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.
Example:
C++ Solution:
#include <iostream>
#include <string>
#include <queue>
#include <sstream>
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);
}
private:
TreeNode* deserializeHelper(istringstream& ss) {
string val;
getline(ss, val, ',');
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);
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)
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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:
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.
Example:
C++ Solution:
#include <iostream>
#include <stack>
#include <unordered_map>
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)
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);
return merged;
}
int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);
return 0;
}
Python Solution:
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
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]
matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate(matrix)
Explanation:
1. Algorithm:
● Transpose the matrix (swap rows with columns).
● Reverse each row to achieve a 90 degree rotation.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
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);
Python Solution:
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.
Given a set of distinct integers, nums, return all possible subsets (the power set).
Example:
C++ Solution:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {1,2,3};
vector<vector<int>> result = subsets(nums);
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
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:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
vector<int> candidates = {10,1,2,7,6,5};
int target = 8;
vector<vector<int>> result = combinationSum2(candidates, target);
return 0;
}
Python Solution:
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.
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>
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);
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)
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
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;
int main() {
vector<vector<char>> board = {
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
string word = "ABCCED";
return 0;
}
Python Solution:
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
combination.push_back(candidates[i]);
backtrack(candidates, target - candidates[i], result, combination, i);
combination.pop_back();
}
}
int main() {
vector<int> candidates = {2,3,6,7};
int target = 7;
vector<vector<int>> result = combinationSum(candidates, target);
return 0;
}
Python Solution:
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
(nums[start], nums[i]);
}
}
int main() {
vector<int> nums = {1,2,3};
vector<vector<int>> result = permute(nums);
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.
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>
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;
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"};
return 0;
}
Python Solution:
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
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] = 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:
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <unordered_set>
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:
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.
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>
int main() {
int m = 3, n = 7;
return 0;
}
Python Solution:
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).
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
merged.push_back(intervals[0]);
return merged;
}
int main() {
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> result = merge(intervals);
return 0;
}
Python Solution:
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
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:
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;
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
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.
Example:
C++ Solution:
#include <iostream>
#include <stack>
#include <unordered_map>
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)
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.
**
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.
Example:
C++ Solution:
#include <iostream>
#include <vector>
#include <algorithm>
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]
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.
Given a sorted array nums, remove the duplicates in-place such that each element
appears only once and return the new length.
Example:
C++ Solution:
#include <iostream>
#include <vector>
using namespace std;
int uniqueIndex = 0;
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
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
rotate(matrix);
return 0;
}
Python Solution:
def rotate(matrix):
n = len(matrix)
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.
Example:
C++ Solution:
#include <iostream>
#include <vector>
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);
return 0;
}
Python Solution:
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.
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;
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);
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))
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.
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:
C++ Solution:
#include <iostream>
#include <vector>
using namespace std;
if (nums[mid] == target) {
return mid;
}
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:
if nums[mid] == target:
return mid
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.