0% found this document useful (0 votes)
6 views61 pages

Hands-On - Problem Solving - Day 06 - Key

The document outlines several programming exercises for problem-solving skills in software development, covering topics such as representing numbers as sums of consecutive integers, generating butterfly star patterns, identifying sums of two prime numbers, calculating sums of floored pairs, and determining bit differences in pairs of integers. Each exercise includes problem statements, sample inputs and outputs, constraints, and sample code solutions. The exercises are designed to enhance coding proficiency and algorithmic thinking.

Uploaded by

k.s.yogeswar3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views61 pages

Hands-On - Problem Solving - Day 06 - Key

The document outlines several programming exercises for problem-solving skills in software development, covering topics such as representing numbers as sums of consecutive integers, generating butterfly star patterns, identifying sums of two prime numbers, calculating sums of floored pairs, and determining bit differences in pairs of integers. Each exercise includes problem statements, sample inputs and outputs, constraints, and sample code solutions. The exercises are designed to enhance coding proficiency and algorithmic thinking.

Uploaded by

k.s.yogeswar3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

PROBLEM SOLVING

SDE Readiness Training

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;

public class Solution {


public static int CountSumConsecutiveNums(int n) {
long maxSum = 0; // Initialize the maximum possible sum
int m = 1; // Initialize the starting number for consecutive numbers

// Calculate the maximum possible sum with consecutive numbers


while (maxSum <= n) {
maxSum += m; // Add the next consecutive number

Little practice is worth more than a ton of theory


2
PROBLEM SOLVING
SDE Readiness Training
m++; // Move to the next consecutive number
}

int sum = 1; // Initialize the sum of consecutive numbers


int ans = 0; // Initialize the counter for representing 'n'

// Iterate through possible consecutive sequences


for (int i = 2; i < m - 1; i++) {
// Check if 'n' can be represented as the sum of consecutive numbers starting from
'sum'
if ((n - sum) % i == 0) {
ans++; // Increment the counter if 'n' can be represented as the sum
}
sum += i; // Update the sum of consecutive numbers
}

return ans; // Return the total count of representing 'n'


}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Prompt the user to input the number 'n'


System.out.print("Enter the number N: ");
int n = scanner.nextInt();
scanner.close();

// Calculate and display the number of ways to represent 'n' as a sum of


consecutive natural numbers
System.out.println("Number of ways to represent " + n + " as a sum of
consecutive natural numbers: " + CountSumConsecutiveNums(n));
}
}
Alternate solution:
class Solution {
// Static method to count the number of ways to represent 'N' as a sum of
consecutive natural numbers

Little practice is worth more than a ton of theory


3
PROBLEM SOLVING
SDE Readiness Training
static int getCount(int N) {
int ans = 0; // Initialize counter for representing 'N' as a sum of consecutive
natural numbers

// Iterate through possible consecutive sequences


for (int i = 2; i * (i - 1) / 2 < N; ++i) {
// Check if 'N' can be represented as a sum of consecutive numbers in the
sequence
if ((N - i * (i - 1) / 2) % i == 0) {
ans++; // Increment the counter if 'N' can be represented
}
}
return ans; // Return the total count of representing 'N'
}
}

2. Butterfly star pattern

Problem statement: Create a program to print a butterfly star pattern consisting of


stars in a symmetrical butterfly shape. The pattern should be printed such that the stars
form wings on both sides of the centerline. The number of stars in each wing should
decrease towards the centerline.

Input 1 : rows = 5
Output 1:
* *
** **
*** ***
**** ****
**********
**** ****
*** ***
** **
* *

Input 2: rows =7
Output 2 :

Little practice is worth more than a ton of theory


4
PROBLEM SOLVING
SDE Readiness Training
* *
** **
*** ***
**** ****
***** *****
************
************
***** *****
**** ****
*** ***
** **
* *

Sample Code:

Solution :

// Function to demonstrate pattern


public static void printPattern(int n)
{
int i, j;
int num = 1;

// outer loop to handle upper part


for (i = 1; i <= n; i++) {
// inner loop to print stars
for (j = 1; j <= i; j++) {
System.out.print("*");
}

// inner loop to print spaces


int spaces = 2 * (n - i);
for (j = 1; j <= spaces; j++) {
System.out.print(" ");
}

// inner loop to print stars


Little practice is worth more than a ton of theory
5
PROBLEM SOLVING
SDE Readiness Training
for (j = 1; j <= i; j++) {
System.out.print("*");
}

System.out.println();
}

// outer loop to handle lower part


for (i = n; i >= 1; i--) {
// inner loop to print stars
for (j = 1; j <= i; j++) {
System.out.print("*");
}

// inner loop to print spaces


int spaces = 2 * (n - i);
for (j = 1; j <= spaces; j++) {
System.out.print(" ");
}

// inner loop to print stars


for (j = 1; j <= i; j++) {
System.out.print("*");
}

System.out.println();
}
}

3. Sum of two prime numbers

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

Sample Output2: 7,13

Constraints:

• N>=1

Sample Code:

General solution:

