Hands-On - Problem Solving - Day 06 - Key
Hands-On - Problem Solving - Day 06 - Key
Exercise No. : VI
Topics Covered :Basic Math, Control Flow, Arrays, Strings, Functions, Bit
Manipulation
Date : 20.02.2025
1. Ways To Express
Problem statement : You are given the number ‘N’. The task is to find the number
of ways to represent ‘N’ as a sum of two or more consecutive natural numbers.
Example:
N=9
‘9’ can be represented as:
2+3+4=9
4+5=9
The number of ways to represent ‘9’ as a sum of consecutive natural numbers is ‘2’.
So, the answer is ‘2’.
Note:
1. The numbers used to represent ‘N’ should be natural numbers (Integers greater
than equal to 1).
Sample Input 1:
2
21
15
Sample Output 1:
3
3
Explanation Of Sample Input 1:
Test Case 1:
‘21’ can be represented as:
1 + 2 + 3 + 4 + 5 + 6 = 21
Little practice is worth more than a ton of theory
1
PROBLEM SOLVING
SDE Readiness Training
6 + 7 + 8 = 21
10 + 11 = 21
The number of ways to represent ‘21’ as a sum of consecutive natural numbers is
‘3’. So, the answer is ‘3’.
Test Case 2:
‘15’ can be represented as:
1 + 2 + 3 + 4 + 5 = 15
4 + 5 + 6 = 15
7 + 8 = 15
The number of ways to represent ‘15’ as a sum of consecutive natural numbers is
‘3’. So, the answer is ‘3’.
Sample Input 2:
2
18
16
Sample Output 2:
2
0
Constraints:
1 <= T <= 1000
3 <= N <= 10 ^ 5
Where ‘T’ is the number of test cases, and ‘N’ is the given number.
Sample Code:
General solution :
import java.util.Scanner;
Input 1 : rows = 5
Output 1:
* *
** **
*** ***
**** ****
**********
**** ****
*** ***
** **
* *
Input 2: rows =7
Output 2 :
Sample Code:
Solution :
System.out.println();
}
System.out.println();
}
}
Problem statement: Rita has to design a code that takes a positive integer or number
which is required to be given by the user. Then the code should further identify whether
that digit can be expressed as the sum of two prime numbers. If the inserted number
can be expressed as sum of two prime numbers then, print the integer can be expressed
as sum of two prime numbers as a result.
Sample Input 1: 34
Little practice is worth more than a ton of theory
6
PROBLEM SOLVING
SDE Readiness Training
Sample Output 1:3,31
Sample Input1: 20
Constraints:
• N>=1
Sample Code:
General solution:
return true;
}
Alternate Solution:
import java.util.Scanner;
class Main {
isPrime[i] = true;
// If p is prime
if (isPrime[p] == true) {
isPrime[i] = false;
return false;
}
Little practice is worth more than a ton of theory
8
PROBLEM SOLVING
SDE Readiness Training
SieveOfEratosthenes(n, isPrime);
return;
// Call the method to find the pair of prime numbers that sum up to 'n'
findPrimePair(n);
Problem Statement : Given an integer array nums, return the sum of floor(nums[i] /
nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer
may be too large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then
sum them up.
Example 2:
Input: nums = [7,7,7,7,7,7,7]
Output: 49
Constraints:
● 1 <= nums.length <= 10^5
● 1 <= nums[i] <= 10^5
Sample Code:
General Solution :
int pre[] = new int[max + 1]; // Array to store prefix sum of frequencies
Examples :
Sample Code:
General Solution:
import java.io.*;
class GFG {
//XOR toggles the bits and will form a number that will have
//set bits at the places where the numbers bits differ
//eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
return diff;
}
//Kernighan algo
static int countSetBits(int n){
int count = 0; // `count` stores the total bits set in `n`
while (n != 0) {
n = n & (n - 1); // clear the least significant bit set
count++;
}
return count;
}
import java.io.*;
class GFG {
static int sumBitDifferences(int arr[], int n)
{
int ans = 0; // Initialize result
// traverse over all bits
for (int i = 0; i < 32; i++) {
// count number of elements with i'th bit set
int count = 0;
for (int j = 0; j < n; j++)
if ((arr[j] & (1 << i)) != 0)
count++;
// Add "count * (n - count) * 2"
// to the answer...(n - count = unset bit count)
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver program
public static void main(String args[])
{
int arr[] = { 1, 3, 5 };
int n = arr.length;
System.out.println(sumBitDifferences(arr, n));
}
}
6. Minimum X (xor) A
Problem Statement : Given two integers A and B, the task is to find an integer X such
that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of
set bits in B.
Example 1:
Input:
A = 3, B = 5
Output: 3
Explanation:
Binary(A) = Binary(3) = 011
Binary(B) = Binary(5) = 101
The XOR will be minimum when x = 3
i.e. (3 XOR 3) = 0 and the number
of set bits in 3 is equal
to the number of set bits in 5.
Example 2:
Input:
A = 7, B = 12
Output: 6
Explanation:
(7)2= 111
(12)2= 1100
The XOR will be minimum when x = 6
i.e. (6 XOR 7) = 1 and the number
of set bits in 6 is equal to the
number of set bits in 12.
Constraints :
0 <= A, B <= 10^9
Sample Code:
General Solution :
class Solution{
// Method to find the minimum value
public static int minVal(int a, int b) {
// Counting the number of set bits in b
int setBits = Integer.bitCount(b);
// Counting the number of set bits in a
int setBits1 = Integer.bitCount(a);
// If i'th bit is not set and number of set bits in b is greater than set bits
in a
// Then set the i'th bit in the answer number and decrement the setBits
count
if (set == 0 && setBits > setBits1) {
ans |= (mask);
setBits--;
}
// If i'th bit is set and number of set bits in a is greater than set bits in b
// Then decrement the setBits1 count
else if (set!=0 && setBits1 > setBits) {
setBits1--;
}
// If none of the conditions are met, then set the i'th bit in the answer
number as same as in a
else {
ans |= set;
}
}
Example 1:
Input:
m = 3, n = 4
array1[] = {1,5,9}
array2[] = {2,3,6,7}
Output: 5
Explanation: The middle element for {1,2,3,5,6,7,9} is 5
Example 2:
Input:
m = 2, n = 4
array1[] = {4,6}
array2[] = {1,2,3,5}
Output: 3.5
Constraints:
0 ≤ m,n ≤ 10^6
1 ≤ array1[i], array2[i] ≤ 10^9
Sample Code:
General Solution 1 :
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length;
int m = nums2.length;
int i = 0, j = 0, m1 = 0, m2 = 0;
// Find median.
for (int count = 0; count <= (n + m) / 2; count++) {
m2 = m1;
if (i != n && j != m) {
if (nums1[i] > nums2[j]) {
m1 = nums2[j++];
} else {
m1 = nums1[i++];
}
if (n % 2 == 1)
return nums3[n / 2];
else {
double median = (double) (nums3[(n - 1) / 2] + nums3[n / 2]) /
2.0;
return median;
}
}
}
Alternate solution :
import java.util.Arrays; // Importing Arrays class
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Combine arrays nums1 and nums2
int[] arr = new int[nums1.length + nums2.length];
System.arraycopy(nums1, 0, arr, 0, nums1.length);
System.arraycopy(nums2, 0, arr, nums1.length, nums2.length);
Problem statement : You are given an array containing ‘N’ integers. In the array, the
elements are 0, 1 and 2. You have a simple task, find the count of non-empty subarrays
containing an equal number of 0’s, 1’s and 2’s.
The subarray of ARR is a contiguous part of the array ARR, i. e. the array ARRi, ARRi+1,
. . . . . , ARRj for some 0 ≤ i ≤ j ≤ N - 1.
For Example :
There are exactly two subarrays that contain an equal number of 0’s, 1’s and 2’s.
Sample Input 1 :
11021
Sample Output 1 :
There are exactly two subarrays that contain an equal number of 0’s, 1’s and
2’s.
The first subarray is from ARR[1] to ARR[3], ie: {1, 0, 2}, and the second
subarray is from ARR[2] to ARR[4], ie: {0, 2, 1}
The input array doesn’t contain any element equal to 2, so it’s impossible to
form a non-empty subarray with an equal number of 0’s, 1’s and 2’s.
Sample Input 2 :
102102
110022
Sample Output 2 :
Constraints :
1 ≤ T ≤ 10
ARR[i] = {0, 1, 2}
Sample Code
int ans = 0;
// Initialize variables to store the count of 0's, 1's and 2's so far.
if (arr[i] == 0) {
cnt0++;
} else if (arr[i] == 1) {
cnt1++;
} else if (arr[i] == 2) {
cnt2++;
prefix0[i] = cnt0;
prefix1[i] = cnt1;
prefix2[i] = cnt2;
ans++;
// Count of 0's in stored in cnt0, similarly for cnt1 and cnt2 also.
ans++;
return ans;
Problem Statement : Given a 0-indexed integer array nums of length n and an integer
k, return the number of pairs (i, j) such that:
● 0 <= i < j <= n - 1 and
● nums[i] * nums[j] is divisible by k.
Example 1:
Input: nums = [1,2,3,4,5], k = 2
Output: 7
Explanation:
The 7 pairs of indices whose corresponding products are divisible by 2 are (0, 1),
(0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).
Their products are 2, 4, 6, 8, 10, 12, and 20 respectively.
Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which
are not divisible by 2.
Example 2:
Input: nums = [1,2,3,4], k = 5
Output: 0
Explanation: There does not exist any pair of indices whose corresponding
product is divisible by 5.
Constraints:
● 1 <= nums.length <= 10^5
● 1 <= nums[i], k <= 10^5
Sample code :
General solution :
class Solution {
public long countPairs(int[] nums, int k) {
// Initialize an array to count the occurrences of each gcd value
int[] counts = new int[k + 1];
return sum;
}
Alternate solution :
class Solution {
public long countPairs(int[] nums, int k) {
long cnt = 0; // Initialize the count of pairs
Problem Statement : Given an array arr[] of N elements and a number K., split the
given array into K subarrays such that the maximum subarray sum achievable out of K
subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4, which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
Little practice is worth more than a ton of theory
28
PROBLEM SOLVING
SDE Readiness Training
This results in a maximum sum subarray of 2.
Constraints:
1 ≤ N ≤ 10^5
1≤K≤N
1 ≤ arr[i] ≤ 10^4
Sample Code:
General solution :
class Solution {
// Check if splitting array into K subarrays with max sum mid is possible
static boolean isPossible(int[] arr, int mid, int k) {
int sub_array = 1, sum = 0;
for (int num : arr) {
sum += num;
if (sum > mid) {
sub_array++;
sum = num;
}
}
return sub_array <= k;
}
// Binary search
while (low < high) {
long mid = low + (high - low) / 2; // Calculate mid
int count = getCount(arr, N, mid); // Get count of subarrays with
sum <=
mid
Example 1:
Input:
N=7
arr[] = {8,-8,9,-9,10,-11,12}
Output:
22
Explanation:
Starting from the last element of the array, i.e, 12, and moving in a circular
fashion, we have max subarray as 12, 8, -8, 9, -9, 10, which gives maximum
sum as 22.
Example 2:
Input:
N=8
arr[] = {10,-3,-4,7,6,5,-4,-1}
Output:
Little practice is worth more than a ton of theory
31
PROBLEM SOLVING
SDE Readiness Training
23
Explanation: Sum of the circular subarray with maximum sum is 23
Constraints:
1 <= N <= 10^6
-10^6 <= Arr[i] <= 10^6
Sample Code:
General Solution :
class Solution {
public int maxSubarraySumCircular(int[] nums) {
int maxSum = nums[0]; // Maximum sum of subarray
int minSum = nums[0]; // Minimum sum of subarray
int currentSum1 = 0; // Current sum of subarray for the maximum
sum calculation
int currentSum2 = 0; // Current sum of subarray for the minimum
sum calculation
int totalSum = 0; // Total sum of all elements in the array
// If the total sum equals the minimum sum, it means all elements are
negative,
// so return the maximum element as the result
if (totalSum - minSum == 0) {
return maxSum;
}
// Otherwise, return the maximum of the non-circular and circular sum
return Math.max(maxSum, totalSum - minSum);
}
}
Alternate Solution 1:
class GFG {
// Function to find the maximum circular sum of an array
public static int maxCircularSum(int a[], int n) {
// Corner Case: if there's only one element in the array
if (n == 1)
return a[0];
Alternate solution 2:
class Solution {
// Function to find maximum circular subarray sum
public int maxSubarraySumCircular(int[] nums) {
// Initialize variables
int total = 0, maxSum = nums[0], curMax = 0, minSum = nums[0],
curMin = 0;
12.Print Spiral
Problem statement : For a given two-dimensional integer array/list of size (N x M), print
it in a spiral form. That is, you need to print in the order followed for every iteration:
a. First row(left to right)
b. Last column(top to bottom)
c. Last row(right to left)
d. First column(bottom to top)
Mind that every element will be printed only once.
Sample Input 1:
1
Constraints :
1 <= t <= 10^2
0 <= N <= 10^3
0 <= M <= 10^3
Sample Code:
General Solution :
int n = matrix.length;
if(n == 0) return;
int m = matrix[0].length;
if(tr > br) break; // Break if top row index crosses bottom row
index
count++;
if(lc > rc) break; // Break if left column index crosses right
column index
count++;
}
Little practice is worth more than a ton of theory
37
PROBLEM SOLVING
SDE Readiness Training
rc--; // Move the right column index to the left
if(tr > br) break; // Break if top row index crosses bottom row
index
count++;
if(lc > rc) break; // Break if left column index crosses right
column index
count++;
Alternate Solution :
P A H N
APLSIIG
Y I R
Write the code that will take a string and make this conversion given a number of rows:
Example 1:
Output: "PAHNAPLSIIGYIR"
Example 2:
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A LS IG
YA HR
Little practice is worth more than a ton of theory
40
PROBLEM SOLVING
SDE Readiness Training
P I
Constraints:
Sample Code:
General Solution:
class Solution {
public String convert(String s, int numRows) {
// If numRows is 1, return the original string
if (numRows == 1) return s;
// For rows between the first and last row, add additional characters
if (i > 0 && i < numRows - 1 && j + x - 2 * i < len) {
c[k++] = s.charAt(j + x - 2 * i);
}
}
}
// Convert the character array to a string and return
Alternate Solution 1:
class Solution {
public String convert(String s, int numRows) {
// If numRows is 1, return the original string
if (numRows == 1) return s;
Alternate Solution 2:
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder answer = new StringBuilder();
int n = s.length();
int charsInSection = 2 * (numRows - 1);
if (secondIndex < n) {
answer.append(s.charAt(secondIndex));
}
}
// Jump to same row's first character of next section.
index += charsInSection;
}
}
Problem Statement: Given a string s of length n, find the longest repeating non-
overlapping substring in it. In other words, find 2 identical substrings of maximum length
which do not overlap. Return the longest non-overlapping substring. Return "-1" if no such
string exists.
Note: Multiple Answers are possible but you have to return the substring whose first
occurrence is earlier.
For Example: "abhihiab", here both "ab" and "hi" are possible answers. But you will have
to return "ab" because it's first occurrence appears before the first occurrence of "hi".
Example 1:
Input:
n=9
s = "acdcdacdc"
Output:
"acdc"
Explanation:
The string "acdc" is the longest Substring of s which is repeating but not overlapping.
Example 2:
Input:
n=7
s = "heheheh"
Output:
Explanation:
The string "heh" is the longest Substring of s which is repeating but not overlapping.
Constraints:
1 <= n <= 10^3
Sample Code:
General Solution:
class Solution {
static String longestSubstring(String S, int N) {
// Initialize variables to store the maximum length and the resulting
substring
int maxLength = 0;
String result = "-1";
// Iterate through the string until one of the pointers reaches the end
while (i < N && j < N) {
// Extract the current substring from index i to j
String subString = S.substring(i, j + 1);
// Check if the current substring occurs again in the remaining part of the
string
if (S.indexOf(subString, j + 1) != -1) {
// Calculate the length of the current substring
int len = subString.length();
// If the length is greater than the current maximum, update the answer
if (len > max) {
ans = subString;
// Update the maximum length
max = len;
}
} else {
// If the current substring is not found again, move the starting pointer i
to the next position
i++;
}
Example :
Input: 'str' = "aaccb"
Output: 2
Explanation: We can make a valid partition like aa | cc | b.
Detailed explanation ( Input/output format, Notes, Images )
Sample Input 1 :
aaccb
Sample Output 1 :
2
Explanation of sample input 1 :
We can make a valid partition like aa | cc | b.
Sample Input 2 :
ababa
Sample Output 2 :
0
Explanation of sample input 2 :
The string is already a palindrome, so we need not make any partition.
Sample Code:
General Solution:
Alternate Solution:
// Recursive function to find the minimum cuts needed in a string such that
each partition is a palindrome
public static int minPalinPartition(String str, int i, int j) {
/* Base case: if starting index i and ending index j are equal
or str[i..j] is already a palindrome. */
if (i == j || isPalindrome(str, i, j)) {
// Take the minimum over each possible position at which the String can be
cut
for (int k = i; k <= j - 1; k++) {
// Recur to get minimum cuts required in str[i..k] and str[k+1..j]
int count = 1 + minPalinPartition(str, i, k) + minPalinPartition(str, k + 1,
j);
// Update the min
if (count < min) {
min = count;
}
}
Problem statement : Richal wants to serve food to needy people. So, he bought
Ladoos from a sweet shop and placed them on plates. There can be any number
of Ladoos present in a plate.
Plates containing Ladoos are placed in two rows. Each row is sorted in increasing
order by the number of Ladoos in a plate.
For example :‘ROW1’ : [2, 5, 8, 17] and ‘ROW2’ : [1, 4, 8, 13, 20]
Now people come one by one in a line to take plates of Ladoos from Richal. Richal
picks the two plates in front, one from each row and gives that plate to people in
which the number of ladoos is the smallest (if both plates contain equal numbers
For Example :If ‘ROW1’ is [2, 5, 8, 17] and ‘ROW2’ is [1, 4, 8, 13, 20], then
Richal picks the first plates from each rows, plate containing 2 ladoos from
‘ROW1’ and a plate containing 1 ladoo from ‘ROW2’.
Then he gives the plate with 1 Ladoo to the first person in line and places the
other plate back to its position.
Can you tell how many ladoos the ‘K'th’ person will get?
Sample Input 1 :
2
543
3 11 23 45 52
4 12 14 18
112
1
2
Sample Output 1 :
11
2
Explanation for Sample Output 1 :For sample test case 1:
1’st person will get 3 ladoos i.e a minimum of 3 and 4. Now ‘ROW1’ : [11, 23,
45, 52] and ‘ROW2’ : [4, 12, 14, 18].
2’nd person will get 4 ladoos i.e minimum of 11 and 4. Now ‘ROW1’ : [11, 23,
45, 52] and ‘ROW2’ : [12, 14, 18].
3’rd person will get 11 ladoos i.e minimum of 11 and 12.
Constraints :
Sample Code:
General Solution :
/*
Time complexity: O(M + N)
int a = 0, b = 0, c = 0;
c++;
}
}
}
/*
Time complexity: O(K)
Space complexity: O(1)
where K denotes the Kth person in line waiting to be served.
*/
int i = 0, j = 0;
i++;
}
j++;
}
// This line never runs because we get our desired k in the above code.
return row2[i + j];
}
}
Problem Statement : Given an integer array nums and two integers left and right,
return the number of contiguous non-empty subarrays such that the value of the
maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Constraints:
General Solution :
int n = A.length;
int ans = 0;
if (max > R) {
break;
if (max >= L) {
ans++;
return ans;
int i = 0;
int j = 0;
int smaller = 0; // To track the number of subarrays where the max is smaller
than R but >= L
while (i != A.length) {
// Case 2: When A[i] is smaller than L, all subarrays ending at i are valid.
// If A[i] is smaller than L, subarrays ending at i will have the same valid
count as those before i
// Case 3: When A[i] is greater than R, reset the valid subarray count
else {
i++;
return ans;
• Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but
"uaeio", "aeoiu", and "aaaeeeooo" are not beautiful.
Given a string word consisting of English vowels, return the length of the longest
beautiful substring of word. If no such substring exists, return 0.
Example 1:
Example 2:
Example 3:
Constraints:
Sample Code:
General Solution:
class Solution {
int j = 0, ans = 0, n = word.length(); // Initialize variables: j for index, ans for result,
n for string length
if (cnt == 4) // If all 5 characters 'a', 'b', 'c', 'd', 'e' appear in order
class Solution {
// If the current character is greater than the previous one, increment the count
(increasing sequence)
// If the current character is less than the previous one, reset count and update i
to the current position
cnt = 1;
i = j;
// If cnt reaches 5, it means the substring 'a' to 'e' (in increasing order) is found,
update the max length
return ans;