SEO-Optimized Coding Challenges Guide
SEO-Optimized Coding Challenges Guide
Binary Search
Search 2D Matrix
Find Peak Element....
Jump Game
Binary Search
Given an array of integers nums which is sorted in ascending order, and an integer
target, write a function to search target in nums.If target exists, then return its
index. Otherwise, return -1.
Example 1:
1 // C++ solution
2 class Solution {
3 public:
int search(vectorcint>& nums, int target) {
// Initialize pointers low and high representing the search range.
int low = @, high = nums.size() - 1;
// Use a uhile loop to perform binary search.
while (low <= high) {
// Caleulate the middle index mid.
int mid = (low + high) / 2;
// I the element at mid is equal to the target, return mid.
if (nums[mid] == target) {
return mid;
¥
J/ If the element at mid is greater than the target, update high to mid - 1.
else if (nums[mid] > target) {
high = mid - 1;
¥
J/ Tf the element at mid is less than the target, update low to mid + 1.
else {
Tou = mid + 1;
b
b
// Tf the while loop exits, return -1, indicating that the target is not present in the array.
return -1;
¥
Find the Duplicate Number
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums, return this repeated number
You must solve the problem without modifying the array nuns and uses only constant extra space.
Example 1:
Input: nums = [1,3,4,2,2]
Output: 2
Example 2:
Input: nums = [3,1,3,4,2]
Output: 3
1 class Solution {
2 public:
3 int finduplicate(vector<int>& nums) {
4 For(int i=0;i<nums.size();it+)
5 1
3 For(int j=itl;j<nums.size();3++)
7 {
8 if(nums[d]==nuns[31)
9 {
10 return nums[i];
11 3}
12 3
13 b
14 return -1;
15
16 }
7 b
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were
inserted in order.
You must write an algorithm with 0(log n) runtime complexity.
Example1:
Input: nums = [1,3,5,6], target = 5
output: 2
Example2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
1 class Solution {
2 public:
3 int searchInsert(vector<int>& nums, int target) {
4 int 1=
5 int r=nums.size()-1;
6 int m;
7 while(lesr){
8 m=(14+r)/2;
9 if(nums[m]==target){
10 return m;
11 Yelse if(nums[m]>target){
12 r=m-1;
13 }
14 else{
15 1=m+1;
16 }
17 3}
18 return 1;
19 3}
2 )
Sort Colors
Use bubble sort algorithm
75. Sort Colors
Medium © Topics @ Companies © Hint
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color
are adjacent, with the colors in the order red, white, and blue.
We will use the integers 9, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
1 class solution {
2 public:
3 void sortColors(vector<int>& nums) {
a int n=nums.size();
H int temp;
6
7 for(int i=8;icn-1;i++)
g {
9
10 for(int j=0;j<n-i-1;j++)
11
12 if (nums[§]>nums[§+1])
13 <
14 temp=nums[j];
15 nume [§41];
16
17 ¥
18 3}
19 }
2
Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending
position of a given target value.
Example1:
Example2:
Example 3:
class solution {
public:
vectorcint> searchRange(vectorcint>& nums, int target) {
if(nums. size()==8){
return {-1,-1};
}
int 11=0;
int rl= nums.size()-1;
while(11cr1){
int mi= 11+ (r1-11)/2;
if(nums[m1]>=target){
ri=mi;
}
else{
11=mi+l;
}
}
oy - Auw
int 12=0;
int r2= nums.size();
while(l2<r2){
int m2= 12+ (r2-12)/2;
if(nums[m2]>target){
r2=m2;
i
else{
12=m2+1;
¥
}
return {-1,-1};
}
if(11==12){
return{11,12};
}
return {11, 12-1};
Length of Last Word
Given a string s consisting of words and spaces, return the length of the last word in the
string.
Example 1:
Example 2:
Example 3:
Givenan m x n integer matrix matrix, if an elementis 0, set its entire row and columnto @'s.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],(1,0,1]
Example2:
o/1/2]0 ololo]o
3452|0450
11315 o|3|1]o0
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]]
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[e].size();
vector<int>rows(n,1);
vector<int>cols(m,1);
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],(1,2,1],[1,3,3,1],(1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
3 class Solution {
4 public:
5 std::vector<std::vector<int>> generate(int numRows) {
6 std::vector<std::vector<int>> result;
7
8 for (int i = ©; i < numRows; ++i) {
9 std::vector<int> row(i + 1, 1);
1e
11 for (int j = 1; j < i; ++j) {
12 row[j] = result[i - 1][j - 1] + result[i - 1][j];
13 ¥
14
15
16
17
18
19
20
21
You are given a sorted array consisting of only integers where every element
appears exactly twice, except for one element which appears exactly once.
Example 1:
Example 2:
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = (left + right) / 2;
if (mid % 2 == 1) {
mid--;
}
if (nums[mid] != nums[mid + 1]) {
right = mid;
} else {
left = mid + 2;
}
}
return nums[left];
74. Search a 2D Matrix
Medium © Topics & Companies
You are given an m x n integer matrix matrix with the following two
properties:
o The first integer of each row is greater than the last integer of the previous
row.
Example 1:
113|585 |7
10 |11 | 16 | 20
23 |30 | 34 | 60
Input: matrix = [[1,3,5,7],[10,11,16,20], [23,30,34,60]],
target = 3
Outout: true
Example 2:
113|585 |7
10 | 11 | 16 | 20
23 | 30 | 34 | 60
Input: matrix = [[1,3,5,7],[10,11,16,20], [23,30,34,60]],
target = 13
Output: false
1 class Solution {
2 public:
3 bool searchMatrix(vector<vector<int>>& matrix, int target) {
4
5 int m = matrix.size();
6 int n = matrix[@].size();
7
8 int low = ©;
9 int high = m*n - 1;
10
11 while(low <= high){
12 int mid = (low + high)/2;
13 int ele = matrix[mid/n][mid%n];
14 if(target == ele) return true;
15
16 if(target > ele) low = mid + 1;
17 else high = mid - 1;
18 }
19
20 return false;
21 }
50. Pow(x, n)
Medium © Topics @ Companies
Implement pow(x, n), which calculates x raised to the power n (ie., x").
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 272 = 1/22 = 1/4 = 0.25
C++ Vv @ Auto
1 class Solution {
2 public:
3 double myPow(double x, int n) {
4 ‘ return pow(x, n);
5 }
6 1
Find Peak Element
Given a 0-indexed integer array nums, find a peak element, and return its index. If the
array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = —=.In other words, an element is always
considered to be strictly greater than a neighbor that is outside the array.
Example 1:
Example 2:
Jump Game
55. Jump Game
Medium © Topics @ Companies
You are given an integer array nums. You are initially positioned at the array's first index,
and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Example 2:
Example 2:
1 class Solution {
2 public:
3 bool canJump(vector<int>& nums) {
4 int n = nums.size();
5 int maxReach = 9;
6 for (int 1 = ©; 1 < n; i++) {
7 if (i > maxReach) return false;
8 maxReach = max(maxReach, i + nums[i]);
9 }
10 return true;
1}
12}
Given an integer array nums, return an array answer such that answer[i] s equal to the
product of all the elements of nums except nums[i] .
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in 0(n) time and without using the division
operation.
Example 1:
et 1
}
1 #include <vectors
2
3 class solution {
4 public:
5 std::vector<int> productExceptSelf(std: :vectorcint>& nums) {
6 int n = nums.size();
7
8 // Initialize the result array with all elements set to 1
] std: ivectorcint> result(n, 1);
10
1 // Calculate the product of all elements to the left of each element
12 int leftProduct = 1;
13 for (int i=0; i <n; +H) {
1 result[i] *= leftProduct;
15 leftProduct *= nums[i];
// Calculate the product of all elements to the right of each element and multiply with the result
int rightProduct = 1;
for (int i =n - 1; i>=@; --i) {
result[i] *= rightProduct;
rightproduct *= nuns[il;
}
return result;
Given an integer array nums, find a subarray that has the largest product, and return the
product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Example 2:
19
20 // Update max and min ending here considering the current number
21 maxEndingHere = std::max(nums[i], maxEndingHere * nums[i]);
22 minEndingHere = min(nums[i], minEndingHere * nums[i]);
23
22 // Update the overall result
25 result = std::max(result, maxEndingHere);
26 3}
27
28 return result;
29 }
30 )
31
15. 3Sum
Medium © Topics @ Companies @ Hint
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i
'=j,1i!=k,and j != k,and nums[i] + nums[j] + nums[k] ==
Notice that the solution set must not contain duplicate triplets.
Example1:
Example 2:
Example 3:
14
15 // Use a two-pointer approach to find triplets that sum to the target.
16 while (3 < k) {
17 int sum = nums[i] + nums[§] + nums[k];
18
19 // If the sum is equal to the target, add the triplet to the set.
2 if (sum == target) {
21 s.insert({nums[i], nums[j], nums[k]});
2 s
23 k-=;
22 } else if (sum < target) {
25 // If the sum is less than the target, move the second pointer to the right.
26 3+
27 } else {
28 // If the sum is greater than the target, move the third pointer to the left.
29 k==;
30 ¥
31 b
32 b
33
34 // Convert the set of unique triplets to a vector for the final result.
35 for(auto triplets : s)
36 output.push_back(triplets);
37 return output;
38 1
E N H
40
You are given an integer array height of length n. There are n vertical lines drawn such that
the two endpoints of the i™ lineare (i, @) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains
the most water.
Example 2:
1 class Solution {
2 public:
3 int maxArea(vector<int>& height) {
4
5 int n = height.size();
6
7 //as n will always be 2 but height can be @ so maxarea init to @
8 int maxarea = 8;
]
10 int start = €;
1 int end = n-1;
12
13 while(start < end)
14 {
15 int currarea = min(height[start], height[end]) * (end - start);
16 maxarea = max(maxarea, currarea);
17
18 //move the one which is smaller, as this can only lead to higher area further ahead
19 if(height[start] <= height[end])
20 {
22 }
23 else
22 {
25 end
2 3
27
28 }
29
30 return maxarea;
31 }
52 )
Notice
that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1time results
inthearray [a[n-1], a[@], a[l], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum
element of this array.
Example 2:
Example 3:
1 # C++ Code
2 class solution {
3 public:
4 int findiin(vectorcint>a nums) {
5 // Initialize ans to the first element of the array, assuming the array is not rotated.
6 int ans = numsfe];
7 /7 set low to @ and high to the last index of the array.
8 int low = @ , high = nums.size()-1;
9
10 // Check for Rotation:
1 // If the element at index low is less than the element at index high,
12 // the array is not rotated, and we return the element at index low as the minimum.
if(nums[low] < nums[high]){
return nums[low];
}
11 Binary search:
while(low <= high){
/7 1¢ nums[lou] < nuns[high], update ans and break the loop
if(nums[low] < nums[high]){
ans = min(ans , nums[low]);
break;
1
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot
index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1],
.., nums[n-1], nums[@], nums[1], ..., nums[k-1]] (0-indexed). For example,
[0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index
of target ifitisin nums, or -1 if it is notin nums.
Example2:
Example 3:
T I~
61 We can solve this probles using binary search, but how?
62
6 The interesting property of a sorted and rotated array is that when we divide
64 the array into two halves. Atleast, one of the two halves is always sorted.
65
66 1f mid happens to the polnl of rotation then both the (right and left)
&7 halves will be sorted
Il
69+ nu; static int search(int(] nums, int target) {
%
n if(nums.length == @) {
n return -1;
7 »
u r
7 int start = 8;
7% int end = nums. length-1;
7
78 while(start <= end) {
7
80 int mid = (start + end)/2;
81
82 if(nums(mid) == target) {
83 return mid; o A
58 ) else ifif (nussstart]
(nuss(start] <= numsa[=10]) { F\o \
887 mmgn >= nums [start] & target <= nuas(mid])) {
(T \L \
88 = mid-1;
8 } e
% y st = mieens
https://www.youtube.com/watch?