public class GFG{

// Function to check whether a number


// is prime or not
static boolean isPrime(int n)
{
if (n <= 1)
return false;

for (int i = 2; i <= Math.sqrt(n); i++) {


if (n % i == 0)
return false;
}

return true;
}

// Function to check if a prime number


// can be expressed as sum of
// two Prime Numbers
static boolean isPossible(int N)
{
// if the number is prime,
// and number-2 is also prime
if (isPrime(N) && isPrime(N - 2))
Little practice is worth more than a ton of theory
7
PROBLEM SOLVING
SDE Readiness Training
return true;
else
return false;
}

Alternate Solution:

import java.util.Scanner;

class Main {

static boolean SieveOfEratosthenes(int n, boolean isPrime[]) {

// Mark all numbers as prime initially

isPrime[0] = isPrime[1] = false;

for (int i = 2; i <= n; i++)

isPrime[i] = true;

// Iterate through numbers up to square root of n

for (int p = 2; p * p <= n; p++) {

// If p is prime

if (isPrime[p] == true) {

// Mark multiples of p as not prime

for (int i = p * p; i <= n; i += p)

isPrime[i] = false;

return false;

}
Little practice is worth more than a ton of theory
8
PROBLEM SOLVING
SDE Readiness Training

// Method to find a pair of prime numbers that sum up to 'n'

static void findPrimePair(int n) {

// Create an array to store whether each number up to 'n' is prime

boolean isPrime[] = new boolean[n + 1];

// Use Sieve of Eratosthenes to find prime numbers

SieveOfEratosthenes(n, isPrime);

// Iterate through numbers up to 'n'

for (int i = 0; i < n; i++) {

// Check if both i and n - i are prime

if (isPrime[i] && isPrime[n - i]) {

// Print the pair of prime numbers

System.out.print(i + " " + (n - i));

return;

public static void main(String[] args) {

// Create a Scanner object to read input from the console

Scanner sc = new Scanner(System.in);

// Prompt the user to input the number 'n'

Little practice is worth more than a ton of theory


9
PROBLEM SOLVING
SDE Readiness Training
int n = sc.nextInt();

// Call the method to find the pair of prime numbers that sum up to 'n'

findPrimePair(n);

4. Sum of Floored Pairs

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.

The floor() function returns the integer part of the division.

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 :

Little practice is worth more than a ton of theory


10
PROBLEM SOLVING
SDE Readiness Training
public int sumOfFlooredPairs(int[] arr) {

int n = arr.length; // Length of the array

long ans = 0; // Initialize the answer

long mod = 1000000007; // Modulus value

// Iterate through all possible pairs

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

ans = (ans + arr[i] / arr[j]) % mod; // Add the floored value of


the division

return (int)(ans % mod); // Return the final answer

Alternate solution : Prefix Sum

public int sumOfFlooredPairs(int[] arr) {


int n = arr.length; // Length of the array
long ans = 0; // Initialize the answer
long mod = 1000000007; // Modulus value

int max = Integer.MIN_VALUE; // Initialize maximum value in the array

// Find the maximum value in the array


for(int i = 0; i < n; i++) {
max = Math.max(arr[i], max);
}

Little practice is worth more than a ton of theory


11
PROBLEM SOLVING
SDE Readiness Training
int freq[] = new int[max + 1]; // Array to store frequency of each number
in arr

// Calculate frequency of each number in the array


for(int i = 0; i < n; i++) {
freq[arr[i]]++;
}

int pre[] = new int[max + 1]; // Array to store prefix sum of frequencies

// Calculate prefix sum of frequencies


for(int i = 1; i <= max; i++) {
pre[i] = pre[i - 1] + freq[i];
}

// Iterate through each number in the array


for(int i = 1; i <= max; i++) {
if(freq[i] == 0)
continue; // Skip if frequency is 0

long sum = 0; // Initialize sum for current number


// Iterate through all multiples of the current number up to max
for(int j = 1; j * i <= max; j++) {
int left = j * i; // Left bound of the range
int right = i * (j + 1) - 1; // Right bound of the range
right = Math.min(right, max); // Ensure right bound does not
exceed max
int count = pre[right] - pre[left - 1]; // Calculate count of numbers
in the range
sum = (sum + (j * count) % mod) % mod; // Calculate sum for the
current multiple
}
ans = (ans + (long)(freq[i] * sum) % mod) % mod; // Update total
sum
}
return (int)(ans % mod); // Return the final answer
}

Little practice is worth more than a ton of theory


12
PROBLEM SOLVING
SDE Readiness Training
5. Sum of Bit Differences

Problem Statement : Given an integer array of n integers, find sum of bit


differences in all pairs that can be formed from array elements. Bit difference of a
pair (x, y) is count of different bits at same positions in binary representations of
x and y.

Examples :

Input: arr[] = {1, 2}


Output: 4
All pairs in array are (1, 1), (1, 2)
(2, 1), (2, 2)
Sum of bit differences = 0 + 2 +
2+0
=4

Input: arr[] = {1, 3, 5}


Output: 8
All pairs in array are (1, 1), (1, 3), (1, 5)
(3, 1), (3, 3) (3, 5),
(5, 1), (5, 3), (5, 5)
Sum of bit differences = 0 + 1 + 1 +
1+0+2+
1+2+0
=8
Constraints:
1 <= n <= 10^5
1 <= arr[i] <= 10^5

Sample Code:
General Solution:
import java.io.*;
class GFG {

static int sumBitDiff(int[] arr){

Little practice is worth more than a ton of theory


13
PROBLEM SOLVING
SDE Readiness Training
int diff = 0; //hold the ans
for(int i=0; i<arr.length; i++){
for(int j=i; j<arr.length; j++){

//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

int xor = arr[i]^arr[j];


int count = countSetBits(xor);
//Integer.bitCount() can also be used

//when i == j (same numbers) the xor would be 0,


//thus our ans will remain unaffected as (2*0 = 0)
diff += 2*count;
}
}

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;
}

public static void main (String[] args) {


int[] arr = {5,10};
int ans = sumBitDiff(arr);
System.out.println(ans);

Little practice is worth more than a ton of theory


14
PROBLEM SOLVING
SDE Readiness Training
}
}
Alternate Solution:
// Java program to compute sum of pairwise
// bit differences

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.

Little practice is worth more than a ton of theory


15
PROBLEM SOLVING
SDE Readiness Training

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);

Little practice is worth more than a ton of theory


16
PROBLEM SOLVING
SDE Readiness Training
// Initializing the answer variable
int ans = 0;

// Looping through each bit from 0 to 31


for (int i = 0; i <= 31; i++) {
// Creating a bitmask for the i'th bit
int mask = 1 << i;
// Checking if the i'th bit is set in a
int set = a & mask;

// 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;
}
}

// Returning the final answer


return ans;
}
}
7. Median of 2 Sorted Arrays of Different Sizes

Little practice is worth more than a ton of theory


17
PROBLEM SOLVING
SDE Readiness Training
Problem Statement : Given two sorted arrays array1 and array2 of size m and n
respectively. Find the median of the two sorted arrays.

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++];
}

Little practice is worth more than a ton of theory


18
PROBLEM SOLVING
SDE Readiness Training
} else if (i < n) {
m1 = nums1[i++];
} else {
m1 = nums2[j++];
}
}

// Check if the sum of n and m is odd.


if ((n + m) % 2 == 1) {
return (double) m1;
} else {
double ans = (double) m1 + (double) m2;
return ans / 2.0;
}
}
}
General solution 2:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n1 = nums1.length, n2 = nums2.length;
int[] nums3 = new int[n1 + n2];
int i = 0, j = 0, k = 0;

