Max 1's Row in Binary Matrix
Max 1's Row in Binary Matrix
"Find the row with the maximum number of 1's in a binary matrix where each row is sorted."
🔍 Problem Summary:
Given a 2D binary matrix where each row is sorted in non-decreasing order (i.e., all 0's come before
1's), find the index of the row with the maximum number of 1's.
Move left if you see a 1 (to count more 1's in the row).
Move down if you see a 0 (because rows are sorted, no more 1’s in this row to the left).
🧠 Intuition:
Since each row is sorted, the first 1 you see in a row means all elements to the right are also
1's.
So the more left you go, the more 1's the row has.
int maxOnes = 0;
j--;
return maxRowIndex;
}
🔄 Example:
matrix = [
[0, 0, 1, 1],
[0, 1, 1, 1],
[0, 0, 0, 1]
Sure! Here's each question with input, output, explanation, and C++ code for clear understanding.
✅ Explanation:
Replace each element with the maximum element to its right. Last element becomes -1.
16 → max(17,4,3,5,2) = 17
17 → max(4,3,5,2) = 5
4 → max(3,5,2) = 5
3 → max(5,2) = 5
5 → max(2) = 2
2 → -1
✅ C++ Code:
int n = [Link]();
arr[i] = maxRight;
maxRight = max(maxRight, temp);
return arr;
Output: 3
✅ Explanation:
✅ C++ Code:
int leftSum = 0;
leftSum += arr[i];
return -1;
Input:
123
456
789
Output: 1 2 4 7 5 3 6 8 9
✅ Explanation:
Traverse diagonally in zig-zag:
→ 1 (↘), 2-4 (↙), 7-5-3 (↘), 6-8 (↙), 9
✅ C++ Code:
vector<int> res;
if (d % 2 == 0) {
} else {
return res;
🔁 4. Alternate Sorting
Input: {1, 2, 3, 4, 5, 6, 7}
Output: {7, 1, 6, 2, 5, 3, 4}
✅ Explanation:
Sorted: 1 2 3 4 5 6 7
Output: 7,1,6,2,5,3,4
✅ C++ Code:
sort([Link](), [Link]());
int i = 0, j = [Link]() - 1;
vector<int> res;
while (i <= j) {
if (i != j) {
res.push_back(arr[j--]);
res.push_back(arr[i++]);
} else {
res.push_back(arr[i++]);
return res;
✅ Explanation:
24 → 2*4 = 8
71 → 7*1 = 7
10 → has 0 → 1+0 = 1
59 → 5*9 = 45
✅ C++ Code:
vector<int> res;
if (d == 0) hasZero = true;
sum += d;
product *= d;
temp /= 10;
return res;
✅ Goal:
In the second loop, use the hash to find neighbors and set them to 0.
cpp
CopyEdit
#include <iostream>
const int M = 3;
const int N = 3;
if (mat[i][j] == 1)
hash[i][j] = true;
if (hash[i][j]) {
if (j > 0) mat[i][j - 1] = 0;
if (j < N - 1) mat[i][j + 1] = 0;
int main() {
int mat[M][N] = {
{1, 2, 3},
{4, 1, 6},
{7, 8, 9}
};
setNeighborsToZero(mat);
return 0;
✅ Output:
CopyEdit
103
010
789
🔹Problem:
Change all connected oldColor values starting from (x, y) to newColor.
🔹Input:
cpp
CopyEdit
image = {
{1,1,1},
{1,1,0},
{1,0,1}
x = 1, y = 1, newColor = 2
🔹Output:
CopyEdit
222
220
201
cpp
CopyEdit
void dfs(vector<vector<int>>& image, int i, int j, int oldColor, int newColor) {
return;
image[i][j] = newColor;
dfs(image,i+1,j,oldColor,newColor);
dfs(image,i-1,j,oldColor,newColor);
dfs(image,i,j+1,oldColor,newColor);
dfs(image,i,j-1,oldColor,newColor);
if(image[sr][sc] != color)
return image;
🔹Problem:
Return "Yes" if a path exists from top-left to bottom-right, moving only right or down.
🔹Input:
CopyEdit
11000
01100
00110
00011
00001
🔹Output: "Yes"
🔹Code:
cpp
CopyEdit
🔹Problem:
Count groups of connected 1s. Neighbors are 8-directional.
🔹Input:
diff
CopyEdit
1 -1 -1 1
-1 1 -1 1
-1 -1 1 -1
-1 -1 -1 1
🔹Output: 2
🔹Code:
cpp
CopyEdit
int n = [Link]();
if(dx || dy)
int count = 0;
if(grid[i][j] == 1) {
dfs(grid, i, j);
count++;
return count;
Here are all five string manipulation and parsing problems implemented in C++ without using
inbuilt string functions like substr, stoi, getline, etc.
Each problem includes input/output handling (I/O).
Input: Java1234
Output: Javb1234
#include <iostream>
void task10() {
char s[100];
cin >> s;
while (seen[(int)s[i]]) {
s[i]++;
}
seen[(int)s[i]] = true;
Input:
st
Output:
#include <iostream>
return true;
void task11() {
[Link]();
[Link](line, 200);
char words[20][20];
int i = 0, k = 0, j = 0;
words[k][j++] = line[i];
} else {
words[k][j] = '\0';
k++; j = 0;
i++;
words[k][j] = '\0';
int total = k + 1;
if (startsWith(words[i], match)) {
idx[idxCount++] = i;
int a = idx[i];
char temp[20];
temp[x] = words[a][x];
words[a][x] = words[b][x];
words[b][x] = temp[x];
Input:
4.8.2
4.8.4
Output: upgraded
int num = 0;
i++;
return num;
void task12() {
int i = 0, j = 0;
return;
return;
Input:
Hacker
Rank
Output:
Hce akr
Rn ak
int l = 0;
while (s[l] != '\0') l++;
return l;
void task13() {
Input: PROGRAM
Output:
P P
R R
OO
G
RR
A A
M M
void spaces(int n) {
void task14() {
char s[20];
cin >> s;
spaces(space);
if (i != mid) {
int main() {
task11();
task12();
task13();
task14();
return 0;
Would you like me to combine all these into a single .cpp file for download or editing?
Here are the detailed C++ implementations with Input, Output, Explanation, and Iteration for
problems 15 to 18:
#include <iostream>
#include <vector>
if (target == 0) {
for (int val : current) cout << val << " ";
return;
current.push_back(nums[index]);
current.pop_back();
int main() {
int target = 6;
vector<int> current;
cout << "Subsets with sum " << target << ":\n";
return 0;
✅ Iteration Explanation:
Input:
o Money = 40
o Price = 1
Approach: Simulation
#include <iostream>
int main() {
total += extra;
cout << "total: " << total << ", wrappers: " << wrappers << endl;
return 0;
✅ Iteration Explanation:
Initially: 40 chocolates.
#include <vector>
#include <algorithm>
sort([Link](), [Link]());
int i = 0, j = [Link]() - 1;
int trips = 0;
while (i <= j) {
i++;
j--;
trips++;
return trips;
int main() {
int limit = 5;
cout << "Minimum trips: " << minBikeTrips(people, limit) << endl;
return 0;
✅ Iteration Explanation:
Sort: {3, 3, 4, 5}
Start: 4 5
Moves: U L R R D D U L R
Output: 5 5
#include <iostream>
int main() {
int x = 4, y = 5;
cout << "Final Position: " << x << " " << y << endl;
return 0;
✅ Iteration:
U → (3,5)
L → (3,4)
R → (3,5)
R → (3,6)
D → (4,6)
D → (5,6)
U → (4,6)
L → (4,5)
R → (4,6)
✅ Final → (5,5)
Here are the C++ solutions for the problems you listed, covering sorting, palindrome checks, string
manipulations, and expressions:
1. Sorting
Code:
#include <iostream>
#include <vector>
#include <algorithm>
int countFactors(int n) {
int count = 0;
if (n % i == 0) {
count++;
return count;
int main() {
return 0;
Input:
2*3
2^2^2
35
3*1
Output:
3*1
2*3
2^2^2
35
Code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
// This example handles basic arithmetic, more complex cases can be handled by parsing and
evaluating the expression
int res = 0;
int main() {
return 0;
Input: 121
Output: Palindrome
Code:
#include <iostream>
while (num != 0) {
num /= 10;
int main() {
if (isPalindrome(num)) {
} else {
return 0;
Output: True
Code:
#include <iostream>
#include <cctype>
bool isPalindrome(string s) {
int left = 0, right = [Link]() - 1;
if (!isalnum(s[left])) {
left++;
} else if (!isalnum(s[right])) {
right--;
return false;
} else {
left++;
right--;
return true;
int main() {
if (isPalindrome(str)) {
} else {
return 0;
3. String Manipulation
Input: "a,b$c"
Output: "c,b$a"
Code:
#include <iostream>
#include <string>
string reverseString(string s) {
if (!isalnum(s[left])) {
left++;
} else if (!isalnum(s[right])) {
right--;
} else {
swap(s[left], s[right]);
left++;
right--;
return s;
int main() {
return 0;
Output: True
Code:
#include <iostream>
#include <unordered_set>
using namespace std;
bool isPangram(string s) {
unordered_set<char> letters;
for (char c : s) {
if (isalpha(c)) {
[Link](tolower(c));
int main() {
if (isPangram(str)) {
} else {
return 0;
Input: "Qwerty@123"
Output: Strong
Code:
#include <iostream>
#include <cctype>
return hasUpper && hasLower && hasDigit && hasSpecial && [Link]() >= 8;
int main() {
if (isStrongPassword(password)) {
} else {
return 0;
Input:
Main = "ZOHOCORPORATION"
Sub = "PORT"
Output:
OHOCORPORAT
Code:
#include <iostream>
if (pos != string::npos) {
[Link](pos, [Link]());
return mainStr;
int main() {
return 0;
Output: exprIece
Code:
#include <iostream>
#include <unordered_set>
string result;
if ([Link](c) == [Link]()) {
result.push_back(c);
return result;
int main() {
string s1 = "expErIence";
string s2 = "En";
return 0;
These C++ code snippets should cover the problems you mentioned, including sorting, palindrome
checks, string manipulations, and basic expression evaluation.
Here are C++ examples for the problems you listed. I'll walk you through a few of them in detail:
✅ 4. Matrix
The problem asks for the shortest path in a matrix from the top-left corner to the bottom-right
corner, but you can only move right or down.
Approach:
2. Create a matrix where each cell stores the minimum number of steps required to reach that
cell.
#include <iostream>
#include <vector>
int m = [Link]();
int n = matrix[0].size();
// Create a DP matrix
return dp[m-1][n-1];
int main() {
return 0;
Explanation:
DP Matrix Initialization: The top row and leftmost column are filled with 1 because there is
only one way to move to those positions.
DP Matrix Filling: Every other cell is filled with the sum of the values from the top and left
cells (i.e., the number of ways to reach that position).
The answer is at dp[m-1][n-1], which gives the number of ways to reach the bottom-right
corner.
#include <iostream>
#include <vector>
using namespace std;
int sum = 0;
int n = [Link]();
sum += matrix[i][n-i-1];
return sum;
int main() {
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
cout << "Diagonal Sum: " << diagonalSum(matrix) << endl; // Output: 38
return 0;
Explanation:
For an n x n matrix, the anti-diagonal elements are those where the row index i and column
index are related by n - 1 - i.
✅ 5. Pattern Printing
The problem asks to print a diamond pattern with stars, given a number n representing the number
of rows.
C++ Code Example:
#include <iostream>
void printDiamond(int n) {
int main() {
int n = 3;
return 0;
Explanation:
Output:
***
*****
***
#include <iostream>
#include <unordered_set>
unordered_set<char> seen;
// Loop through the string and add unique characters to the result
if ([Link](c) == [Link]()) {
[Link](c);
result += c;
return result;
int main() {
cout << "Unique Characters: " << uniqueChars(str) << endl; // Output: abc
return 0;
}
Explanation:
The unordered_set is used to track characters that have already been seen.
Output:
Given an array, the problem asks to double the non-zero elements and push all zeros to the end.
#include <iostream>
#include <vector>
int n = [Link]();
int index = 0;
if (arr[i] != 0) {
arr[index++] = 0;
}
int main() {
doubleAndZeroArrangement(arr);
for (int num : arr) cout << num << " ";
return 0;
Explanation:
Output:
4 2 12 8 0 0 0 0 0
✅ 8. Prime/Number Theory
The problem asks if a given number is a Twisted Prime. A Twisted Prime is a prime number whose
reverse is also prime.
#include <iostream>
#include <cmath>
return true;
int reversed = 0;
num /= 10;
return reversed;
if (isPrime(num)) {
return isPrime(reversed);
return false;
int main() {
if (isTwistedPrime(num)) {
} else {
cout << num << " is not a Twisted Prime" << endl;
return 0;
}
Explanation:
Reverse the number and check if the reversed number is also prime.
Output:
97 is a Twisted Prime
Let me know if you'd like more detailed explanations or further examples for other problems!
Yes! Here's another C++ approach that’s cleaner and uses a helper function with vector storage to
collect all results. This makes it easier if you want to use the decoded values later (e.g., return from a
function or store in a list for UI).
#include <iostream>
#include <vector>
#include <string>
vector<string> results;
// Backtracking function
if (index == [Link]()) {
results.push_back(path);
return;
// Single digit
int oneDigit = digits[index] - '0';
// Two digits
decodeHelper(digits, 0, "");
return results;
int main() {
cout << "All possible decodings for \"" << input << "\":" << endl;
return 0;
}
✅ Output:
aabc
aaw
alc
kbc
kw
Would you like a dynamic programming version for this to optimize overlapping subproblems as
well?
Let me break down the solution and the approach behind it in a simpler way:
Problem Overview:
The wildcard * can match zero or more characters in str1. You need to check if str1 can be matched
by str2, where * in str2 can match any sequence of characters (including empty sequences).
We are going to use dynamic programming (DP) to solve this problem efficiently. The idea is to
create a table (2D array) to track whether the first i characters of str1 can be matched with the first j
characters of str2. Here's how we do it step by step:
Steps:
1. Create a DP Table:
We will create a 2D table dp where dp[i][j] tells us whether the first i characters of str1 can
be matched with the first j characters of str2.
The dimensions of this table will be (n+1) x (m+1) where n is the length of str1 and m is the
length of str2. We add 1 extra row and column to handle the base case (matching empty
strings).
2. Base Case:
dp[0][0] = true: This means that empty str1 matches empty str2.
For the first row (dp[0][j]): If str2 starts with *, then * can match an empty sequence of
characters. So, if str2 starts with a series of *, we mark the corresponding dp[0][j] as true.
2. If str2[j-1] == '*': This means that * can match zero or more characters from
str1. So, we can:
4. Result:
The final result is stored in dp[n][m]. If dp[n][m] is true, then str1 can be matched with str2
using the wildcard *. Otherwise, it cannot.
str1 = "baaabab"
str2 = "ba*ab"
We want to check if str1 can match str2 where * can match any sequence of characters.
Step-by-step Explanation:
o Create a table dp[8][6] (since str1 has length 7 and str2 has length 5, we add 1 to
each for the base case).
For each character, we either match directly or use * to match zero or more characters.
3. Final DP Table:
After filling the table, if dp[n][m] is true, then str1 can be matched with str2.
Code Flow:
#include <iostream>
#include <vector>
#include <string>
int n = [Link]();
int m = [Link]();
dp[0][0] = true;
if (str2[j - 1] == '*') {
int main() {
if (isSubstringWithWildcard(str1, str2)) {
} else {
return 0;
Final Output:
str1 = "baaabab"
str2 = "ba*ab"
Match found!
This means str1 matches str2 with the wildcard * properly matching multiple characters in str1.
Conclusion:
DP Table: Keeps track of matches for substrings of both str1 and str2.
Wildcard Handling (*): Allows zero or more characters to be matched, which is handled by
two cases in the DP logic.
Here’s the C++ implementation for the Maximum Subarray Sum problem using Kadane’s Algorithm:
C++ Code:
#include <iostream>
#include <vector>
#include <algorithm>
// Update current_sum: Either start a new subarray with arr[i] or add arr[i] to the existing
subarray
return max_sum;
int main() {
cout << "Maximum sum of subarray is: " << result << endl;
return 0;
Explanation of Code:
1. Initialization:
o max_sum is initialized with the first element of the array because that’s the smallest
possible sum.
o current_sum is initialized with the first element to keep track of the sum of the
current subarray.
o We then compare max_sum with current_sum to keep track of the highest sum
encountered.
3. Return the result: Once the loop is done, max_sum will contain the maximum subarray sum.
Example Walkthrough:
1. Initialize:
current_sum = max(1, -2 + 1) = 1
max_sum = max(-2, 1) = 1
current_sum = max(4, -2 + 4) = 4
max_sum = max(1, 4) = 4
max_sum = max(4, 3) = 4
current_sum = max(2, 3 + 2) = 5
max_sum = max(4, 5) = 5
current_sum = max(1, 5 + 1) = 6
max_sum = max(5, 6) = 6
max_sum = max(6, 1) = 6
current_sum = max(4, 1 + 4) = 5
max_sum = max(6, 5) = 6
Output:
This approach runs in O(n) time and uses O(1) extra space, making it an optimal solution for this
problem.
Here’s the C++ code for solving the Longest Common Subsequence (LCS) problem using Dynamic
Programming:
#include <iostream>
#include <vector>
#include <string>
int m = [Link]();
int n = [Link]();
// Create a 2D DP table
} else {
// If they don't match, take the max of the previous LCS values
return dp[m][n];
int main() {
string X = "AGGTAB";
string Y = "GXTXAYB";
cout << "Length of Longest Common Subsequence: " << longestCommonSubsequence(X, Y) <<
endl;
return 0;
1. Input Strings: We are given two strings X and Y. In the code, they are "AGGTAB" and
"GXTXAYB".
2. DP Table Initialization:
o The loop runs from 1 to m for X and 1 to n for Y. For each pair of indices (i, j), we
compare X[i-1] and Y[j-1] (since the indices in the DP table are shifted by 1).
o If they don't match, the LCS length at dp[i][j] will be the maximum of dp[i-1][j] and
dp[i][j-1].
4. Final Answer: The value of dp[m][n] will contain the length of the longest common
subsequence.
Example Output:
string X = "AGGTAB";
string Y = "GXTXAYB";
Would you like to see additional improvements, or do you need further clarifications on this
solution?