Infosys Coding
Infosys Coding
int main() {
int N, K, M;
cin >> N >> K >> M;
vector<vector<int>> dp(N + 1, vector<int>(K + 1, 0));
dp[0][0] = 1;
Question 2:
Problem Statement: Find the smallest positive integer X such that
the sum of digits of X equals a given number S.
Input:
The first line contains a single integer S.
Output:
Print the smallest integer X or -1 if no such X exists.
Constraints:
1≤S≤10001 \leq S \leq 1000
Sample Input:
10
Sample Output:
19
Solution in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int S;
cin >> S;
if (S > 900) {
cout << -1 << endl;
return 0;
}
return 0;
}
Question 3:
Problem Statement: You are given an array of integers A of size N.
Find the maximum sum of a subarray where the sum of the subarray
is divisible by M.
Input:
The first line contains two integers N and M.
The second line contains N integers representing the array A.
Output:
Print the maximum sum of the subarray.
Constraints:
1≤N≤1051 \leq N \leq 10^5
1≤M≤1091 \leq M \leq 10^9
−106≤A[i]≤106-10^6 \leq A[i] \leq 10^6
Sample Input:
53
12345
Sample Output:
12
Solution in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int N, M;
cin >> N >> M;
vector<int> A(N);
for (int i = 0; i < N; i++) cin >> A[i];
int maxSum = 0;
map<int, int> modIndex;
if (modIndex.count(mod)) {
maxSum = max(maxSum, prefix[i] - prefix[modIndex[mod]]);
} else {
modIndex[mod] = i;
}
}
int main() {
string S1, S2;
cin >> S1 >> S2;
cout << minDeletionsToAnagram(S1, S2);
return 0;
}
6. Subset Sum Problem
Given an array of integers, determine if there exists a subset
whose sum equals a given target value K.
Input:
o First line: Two integers, N (size of the array) and K (target
sum).
o Second line: Space-separated integers representing the
array elements.
Output:
o Print "YES" if such a subset exists, otherwise print "NO".
Constraints:
o 1≤N≤10001 \leq N \leq 1000
o −104≤array elements≤104-10^4 \leq \text{array elements}
\leq 10^4
o −105≤K≤105-10^5 \leq K \leq 10^5.
Solution:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int N, K;
cin >> N >> K;
vector<int> arr(N);
for (int i = 0; i < N; i++) cin >> arr[i];
cout << (subsetSum(arr, N, K) ? "YES" : "NO");
return 0;
}
int main() {
int N;
cin >> N;
cout << (knightTour(N) ? "YES" : "NO");
return 0;
}
int main() {
int N;
cin >> N;
vector<int> arr(N);
for (int i = 0; i < N; i++) cin >> arr[i];
cout << maxSubarrayProduct(arr, N);
return 0;
}
Question 9
Problem Statement:
You are given two integers X and Y. Find the minimum number
of operations required to convert X into Y. The following
operations are allowed:
1. If X is even, divide it by 2.
2. Add 1 to X.
3. Subtract 1 from X.
Input:
The first line contains two integers X and Y.
Output:
Output a single integer representing the minimum number of
operations.
Constraints:
1≤X,Y≤1061 \leq X, Y \leq 10^6
Example Input:
83
Example Output:
5
Solution in C++:
#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;
q.push({X, 0});
visited.insert(X);
while (!q.empty()) {
int curr = q.front().first;
int steps = q.front().second;
q.pop();
if (curr == Y)
return steps;
int main() {
int X, Y;
cin >> X >> Y;
cout << minOperations(X, Y) << endl;
return 0;
}
Question 10
Problem Statement:
You are given an integer N. Your task is to generate a matrix of
size N×NN \times N such that:
1. Each row contains integers from 1 to NN in ascending order.
2. Every even row is reversed.
Input:
A single integer N.
Output:
Print the generated matrix.
Constraints:
1≤N≤1031 \leq N \leq 10^3
Example Input:
3
Example Output:
123
654
789
Solution in C++:
#include <iostream>
using namespace std;
void generateMatrix(int N) {
int num = 1;
for (int i = 0; i < N; i++) {
if (i % 2 == 0) {
for (int j = 0; j < N; j++) {
cout << num++ << " ";
}
} else {
int temp = num + N - 1;
for (int j = 0; j < N; j++) {
cout << temp-- << " ";
num++;
}
}
cout << endl;
}
}
int main() {
int N;
cin >> N;
generateMatrix(N);
return 0;
}
Question 11
Problem Statement:
You are given an integer N. Find all pairs of integers (a,b)(a, b)
such that:
1. 1≤a,b≤N1 \leq a, b \leq N
2. a2+b2a^2 + b^2 is a perfect square.
Input:
A single integer N.
Output:
Print all pairs (a,b)(a, b) in ascending order of a and then b.
Constraints:
1≤N≤10001 \leq N \leq 1000
Example Input:
5
Example Output:
34
43
Solution in C++:
#include <iostream>
#include <cmath>
using namespace std;
void findPairs(int N) {
for (int a = 1; a <= N; a++) {
for (int b = 1; b <= N; b++) {
int sum = a * a + b * b;
int root = sqrt(sum);
if (root * root == sum) {
cout << a << " " << b << endl;
}
}
}
}
int main() {
int N;
cin >> N;
findPairs(N);
return 0;
}
Question 12
Problem Statement:
You are given two integers N and M. Find the number of ways
to fill a N×MN \times M grid using 2x1 dominoes such that no
dominoes overlap or go outside the grid.
Input:
Two integers N and M.
Output:
Output a single integer representing the number of ways to fill
the grid modulo 109+710^9 + 7.
Constraints:
1≤N,M≤1031 \leq N, M \leq 10^3
Example Input:
23
Example Output:
3
Solution in C++:
#include <iostream>
#include <vector>
using namespace std;
const int MOD = 1e9 + 7;
return dp[M];
}
int main() {
int N, M;
cin >> N >> M;
if (N % 2 != 0) cout << 0 << endl;
else cout << countWays(N, M) << endl;
return 0;
}
Question 13
Problem Statement:
You are given an integer array nums and an integer target. Your
task is to find a subarray whose sum is closest to the given
target. If there are multiple subarrays with the same closest
sum, return the one with the smallest length.
Input:
The first line contains an integer n, the size of the array.
The second line contains n integers representing the array.
The third line contains an integer target.
Output:
Output the closest sum to the target and the length of the
subarray.
Constraints:
1≤n≤1051 \leq n \leq 10^5
−104≤nums[i]≤104-10^4 \leq nums[i] \leq 10^4
−106≤target≤106-10^6 \leq target \leq 10^6
Example Input:
5
2 -3 4 -1 6
5
Example Output:
52
Solution in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, target;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) cin >> nums[i];
cin >> target;
cout << resultSum << " " << minLength << endl;
return 0;
}
Question 14
Problem Statement:
Given an integer n, determine the number of distinct prime
factorizations of all numbers from 1 to n modulo 109+710^9+7.
Input:
The first line contains an integer n.
Output:
Print the result modulo 109+710^9+7.
Constraints:
1≤n≤1061 \leq n \leq 10^6
Example Input:
5
Example Output:
5
Solution in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> sieve(n + 1, 1);
vector<int> primeCount(n + 1, 0);
Question 15
Problem Statement:
You are given a string s containing only lowercase English
letters. Find the lexicographically smallest string that can be
obtained by removing exactly one character.
Input:
The first line contains a string s.
Output:
Print the lexicographically smallest string.
Constraints:
1≤∣s∣≤1051 \leq |s| \leq 10^5
Example Input:
abcde
Example Output:
abde
Solution in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
for (int i = 0; i < n - 1; i++) {
if (s[i] > s[i + 1]) {
s.erase(i, 1);
cout << s << endl;
return 0;
}
}
s.pop_back();
cout << s << endl;
return 0;
}
Question 16
Problem Statement:
Given a 2D grid of size N x M, find the maximum sum of any path
starting from the top-left corner (1,1) to the bottom-right corner
(N,M). You can only move right or down.
Input:
First line contains two integers N and M, the dimensions of the
grid.
Next N lines contain M integers each, representing the grid.
Output:
Single integer, the maximum sum.
Constraints:
1 ≤ N, M ≤ 1000
-10^6 ≤ Grid[i][j] ≤ 10^6
Example Input:
33
123
456
789
Example Output:
29
C++ Solution:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n, vector<int>(m));
vector<vector<int>> dp(n, vector<int>(m, 0));
dp[0][0] = grid[0][0];
for (int i = 1; i < n; i++) dp[i][0] = dp[i-1][0] + grid[i][0];
for (int j = 1; j < m; j++) dp[0][j] = dp[0][j-1] + grid[0][j];
Question 17
Problem Statement:
Find the number of pairs (i, j) such that 1 ≤ i < j ≤ N and A[i] + A[j] is
divisible by K.
Input:
First line contains two integers N and K.
Second line contains N integers A[i].
Output:
Single integer, the count of such pairs.
Constraints:
1 ≤ N ≤ 100000
1 ≤ K ≤ 1000
1 ≤ A[i] ≤ 10^9
Example Input:
53
12345
Example Output:
4
C++ Solution:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> a(n);
vector<int> freq(k, 0);
Question 17
Problem Statement:
A farmer is growing an orchard with N trees. The farmer needs to
divide the trees into K groups such that each group has at least one
tree, and the product of the number of trees in all groups is
maximized.
Input:
First line contains integers N and K.
Constraints:
1≤N,K≤1031 \leq N, K \leq 10^3.
Output:
Print the maximum product modulo 109+710^9 + 7.
Sample Input
10 3
Sample Output
36
Solution (C++)
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int main() {
int N, K;
cin >> N >> K;
Question 18
Problem Statement:
You have a list of N integers. Find the minimum cost to make all
elements in the list equal by either incrementing or decrementing a
number by 1.
Input:
First line contains integer N.
Second line contains N integers A[i]A[i].
Constraints:
1≤N≤1051 \leq N \leq 10^5
1≤A[i]≤1091 \leq A[i] \leq 10^9.
Output:
Print the minimum cost.
Sample Input
4
1 2 9 10
Sample Output
16
Solution (C++)
#include<bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) cin >> A[i];
sort(A.begin(), A.end());
int median = A[N / 2];
long long cost = 0;
Question 19
Problem Statement:
Given an array of integers, find the number of distinct pairs (i,j)(i, j)
such that A[i]+A[j]A[i] + A[j] is divisible by K.
Input:
First line contains integers N and K.
Second line contains N integers A[i]A[i].
Constraints:
1≤N≤1051 \leq N \leq 10^5
1≤K≤1051 \leq K \leq 10^5
1≤A[i]≤1091 \leq A[i] \leq 10^9.
Output:
Print the count of such pairs.
Sample Input
53
12345
Sample Output
4
Solution (C++)
#include<bits/stdc++.h>
using namespace std;
int main() {
int N, K;
cin >> N >> K;
Question 20
Problem Statement:
Find the total number of subarrays having an XOR equal to K.
Input:
First line contains integers N and K.
Second line contains NN integers A[i]A[i].
Constraints:
1≤N≤1051 \leq N \leq 10^5, 0≤K≤1090 \leq K \leq 10^9,
0≤A[i]≤1090 \leq A[i] \leq 10^9.
Output:
Print the total count of subarrays.
Sample Input
54
42264
Sample Output
4
Solution (C++)
#include<bits/stdc++.h>
using namespace std;
int main() {
int N, K;
cin >> N >> K;
vector<int> A(N);
for (int i = 0; i < N; i++) cin >> A[i];
int main() {
int N, M;
cin >> N >> M;
Question 22
Problem Statement:
You are given a string S of length N. Find the longest palindromic
substring in S.
Input:
First line contains string S.
Constraints:
1≤N≤1031 \leq N \leq 10^3.
Output:
Print the longest palindromic substring.
Sample Input
babad
Sample Output
bab
Solution (C++)
#include<bits/stdc++.h>
using namespace std;
string longestPalindrome(string S) {
int N = S.size(), start = 0, maxLength = 1;
vector<vector<bool>> dp(N, vector<bool>(N, false));
int main() {
string S;
cin >> S;
cout << longestPalindrome(S) << endl;
return 0;
}
Question 23
Problem Statement:
Given a tree with N nodes, each having a value, find the maximum
sum of values in a path from any node to any other node.
Input:
First line contains N.
Second line contains N integers (values of nodes).
Next N−1N-1 lines contain edges between nodes.
Constraints:
2≤N≤1052 \leq N \leq 10^5, values can be negative or positive.
Output:
Print the maximum sum path.
Sample Input
5
1 2 3 -2 -1
12
13
34
35
Sample Output
6
Solution (C++)
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> tree;
vector<int> values;
int maxSum = INT_MIN;
int main() {
int N;
cin >> N;
values.resize(N);
tree.resize(N + 1);
dfs(1, -1);
cout << maxSum << endl;
return 0;
}
Question 24
Problem Statement:
Given an array of integers, find the number of subarrays whose sum
is divisible by k.
Input:
First line contains integers N (length of array) and k.
Second line contains N integers representing the array.
Constraints:
1≤N≤1051 \leq N \leq 10^5
1≤k≤1031 \leq k \leq 10^3
−109≤array[i]≤109-10^9 \leq \text{array[i]} \leq 10^9
Output:
Print the count of subarrays whose sum is divisible by k.
Sample Input
45
1234
Sample Output
2
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N, k;
cin >> N >> k;
vector<int> arr(N);
for (int i = 0; i < N; i++) cin >> arr[i];
Question 25
Problem Statement:
Given an integer n, find the number of ways to partition n into the
sum of one or more positive integers. Two partitions that differ only
in the order of their summands are considered the same.
Input:
First line contains the integer n.
Constraints:
1≤n≤10001 \leq n \leq 1000
Output:
Print the number of distinct partitions of n.
Sample Input
5
Sample Output
7
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> dp(n + 1, 0);
dp[0] = 1;
Question 26
Problem Statement:
You are given a sequence of integers, and you need to find the
longest increasing subsequence (LIS) in the sequence.
Input:
First line contains the integer n (size of the sequence).
Second line contains the sequence of n integers.
Constraints:
1≤n≤1051 \leq n \leq 10^5
1≤arr[i]≤1091 \leq \text{arr}[i] \leq 10^9
Output:
Print the length of the longest increasing subsequence.
Sample Input
6
10 9 2 5 3 7
Sample Output
3
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
vector<int> lis;
for (int i = 0; i < n; i++) {
auto it = lower_bound(lis.begin(), lis.end(), arr[i]);
if (it == lis.end()) lis.push_back(arr[i]);
else *it = arr[i];
}
Question 27
Problem Statement:
You are given a matrix N x N representing a maze, where 1 represents
an open path and 0 represents a wall. Find the shortest path from
the top-left corner to the bottom-right corner, moving only through
open paths (1).
Input:
First line contains integer N.
Next N lines contain N integers representing the maze.
Constraints:
1≤N≤10001 \leq N \leq 1000
Output:
Print the length of the shortest path. If no path exists, print -1.
Sample Input
4
1010
1110
0101
1111
Sample Output
7
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
dist[0][0] = 0;
q.push({0, 0});
while (!q.empty()) {
int x = q.front().first, y = q.front().second;
q.pop();
return -1;
}
int main() {
int N;
cin >> N;
vector<vector<int>> maze(N, vector<int>(N));
int main() {
int N;
cin >> N;
vector<pair<int, pair<int, int>>> jobs(N);
vector<int> dp(N);
dp[0] = jobs[0].first;
Question 29
Problem Statement:
Given a string, find the length of the longest substring without
repeating characters.
Input:
A single string s.
Constraints:
1≤len(s)≤1051 \leq \text{len(s)} \leq 10^5
Output:
Print the length of the longest substring without repeating
characters.
Sample Input
abcabcbb
Sample Output
3
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> map;
int start = 0, maxLength = 0;
int main() {
string s;
cin >> s;
cout << lengthOfLongestSubstring(s) << endl;
return 0;
}
Question 30
Problem Statement:
Given an integer n, print all the prime numbers up to n.
Input:
A single integer n.
Constraints:
1≤n≤1061 \leq n \leq 10^6
Output:
Print all prime numbers from 1 to n.
Sample Input
10
Sample Output
2357
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
void sieveOfEratosthenes(int n) {
vector<bool> prime(n + 1, true);
prime[0] = prime[1] = false;
int main() {
int n;
cin >> n;
sieveOfEratosthenes(n);
return 0;
}
Question 31
Problem Statement:
You are given a list of integers. Find the maximum sum of a subarray
of length k.
Input:
First line contains integers n and k.
Second line contains the array of n integers.
Constraints:
1≤n≤1051 \leq n \leq 10^5
1≤k≤n1 \leq k \leq n
−105≤array[i]≤105-10^5 \leq \text{array[i]} \leq 10^5
Output:
Print the maximum sum of a subarray of length k.
Sample Input
53
21513
Sample Output
9
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
Question 32
Problem Statement:
You are given a list of integers, and you need to find the largest
product of three numbers in the list.
Input:
A single line containing n integers, the list of numbers.
Constraints:
3≤n≤10003 \leq n \leq 1000
−103≤array[i]≤103-10^3 \leq \text{array[i]} \leq 10^3
Output:
Print the largest product of any three numbers in the list.
Sample Input
-10 -10 5 2
Sample Output
500
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
sort(arr.begin(), arr.end());
Question 33
Problem Statement:
Given an array of integers, find the majority element (the element
that appears more than n / 2 times). If no such element exists, return
-1.
Input:
The first line contains integer n.
The second line contains n integers representing the array.
Constraints:
1≤n≤1051 \leq n \leq 10^5
−109≤array[i]≤109-10^9 \leq \text{array[i]} \leq 10^9
Output:
Print the majority element, or -1 if no majority element exists.
Sample Input
5
33424
Sample Output
-1
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
count = 0;
for (int num : nums) {
if (num == candidate) count++;
}
int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
Question 34
Problem Statement:
You are given an integer n. Find the number of trailing zeros in the
factorial of n.
Input:
A single integer n.
Constraints:
1≤n≤1051 \leq n \leq 10^5
Output:
Print the number of trailing zeros in n!.
Sample Input
5
Sample Output
1
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int trailingZeroes(int n) {
int count = 0;
while (n >= 5) {
n /= 5;
count += n;
}
return count;
}
int main() {
int n;
cin >> n;
cout << trailingZeroes(n) << endl;
return 0;
}
Question 35
Problem Statement:
Given a matrix of integers, find the number of distinct paths from the
top-left corner to the bottom-right corner. You can only move right or
down at any point in time.
Input:
First line contains two integers m and n, representing the
dimensions of the matrix.
The second line contains a matrix of size m x n.
Constraints:
1≤m,n≤1001 \leq m, n \leq 100
Output:
Print the number of distinct paths from top-left to bottom-right
corner.
Sample Input
33
000
000
000
Sample Output
6
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
cout << uniquePaths(m, n) << endl;
return 0;
}
Question 36
Problem Statement:
Find the length of the longest palindromic subsequence in a given
string.
Input:
A single string s.
Constraints:
1≤len(s)≤10001 \leq \text{len(s)} \leq 1000
Output:
Print the length of the longest palindromic subsequence.
Sample Input
bbabcbab
Sample Output
7
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int longestPalindromicSubseq(string s) {
int n = s.length();
vector<vector<int>> dp(n, vector<int>(n, 0));
int main() {
string s;
cin >> s;
cout << longestPalindromicSubseq(s) << endl;
return 0;
}
Question 37
Problem Statement:
Given a sorted array, remove the duplicates in-place such that each
element appears only once and return the new length of the array.
Input:
A sorted array of integers.
Constraints:
1≤n≤1041 \leq n \leq 10^4
Output:
Print the length of the array after removing duplicates.
Sample Input
112
Sample Output
2
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return j + 1;
}
int main() {
vector<int> nums;
int n, temp;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> temp;
nums.push_back(temp);
}
char firstUniqChar(string s) {
unordered_map<char, int> count;
for (char c : s) {
count[c]++;
}
for (char c : s) {
if (count[c] == 1) return c;
}
return '-1';
}
int main() {
string s;
cin >> s;
cout << firstUniqChar(s) << endl;
return 0;
}
Question 39
Problem Statement:
Find the minimum number of moves to reach the target number
from 1. In each move, you can multiply the current number by 2 or 3,
or subtract 1 from it.
Input:
A single integer target.
Constraints:
1≤target≤1051 \leq \text{target} \leq 10^5
Output:
Print the minimum number of moves to reach the target from
1.
Sample Input
10
Sample Output
4
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
while (!q.empty()) {
int num = q.front().first;
int steps = q.front().second;
q.pop();
return -1;
}
int main() {
int target;
cin >> target;
cout << minMoves(target) << endl;
return 0;
}
Question 40
Problem Statement:
Find the maximum area of a rectangle in a histogram.
Input:
The first line contains the integer n, the number of bars.
The second line contains the heights of the bars.
Constraints:
1≤n≤1051 \leq n \leq 10^5
1≤height[i]≤1031 \leq \text{height[i]} \leq 10^3
Output:
Print the maximum area of the rectangle.
Sample Input
5
21562
Sample Output
10
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
while (!s.empty()) {
int h = heights[s.top()];
s.pop();
int width = s.empty() ? i : i - s.top() - 1;
maxArea = max(maxArea, h * width);
}
return maxArea;
}
int main() {
int n;
cin >> n;
vector<int> heights(n);
for (int i = 0; i < n; i++) cin >> heights[i];
Question 41
Problem Statement:
Given a string s, return the number of distinct subsequences of s
which are palindromes.
Input:
A single string s.
Constraints:
1≤len(s)≤10001 \leq \text{len(s)} \leq 1000
Output:
Print the number of distinct palindromic subsequences.
Sample Input
aab
Sample Output
4
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int countPalindromicSubsequences(string s) {
int n = s.length();
vector<vector<int>> dp(n, vector<int>(n, 0));
int main() {
string s;
cin >> s;
cout << countPalindromicSubsequences(s) << endl;
return 0;
}
Question 42
Problem Statement:
Given an array of integers, find the maximum product of any two
integers.
Input:
A single array of integers nums.
Constraints:
2≤len(nums)≤1042 \leq \text{len(nums)} \leq 10^4
−103≤nums[i]≤103-10^3 \leq \text{nums[i]} \leq 10^3
Output:
Print the maximum product of any two integers.
Sample Input
31456
Sample Output
30
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums;
int n, temp;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> temp;
nums.push_back(temp);
}
Question 43
Problem Statement:
Given a number n, find the smallest number whose sum of digits
equals n and it has the minimum possible number of digits.
Input:
A single integer n.
Constraints:
1≤n≤10001 \leq n \leq 1000
Output:
Print the smallest number whose sum of digits equals n.
Sample Input
9
Sample Output
9
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int smallestNumber(int n) {
string result = "";
while (n > 9) {
result += '9';
n -= 9;
}
if (n > 0) result += to_string(n);
reverse(result.begin(), result.end());
return stoi(result);
}
int main() {
int n;
cin >> n;
cout << smallestNumber(n) << endl;
return 0;
}
Question 44
Problem Statement:
Find the maximum subarray sum in an array of integers.
Input:
A single array of integers nums.
Constraints:
1≤len(nums)≤1041 \leq \text{len(nums)} \leq 10^4
−103≤nums[i]≤103-10^3 \leq \text{nums[i]} \leq 10^3
Output:
Print the maximum subarray sum.
Sample Input
-2 1 -3 4 -1 2 1 -5 4
Sample Output
6
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return maxSum;
}
int main() {
vector<int> nums;
int n, temp;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> temp;
nums.push_back(temp);
}
Question 45
Problem Statement:
Given a binary tree, find the maximum depth of the tree.
Input:
A binary tree represented by a series of integers.
-1 represents a null node.
Constraints:
The number of nodes in the tree is at most 10510^5.
Output:
Print the maximum depth of the tree.
Sample Input
1 2 3 -1 5 -1 -1
Sample Output
3
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
// Building the tree
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->right = new TreeNode(5);
cout << maxDepth(root) << endl;
return 0;
}
Question 46
Problem Statement:
Find the longest common subsequence (LCS) between two strings.
Input:
Two strings s1 and s2.
Constraints:
1≤len(s1),len(s2)≤10001 \leq \text{len(s1)}, \text{len(s2)} \leq
1000
Output:
Print the length of the longest common subsequence.
Sample Input
abcde
ace
Sample Output
3
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return dp[m][n];
}
int main() {
string s1, s2;
cin >> s1 >> s2;
cout << longestCommonSubsequence(s1, s2) << endl;
return 0;
}
Question 47
Problem Statement:
Given a string, find all permutations of the string without repeating
characters.
Input:
A single string s.
Constraints:
1≤len(s)≤101 \leq \text{len(s)} \leq 10
Output:
Print all the distinct permutations of the string.
Sample Input
abc
Sample Output
abc
acb
bac
bca
cab
cba
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
set<string> result;
permute(s, 0, s.length() - 1, result);
for (const auto& str : result) {
cout << str << endl;
}
return 0;
}
Question 48
Problem Statement:
Find the intersection of two arrays. Each element in the result must
be unique.
Input:
Two arrays nums1 and nums2.
Constraints:
1≤len(nums1),len(nums2)≤10001 \leq \text{len(nums1)},
\text{len(nums2)} \leq 1000
Output:
Print the intersection of the two arrays.
Sample Input
1221
22
Sample Output
2
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return result;
}
int main() {
vector<int> nums1 = {1, 2, 2, 1};
vector<int> nums2 = {2, 2};
Question 49
Problem Statement:
Given an array of integers, return the indices of the two numbers
such that they add up to a specific target.
Input:
An array nums and an integer target.
Constraints:
2≤len(nums)≤1042 \leq \text{len(nums)} \leq 10^4
−103≤nums[i]≤103-10^3 \leq \text{nums[i]} \leq 10^3
The answer is guaranteed to be unique.
Output:
Print the indices of the two numbers.
Sample Input
[2, 7, 11, 15]
target = 9
Sample Output
01
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> result = twoSum(nums, target);
cout << result[0] << " " << result[1] << endl;
return 0;
}
Question 50
Problem Statement:
Check if a given string is a valid palindrome. Ignore spaces,
punctuation, and capitalization.
Input:
A single string s.
Constraints:
1≤len(s)≤1051 \leq \text{len(s)} \leq 10^5
Output:
Print true if the string is a valid palindrome, otherwise false.
Sample Input
A man, a plan, a canal, Panama
Sample Output
true
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string s) {
string cleanString = "";
for (char c : s) {
if (isalnum(c)) {
cleanString += tolower(c);
}
}
int main() {
string s;
getline(cin, s);
Question 51
Problem Statement:
Given a matrix of integers, find the sum of all elements in the matrix.
Input:
A matrix m x n.
Constraints:
1≤m,n≤10001 \leq m, n \leq 1000
Each integer in the matrix is between −103-10^3 and 10310^3.
Output:
Print the sum of all the elements in the matrix.
Sample Input
123
456
789
Sample Output
45
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
cout << sumMatrix(matrix) << endl;
return 0;
}
Question 52
Problem Statement:
Given a list of integers, find the first missing positive integer.
Input:
A list of integers nums.
Constraints:
1≤len(nums)≤10001 \leq \text{len(nums)} \leq 1000
−103≤nums[i]≤103-10^3 \leq \text{nums[i]} \leq 10^3
Output:
Print the smallest missing positive integer.
Sample Input
[1, 2, 0]
Sample Output
3
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return n + 1;
}
int main() {
vector<int> nums = {1, 2, 0};
cout << firstMissingPositive(nums) << endl;
return 0;
}
Question 53
Problem Statement:
Given a string s, return the length of the longest substring without
repeating characters.
Input:
A string s.
Constraints:
1≤len(s)≤1041 \leq \text{len(s)} \leq 10^4
Output:
Print the length of the longest substring without repeating
characters.
Sample Input
abcabcbb
Sample Output
3
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> map;
int left = 0, right = 0, maxLength = 0;
return maxLength;
}
int main() {
string s;
cin >> s;
Question 54
Problem Statement:
Given a non-empty array nums of integers, find the maximum
product of any two numbers.
Input:
An array nums of integers.
Constraints:
2≤len(nums)≤1042 \leq \text{len(nums)} \leq 10^4
−103≤nums[i]≤103-10^3 \leq \text{nums[i]} \leq 10^3
Output:
Print the maximum product of any two numbers.
Sample Input
[1, 2, 3, 4]
Sample Output
12
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
Question 55
Problem Statement:
Find the longest common prefix string amongst an array of strings. If
there is no common prefix, return an empty string.
Input:
An array of strings strs.
Constraints:
1≤len(strs)≤2001 \leq \text{len(strs)} \leq 200
0≤len(strs[i])≤2000 \leq \text{len(strs[i])} \leq 200
Output:
Return the longest common prefix.
Sample Input
["flower","flow","flight"]
Sample Output
"fl"
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << longestCommonPrefix(strs) << endl;
return 0;
}
Question 56
Problem Statement:
Reverse a linked list.
Input:
A singly linked list.
Constraints:
1≤len(linked list)≤1051 \leq \text{len(linked list)} \leq 10^5
Output:
Return the reversed linked list.
Sample Input
1 -> 2 -> 3 -> 4 -> 5
Sample Output
5 -> 4 -> 3 -> 2 -> 1
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
return prev;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
return 0;
}
Question 57
Problem Statement:
Find the kth largest element in an unsorted array.
Input:
An array of integers nums and an integer k.
Constraints:
1≤k≤len(nums)≤1041 \leq k \leq \text{len(nums)} \leq 10^4
−104≤nums[i]≤104-10^4 \leq \text{nums[i]} \leq 10^4
Output:
Print the kth largest element in the array.
Sample Input
[3, 2, 1, 5, 6, 4]
k=2
Sample Output
5
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return pq.top();
}
int main() {
vector<int> nums = {3, 2, 1, 5, 6, 4};
int k = 2;
Question 58
Problem Statement:
Given a string s and a dictionary of words wordDict, determine if the
string can be segmented into a space-separated sequence of one or
more dictionary words.
Input:
A string s and a list wordDict of words.
Constraints:
1≤len(s)≤10001 \leq \text{len(s)} \leq 1000
1≤len(wordDict)≤10001 \leq \text{len(wordDict)} \leq 1000
Output:
Return true if the string can be segmented, otherwise return
false.
Sample Input
s = "leetcode"
wordDict = ["leet", "code"]
Sample Output
true
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return dp[s.length()];
}
int main() {
string s = "leetcode";
vector<string> wordDict = {"leet", "code"};
Question 59
Problem Statement:
Given an array of integers nums, find the number of subarrays with
sum equal to k.
Input:
An array of integers nums and an integer k.
Constraints:
1≤len(nums)≤2×1041 \leq \text{len(nums)} \leq 2 \times 10^4
−107≤nums[i]≤107-10^7 \leq \text{nums[i]} \leq 10^7
Output:
Return the number of subarrays that sum to k.
Sample Input
nums = [1, 1, 1], k = 2
Sample Output
2
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
map[0] = 1;
int main() {
vector<int> nums = {1, 1, 1};
int k = 2;
Question 60
Problem Statement:
Given a list of integers nums, find the peak element. An element is a
peak if it is greater than its neighbors.
Input:
An array of integers nums.
Constraints:
1≤len(nums)≤10001 \leq \text{len(nums)} \leq 1000
1≤nums[i]≤1061 \leq \text{nums[i]} \leq 10^6
Output:
Return the index of a peak element.
Sample Input
[1, 2, 3, 1]
Sample Output
2
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return left;
}
int main() {
vector<int> nums = {1, 2, 3, 1};
cout << findPeakElement(nums) << endl;
return 0;
}
Question 61
Problem Statement:
Given an integer n, generate all the valid parentheses combinations.
Input:
An integer n.
Constraints:
1≤n≤101 \leq n \leq 10
Output:
Return a list of all combinations of well-formed parentheses.
Sample Input
n=3
Sample Output
["((()))", "(()())", "(())()", "()(())", "()()()"]
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
if (open < n) {
generateParenthesis(n, open + 1, close, s + "(", result);
}
vector<string> generateParenthesis(int n) {
vector<string> result;
generateParenthesis(n, 0, 0, "", result);
return result;
}
int main() {
int n = 3;
vector<string> result = generateParenthesis(n);
return 0;
}
Question 62
Problem Statement:
Given a string s, determine if it is a palindrome, considering only
alphanumeric characters and ignoring cases.
Input:
A string s.
Constraints:
0≤len(s)≤1050 \leq \text{len(s)} \leq 10^5
Output:
Return true if s is a palindrome, otherwise return false.
Sample Input
"A man, a plan, a canal: Panama"
Sample Output
true
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (!isalnum(s[left])) {
left++;
} else if (!isalnum(s[right])) {
right--;
} else if (tolower(s[left]) != tolower(s[right])) {
return false;
} else {
left++;
right--;
}
}
return true;
}
int main() {
string s = "A man, a plan, a canal: Panama";
cout << (isPalindrome(s) ? "true" : "false") << endl;
return 0;
}
Question 63
Problem Statement:
Given a non-empty array nums of integers, find the maximum sum of
a non-empty subarray.
Input:
An array of integers nums.
Constraints:
1≤len(nums)≤1051 \leq \text{len(nums)} \leq 10^5
−104≤nums[i]≤104-10^4 \leq \text{nums[i]} \leq 10^4
Output:
Return the maximum sum of the subarray.
Sample Input
[1, -2, 3, 4, -1, 2, 1, -5, 4]
Sample Output
8
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
return maxSum;
}
int main() {
vector<int> nums = {1, -2, 3, 4, -1, 2, 1, -5, 4};
cout << maxSubArray(nums) << endl;
return 0;
}
Question 64
Problem Statement:
Given a 2D matrix, find the sum of the elements in the submatrix
from (row1, col1) to (row2, col2), inclusive.
Input:
A 2D matrix matrix and four integers row1, col1, row2, col2.
Constraints:
1≤rows,cols≤1041 \leq \text{rows}, \text{cols} \leq 10^4
Output:
Return the sum of the elements in the submatrix.
Sample Input
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
row1 = 0, col1 = 0, row2 = 2, col2 = 2
Sample Output
45
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
class NumMatrix {
public:
vector<vector<int>> prefixSum;
NumMatrix(vector<vector<int>>& matrix) {
int rows = matrix.size(), cols = matrix[0].size();
prefixSum.resize(rows + 1, vector<int>(cols + 1, 0));
int main() {
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8,
9}}; NumMatrix numMatrix(matrix); cout <<
numMatrix.sumRegion(0, 0, 2, 2) << endl; // Output: 45 return 0; }
---