//merging the sorted array


while (i < n1 && j < n2) {
if (nums1[i] < nums2[j]) {
nums3[k] = nums1[i];
i++;
} else {
nums3[k] = nums2[j];
j++;
}
k++;
}

while (i < n1) {


nums3[k] = nums1[i];

Little practice is worth more than a ton of theory


19
PROBLEM SOLVING
SDE Readiness Training
i++;
k++;
}

while (j < n2) {


nums3[k] = nums2[j];
j++;
k++;
}

//finding the median of the merged array


int n = n1 + n2;

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);

// Sort the combined array


Arrays.sort(arr);

// Calculate median based on array length

Little practice is worth more than a ton of theory


20
PROBLEM SOLVING
SDE Readiness Training
int x = arr.length;
double med;
if (x % 2 == 0) {
med = arr[x / 2] + arr[x / 2 - 1];
return med / 2;
} else {
med = arr[x / 2];
return med;
}
}
}

8. Subarrays With Equal 0’s, 1’s and 2’s

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 :

If ‘N’ = 5, ‘ARR’ = {1, 1, 0, 2, 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}.

The second subarray is from ‘ARR[2]’ to ‘ARR[4]’, ie: {0, 2, 1}.

Sample Input 1 :

11021

Little practice is worth more than a ton of theory


21
PROBLEM SOLVING
SDE Readiness Training
1100

Sample Output 1 :

Explanation For Sample Input 1 :

For test case 1 :

We will print 2 because:

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}

For test case 2 :

We will print 0 because:

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

Little practice is worth more than a ton of theory


22
PROBLEM SOLVING
SDE Readiness Training
1 ≤ N ≤ 1000

ARR[i] = {0, 1, 2}

Sample Code

//Using Prefix sum

public class Solution {

public static int countSubarrays(int n, int[] arr) {

// Initialize 'ans' equal to 0.

int ans = 0;

// Initialize variables to store the count of 0's, 1's and 2's so far.

int cnt0 = 0, cnt1 = 0, cnt2 = 0;

// Declare three prefix arrays.

int[] prefix0 = new int[n];

int[] prefix1 = new int[n];

int[] prefix2 = new int[n];

// Fill the prefix arrays.

for (int i = 0; i < n; i++) {

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;

Little practice is worth more than a ton of theory


23
PROBLEM SOLVING
SDE Readiness Training
}

// Run a FOR loop.

for (int i = 0; i < n; i++) {

// Check for the subarray starting at 0'th index.

if (prefix0[i] == prefix1[i] && prefix0[i] == prefix2[i]) {

ans++;

// Check for other possible subarrays from j + 1 to i.

for (int j = 0; j < i; j++) {

// Count of 0's in stored in cnt0, similarly for cnt1 and cnt2 also.

cnt0 = prefix0[i] - prefix0[j];

cnt1 = prefix1[i] - prefix1[j];

cnt2 = prefix2[i] - prefix2[j];

// If all the counts are equal.

if (cnt0 == cnt1 && cnt0 == cnt2) {

ans++;

// Finally, return the value of 'ans'.

return ans;

Little practice is worth more than a ton of theory


24
PROBLEM SOLVING
SDE Readiness Training
9. Count Array Pairs Divisible by K

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];

Little practice is worth more than a ton of theory


25
PROBLEM SOLVING
SDE Readiness Training
// Count the occurrences of each gcd value
for (int n : nums) counts[gcd(n, k)]++;

// Initialize variables to store the count of pairs and sum


long ck = counts[k];
long sum = 0;

// Loop through each possible gcd value


for (int i = 1; i < counts.length; i++) {
if (counts[i] == 0) continue;

// Calculate the count of pairs where gcd(i, j) == k


if ((long) i * i % k == 0) sum += (long) counts[i] * (counts[i] - 1)
/ 2;

// Calculate the count of pairs where gcd(i, j) == k and i != j


for (int j = i + 1; j < counts.length; j++) {
if ((long) i * j % k != 0) continue;
sum += (long) counts[i] * counts[j];
}
}

return sum;
}

// Recursive function to calculate gcd


int gcd(int a, int b) {
if (b != 0) return gcd(b, a % b);
return a;
}
}

Alternate solution :

class Solution {
public long countPairs(int[] nums, int k) {
long cnt = 0; // Initialize the count of pairs

Little practice is worth more than a ton of theory


26
PROBLEM SOLVING
SDE Readiness Training
long[] cntgcd = new long[k + 1]; // Initialize an array to count
occurrences of each gcd value

// Count occurrences of each gcd value in nums


for (int i : nums) {
int gcd = gcd(i, k);
cntgcd[gcd]++;
}

// Iterate through possible gcd values


for (int i = 1; i < k; i++) {
if (cntgcd[i] == 0) continue;
int rest = k / i;
long subc = 0;

// Calculate the count of pairs where gcd(i, j) == k and j * rest <=


k
if (rest <= i) {
for (int j = 1; j * rest <= k; j++) {
if (j * rest < i) continue;
if (j * rest == i) {
subc += cntgcd[i] * (cntgcd[i] - 1) / 2;
continue;
}
subc += cntgcd[i] * cntgcd[j * rest];
}
} else {
for (int j = 1; j * rest <= k; j++) {
subc += cntgcd[i] * cntgcd[j * rest];
}
}
cnt += subc; // Update the total count
}
cnt += cntgcd[k] * (cntgcd[k] - 1) / 2; // Add pairs where gcd(i, j)
== k and i == j
return cnt; // Return the total count of pairs
}

Little practice is worth more than a ton of theory


27
PROBLEM SOLVING
SDE Readiness Training

// Function to calculate the greatest common divisor (GCD) of two


numbers
public int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
}

10.Split Array Largest Sum

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;
}

// Split array into K subarrays with min largest sum


static int splitArray(int[] arr, int N, int K) {
// Find maximum and sum of the array
int max = 0, sum = 0;
for (int val : arr) {
sum += val;
max = Math.max(max, val);
}
// If K equals to N, return the maximum element
if (K == N) return max;
// Binary search for the minimum largest sum
int start = max, end = sum, ans = 0;
while (start <= end) {
int mid = start + (end - start) / 2;

Little practice is worth more than a ton of theory


29
PROBLEM SOLVING
SDE Readiness Training
if (isPossible(arr, mid, K)) {
ans = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return ans;
}
}
Alternate solution :
class Solution {
// Binary search to find minimum largest sum
static int splitArray(int[] arr, int N, int K) {
long low = Arrays.stream(arr).max().getAsInt(); // Initialize low to
maximum element
long high = Arrays.stream(arr).sum(); // Initialize high to sum of all
elements

// 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

// Update low or high based on count


if (count > K) {
low = mid + 1;
} else {
high = mid;
}
}
return (int) low; // Return minimum largest sum
}

// Get count of subarrays with sum <= maxSum

Little practice is worth more than a ton of theory


30
PROBLEM SOLVING
SDE Readiness Training
static int getCount(int[] arr, int N, long maxSum) {
int count = 1;
long currentSum = 0;

// Iterate through array


for (int num : arr) {
currentSum += num;
if (currentSum > maxSum) { // If sum exceeds maxSum,
increment count
count++;
currentSum = num; // Reset currentSum
}
}
return count; // Return count of subarrays
}
}

11. Max Circular Subarray Sum

Problem Statement : Given an array arr[] of N integers arranged in a circular fashion.


Your task is to find the maximum contiguous subarray sum

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

// Iterate through the array to calculate maximum and minimum sums


for (int i = 0; i < nums.length; i++) {
totalSum += nums[i]; // Calculate total sum of the array

// Calculate the current sum of subarray for maximum sum


calculation
currentSum1 += nums[i];
maxSum = Math.max(currentSum1, maxSum);

// Calculate the current sum of subarray for minimum sum


calculation
currentSum2 += nums[i];
minSum = Math.min(currentSum2, minSum);

// Reset current sum if it becomes negative


if (currentSum1 < 0) {
currentSum1 = 0;

Little practice is worth more than a ton of theory


32
PROBLEM SOLVING
SDE Readiness Training
}
// Reset current sum if it becomes positive
if (currentSum2 > 0) {
currentSum2 = 0;
}
}

// 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];

// Calculate the total sum of the array


int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}

// Initialize variables for Kadane's Algorithm


int curr_max = a[0], max_so_far = a[0],
curr_min = a[0], min_so_far = a[0];

// Apply Kadane's Algorithm to find max and min subarray sums

Little practice is worth more than a ton of theory


33
PROBLEM SOLVING
SDE Readiness Training
for (int i = 1; i < n; i++) {
// Update maximum subarray sum
curr_max = Math.max(curr_max + a[i], a[i]);
max_so_far = Math.max(max_so_far, curr_max);

// Update minimum subarray sum


curr_min = Math.min(curr_min + a[i], a[i]);
min_so_far = Math.min(min_so_far, curr_min);
}

// If the minimum subarray sum equals the total sum, return


max_so_far
if (min_so_far == sum) {
return max_so_far;
}

// Otherwise, return the maximum of max_so_far and the difference


between sum and min_so_far
return Math.max(max_so_far, sum - min_so_far);
}
}

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;

// Iterate through the array


for (int a : nums) {
// Update maximum sum
curMax = Math.max(curMax + a, a);
maxSum = Math.max(maxSum, curMax);

// Update minimum sum

Little practice is worth more than a ton of theory


34
PROBLEM SOLVING
SDE Readiness Training
curMin = Math.min(curMin + a, a);
minSum = Math.min(minSum, curMin);

// Update total sum


total += a;
}

// Return maximum circular subarray sum


return maxSum > 0 ? Math.max(maxSum, total - minSum) :
maxSum;
}
}

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.

Refer to the Image:

Sample Input 1:
1

Little practice is worth more than a ton of theory


35
PROBLEM SOLVING
SDE Readiness Training
44
1234
5678
9 10 11 12
13 14 15 16
Sample Output 1:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Sample Input 2:
2
33
123
456
789
31
10
20
30
Sample Output 2:
123698745
10 20 30

Constraints :
1 <= t <= 10^2
0 <= N <= 10^3
0 <= M <= 10^3

Sample Code:

General Solution :

public class Solution {

public static void spiralPrint(int matrix[][]){

// Check if the matrix is empty

int n = matrix.length;

if(n == 0) return;

int m = matrix[0].length;

Little practice is worth more than a ton of theory


36
PROBLEM SOLVING
SDE Readiness Training
if(m == 0) return;

// Initialize variables to keep track of the spiral traversal

int count = 1; // Number of elements printed

int tr = 0; // Top row index

int br = n - 1; // Bottom row index

int lc = 0; // Left column index

int rc = m - 1; // Right column index

// Loop until all elements are printed

while(count <= n * m){

// Print top row from left to right

for(int i = lc; i <= rc; i++){

if(tr > br) break; // Break if top row index crosses bottom row
index

System.out.print(matrix[tr][i] + " ");

count++;

tr++; // Move the top row index down

// Print right column from top to bottom

for(int i = tr; i <= br; i++){

if(lc > rc) break; // Break if left column index crosses right
column index

System.out.print(matrix[i][rc] + " ");

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

// Print bottom row from right to left

for(int i = rc; i >= lc; i--){

if(tr > br) break; // Break if top row index crosses bottom row
index

System.out.print(matrix[br][i] + " ");

count++;

br--; // Move the bottom row index up

// Print left column from bottom to top

for(int i = br; i >= tr; i--){

if(lc > rc) break; // Break if left column index crosses right
column index

System.out.print(matrix[i][lc] + " ");

count++;

lc++; // Move the left column index to the right

Alternate Solution :

// Method to print elements of a matrix in a spiral order


public static void spiralPrint(int mat[][]){
// Get the number of rows in the matrix
int nRows = mat.length;

Little practice is worth more than a ton of theory


38
PROBLEM SOLVING
SDE Readiness Training
// If there are no rows, return
if (nRows == 0) {
return;
}

// Get the number of columns in the matrix


int mCols = mat[0].length;

int i, rowStart = 0, colStart = 0;

int numElements = nRows * mCols, count = 0;

// Iterate until all elements are printed


while(count < numElements){
// Print elements of top row from left to right
for(i = colStart; count < numElements && i < mCols; ++i) {
System.out.print(mat[rowStart][i]+ " ");
count++;
}
rowStart++;

// Print elements of rightmost column from top to bottom


for(i = rowStart; count < numElements && i < nRows; ++i) {
System.out.print(mat[i][mCols - 1] + " ");
count++;
}
mCols--;

// Print elements of bottom row from right to left


for(i = mCols - 1; count < numElements && i >= colStart; --i) {
System.out.print(mat[nRows - 1][i] + " ");
count++;
}
nRows--;

// Print elements of leftmost column from bottom to top


for(i = nRows - 1; count < numElements && i >= rowStart; --i) {

Little practice is worth more than a ton of theory


39
PROBLEM SOLVING
SDE Readiness Training
System.out.print(mat[i][colStart] + " ");
count++;
}
colStart++;
}
}

13. Zigzag Conversion

Problem Statement: The string "PAYPALISHIRING" is written in a zigzag pattern on a


given number of rows like this: (you may want to display this pattern in a fixed font for
better legibility)

P A H N

APLSIIG

Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3

Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4

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:

● 1 <= s.length <= 1000


● s consists of English letters (lower-case and upper-case), ',' and '.'.

● 1 <= numRows <= 1000

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;

// Calculate the distance between two consecutive elements in the zigzag


pattern
int x = 2 * (numRows - 1);
int len = s.length();
char[] c = new char[len];
int k = 0;

// Traverse through each row of the zigzag pattern


for (int i = 0; i < numRows; i++) {
// Traverse through the string with a step size of x
for (int j = i; j < len; j += x) {
// Add the character at index j to the result
c[k++] = s.charAt(j);

// 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

Little practice is worth more than a ton of theory


41
PROBLEM SOLVING
SDE Readiness Training
return new String(c);
}
}

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;

// Calculate the step size between consecutive elements in the zigzag


pattern
int increase = 2 * numRows - 2;
char[] str = s.toCharArray();
char[] ans = new char[str.length];
int index = 0;

// Traverse through each row of the zigzag pattern


for (int i = 0; i < numRows; i++) {
// Traverse through the string with a step size of increase
for (int j = 0; j < str.length; j += increase) {
// Add the character at index i+j to the result for the first and last row
if (i == 0 || i == numRows - 1) {
if (i + j < str.length) {
ans[index++] = str[i + j];
}
} else {
// For rows between the first and last row, add additional characters
if (i + j < str.length) {
ans[index++] = str[i + j];
}
if (j + increase - i < str.length) {
ans[index++] = str[j + increase - i];
}
}
}

Little practice is worth more than a ton of theory


42
PROBLEM SOLVING
SDE Readiness Training
}
// Convert the character array to a string and return
return String.valueOf(ans);
}
}

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);

for (int currRow = 0; currRow < numRows; ++currRow) {


int index = currRow;

while (index < n) {


answer.append(s.charAt(index));

// If currRow is not the first or last row


// then we have to add one more character of current section.
if (currRow != 0 && currRow != numRows - 1) {
int charsInBetween = charsInSection - 2 * currRow;
int secondIndex = index + charsInBetween;

if (secondIndex < n) {
answer.append(s.charAt(secondIndex));
}
}
// Jump to same row's first character of next section.
index += charsInSection;
}
}

Little practice is worth more than a ton of theory


43
PROBLEM SOLVING
SDE Readiness Training
return answer.toString();
}
}

14. Longest repeating and non-overlapping substring

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:

Little practice is worth more than a ton of theory


44
PROBLEM SOLVING
SDE Readiness Training
"heh"

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 all possible starting indices of substrings


for (int i = 0; i < N; i++) {
// Iterate through all possible ending indices of substrings
for (int j = i + 1; j <= N; j++) {
String subString = S.substring(i, j); // Get the current substring

// Check if the substring appears again after position j


if (S.indexOf(subString, j) != -1) {
// If the substring appears again, check its length
int len = subString.length();

// If this is the longest substring found so far, update the result


if (len > maxLength) {
result = subString;
maxLength = len;
}
}
}
Little practice is worth more than a ton of theory
45
PROBLEM SOLVING
SDE Readiness Training
}

return result; // Return the longest non-overlapping substring


}
}
Optimal Solution : Sliding Window
class Solution {
static String longestSubstring(String S, int N) {
// Initialize variables to store the maximum length, answer, and pointers
int max = 0;
String ans = "-1";
int i = 0;
int j = 0;

// 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++;
}

Little practice is worth more than a ton of theory


46
PROBLEM SOLVING
SDE Readiness Training
// Move the ending pointer j to the next character
j++;
}

// Return the final answer


return ans;
}
}

15. Palindrome partitioning

Problem statement : You are given a string 'str' of length 'n'.


Find the minimum number of partitions in the string so that no partition is empty and
every partitioned substring is a palindrome.

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.

Little practice is worth more than a ton of theory


47
PROBLEM SOLVING
SDE Readiness Training
Constraints :
1 <= 'n' <= 100

Sample Code:

General Solution:

public class Solution {


// Method to find the minimum number of partitions required
public static int palindromePartitioning(String str) {
// Call the recursive function to compute the result
return func(str, 0, str.length() - 1);
}

// Recursive function to find the minimum number of partitions required


private static int func(String s, int i, int j) {
// Base case: if the substring is empty or a palindrome, return 0
if (i >= j) return 0;
if (isPalindrome(s, i, j)) return 0;

// Initialize the minimum number of partitions to the maximum value


int mini = Integer.MAX_VALUE;

// Try all possible partitions and find the minimum


for (int k = i; k <= j - 1; k++) {
int temp = 1 + func(s, i, k) + func(s, k + 1, j);
mini = Math.min(temp, mini);
}

// Return the minimum number of partitions


return mini;
}

// Helper method to check if a substring is a palindrome


private static boolean isPalindrome(String s, int i, int j) {
// Iterate through the substring from both ends
while (i < j) {
// If characters at both ends are equal, move towards the center
Little practice is worth more than a ton of theory
48
PROBLEM SOLVING
SDE Readiness Training
if (s.charAt(i) == s.charAt(j)) {
i++;
j--;
} else {
// If characters are not equal, the substring is not a palindrome
return false;
}
}
// If all characters matched, the substring is a palindrome
return true;
}
}

Alternate Solution:

public class Solution {


public static int palindromePartitioning(String str) {
int n = str.length();
return minPalinPartition(str, 0, n - 1);
}

// Function to check if string str[i..j] is a palindrome or not


public static boolean isPalindrome(String str, int i, int j) {
while (i <= j) {
if (str.charAt(i++) != str.charAt(j--)) {
return false;
}
}
return true;
}

// 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)) {

Little practice is worth more than a ton of theory


49
PROBLEM SOLVING
SDE Readiness Training
return 0;
}

// Stores minimum number cuts needed to partition str[i..j] initially its


infinite
int min = Integer.MAX_VALUE;

// 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;
}
}

// Return the minimum cuts required


return min;
}
}

16. K th element of Two sorted arrays

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

Little practice is worth more than a ton of theory


50
PROBLEM SOLVING
SDE Readiness Training
of ladoos then he serves any plate from the two plates) and places the other
plate back to its position.

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.

For sample test case 2:


1’st person will get 1 ladoos i.e a minimum of 1 and 2. Now ‘ROW1’ : [ ] and
‘ROW2’ : [2].
2’st person will get 2 ladoos because we have only one element left in ROW2 .
Now ‘ROW1’ : [] and ‘ROW2’ : [].
Sample Input 2 :
2
53
1 3 6 7 10
Little practice is worth more than a ton of theory
51
PROBLEM SOLVING
SDE Readiness Training
3557
332
10 20 20
123
Sample Output 2 :
3
2
Explanation for Sample Output 2 :For sample test case 1:
1’st person will get 1 ladoo i.e minimum of 1 and 3. Now ‘ROW1’ : [3, 7, 10]
and ‘ROW2’ : [3, 5, 5, 7].
2’nd person will get 3 ladoos i.e now from both rows we will get a plate of 3
ladoos so Richal can give any one plate containing ladoos from each row. Let us
assume Richal give a plate from ‘ROW2’. Now ‘ROW1’ : [3, 7, 10] and ‘ROW2’ :
[5, 5, 7].
3’rd person will get 3 ladoos i.e minimum of 3 and 5. Now ‘ROW1’ : [7, 10] and
‘ROW2’ : [5, 5, 7].

For sample test case 2:


1’st person will get 1 ladoo i.e minimum of 10 and 1. Now ‘ROW1’ : [10, 20, 30]
and ‘ROW2’ : [ 2, 3].
2’nd person will get 2 ladoos i.e minimum of 10 and 2. Now ‘ROW1’ : [10, 20,
30] and ‘ROW2’ : [3].

Constraints :

• 1 <= T <= 100


1 <= N, M, K <= 10^5
K <= (N + M)
0 <= ROW1[i], ROW2[i] <= 10^5
where ROW1[i] and ROW2[i] denote the number of Ladoos in i’th plates of
ROW1 and ROW2 respectively

Sample Code:
General Solution :

/*
Time complexity: O(M + N)

Little practice is worth more than a ton of theory


52
PROBLEM SOLVING
SDE Readiness Training
Space complexity: O(M + N)

where M and N are the length of ROW1 and ROW2 respectively.


*/

public class Solution {


public static int Ladoos(int row1[], int row2[], int m, int n, int k) {
int sortedRows[] = new int[m + n];

int a = 0, b = 0, c = 0;

// Iterate while a is less than m and b is less than n


while (a < m && b < n) {
if (row1[a] < row2[b]) {
sortedRows[c] = row1[a];
a++;
} else {
sortedRows[c] = row2[b];
b++;
}

c++;
}

// Iterate while a is less than m


while (a < m) {
sortedRows[c] = row1[a];
a++;
c++;
}

// Iterate while b is less than n


while (b < n) {
sortedRows[c] = row2[b];
b++;
c++;

Little practice is worth more than a ton of theory


53
PROBLEM SOLVING
SDE Readiness Training
}

return sortedRows[k - 1];

}
}

Optimal Solution : Two pointer

/*
Time complexity: O(K)
Space complexity: O(1)
where K denotes the Kth person in line waiting to be served.
*/

public class Solution {


public static int Ladoos(int row1[], int row2[], int m, int n, int k) {

int i = 0, j = 0;

// Iterate while i is less than m and j is less than n


while (i < m && j < n) {
if (i + j == k - 1) {
return Math.min(row1[i], row2[j]);
}

if (row1[i] < row2[j]) {


i++;
} else {
j++;
}

// Iterate while i is less than m


while (i < m) {

Little practice is worth more than a ton of theory


54
PROBLEM SOLVING
SDE Readiness Training
if (i + j == k - 1) {
return row1[i];
}

i++;
}

// Iterate while j is less than n


while (j < n) {
if (i + j == k - 1) {
return row2[j];
}

j++;
}

// This line never runs because we get our desired k in the above code.
return row2[i + j];

}
}

17. Number of Subarrays with Bounded maximum

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:

Input: nums = [2,1,4,3], left = 2, right = 3


Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1],
[3].

Little practice is worth more than a ton of theory


55
PROBLEM SOLVING
SDE Readiness Training
Example 2:

Input: nums = [2,9,2,5,6], left = 2, right = 8


Output: 7

Constraints:

1 <= nums.length <= 10^5

0 <= nums[i] <= 10^9

0 <= left <= right <= 10

General Solution :

public int numSubarrayBoundedMax(int[] A, int L, int R) {

int n = A.length;

int ans = 0;

// Iterate over all possible subarrays

for (int start = 0; start < n; start++) {

int max = Integer.MIN_VALUE;

// Check every subarray starting from index 'start'

for (int end = start; end < n; end++) {

max = Math.max(max, A[end]);

// If max exceeds R, stop considering further elements in this subarray

if (max > R) {

break;

Little practice is worth more than a ton of theory


56
PROBLEM SOLVING
SDE Readiness Training
// If max is within the range [L, R], increment the result

if (max >= L) {

ans++;

return ans;

Optimal Solution : Two pointer

public int numSubarrayBoundedMax(int[] A, int L, int R) {

// Initialize two pointers i and j

int i = 0;

int j = 0;

int ans = 0; // To store the final answer (count of valid subarrays)

int smaller = 0; // To track the number of subarrays where the max is smaller
than R but >= L

// Loop through the array using the pointer i

while (i != A.length) {

// Case 1: When A[i] is within the range [L, R]

if (A[i] >= L && A[i] <= R) {

// All subarrays ending at i and starting from j (to i) are valid.

smaller = i - j + 1; // Update the count of subarrays starting from j and


ending at i

Little practice is worth more than a ton of theory


57
PROBLEM SOLVING
SDE Readiness Training
ans += smaller; // Add the number of valid subarrays to the answer

// Case 2: When A[i] is smaller than L, all subarrays ending at i are valid.

else if (A[i] < L) {

// If A[i] is smaller than L, subarrays ending at i will have the same valid
count as those before i

ans += smaller; // Continue adding the valid subarrays count

// Case 3: When A[i] is greater than R, reset the valid subarray count

else {

// If A[i] is greater than R, it invalidates all subarrays that include A[i]

j = i + 1; // Move j to the next position after i

smaller = 0; // Reset the count of valid subarrays as no subarray with


A[i] is valid

// Increment i to move to the next element in the array

i++;

// Return the total number of valid subarrays found

return ans;

18.Longest Substring Of All Vowels in Order

Problem Statement : A string is considered beautiful if it satisfies the following


conditions:

• Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.

Little practice is worth more than a ton of theory


58
PROBLEM SOLVING
SDE Readiness Training
• The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's
before 'i's, etc.).

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.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"


Output: 13
Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.

Example 2:

Input: word = "aeeeiiiioooauuuaeiou"


Output: 5
Explanation: The longest beautiful substring in word is "aeiou" of length 5.

Example 3:

Input: word = "a"


Output: 0
Explanation: There is no beautiful substring, so return 0.

Constraints:

1 <= word.length <= 5 * 105

word consists of characters 'a', 'e', 'i', 'o', and 'u'.

Sample Code:

General Solution:

class Solution {

Little practice is worth more than a ton of theory


59
PROBLEM SOLVING
SDE Readiness Training
public int longestBeautifulSubstring(String word) {

int j = 0, ans = 0, n = word.length(); // Initialize variables: j for index, ans for result,
n for string length

for (int i = 0; i < n; i++) { // Loop through the string

if (word.charAt(i) == 'a') { // If the current character is 'a'

int cnt = 0; // Count of increasing 'a' to 'e'

for (j = i + 1; j < n && word.charAt(j - 1) <= word.charAt(j); j++) // Traverse


the substring while it is in increasing order

cnt += word.charAt(j - 1) < word.charAt(j) ? 1 : 0; // Increase cnt when


character increases

if (cnt == 4) // If all 5 characters 'a', 'b', 'c', 'd', 'e' appear in order

ans = Math.max(ans, j - i); // Update the maximum length of valid substring

i = j - 1; // Move i to the end of the current valid substring

return ans; // Return the maximum length found

Optimal Solution : Sliding window

class Solution {

public int longestBeautifulSubstring(String word) {

int n = word.length(), i = 0, j = 0, ans = 0, cnt = 1; // Initialize variables: n (length),


i, j (indexes), ans (max length), cnt (count of increasing chars)

// Loop through the string starting from the second character

Little practice is worth more than a ton of theory


60
PROBLEM SOLVING
SDE Readiness Training
for (j = 1; j < n; j++) {

// If the current character is greater than the previous one, increment the count
(increasing sequence)

if (word.charAt(j) > word.charAt(j - 1)) cnt++;

// If the current character is less than the previous one, reset count and update i
to the current position

if (word.charAt(j) < word.charAt(j - 1)) {

cnt = 1;

i = j;

// If cnt reaches 5, it means the substring 'a' to 'e' (in increasing order) is found,
update the max length

if (cnt == 5) ans = Math.max(ans, j - i + 1);

// Return the maximum length of a valid "beautiful" substring

return ans;

Little practice is worth more than a ton of theory


61

You might also like