0% found this document useful (0 votes)
3 views131 pages

Striver A2z CPP Part 1

The document contains a series of C++ programming problems along with their solutions. It covers topics such as counting digits, reversing numbers, checking for palindromes, calculating GCD, identifying Armstrong numbers, printing divisors, checking for prime numbers, and using recursion. Each problem includes a description, example input/output, and the corresponding C++ code.

Uploaded by

yashamhm19
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)
3 views131 pages

Striver A2z CPP Part 1

The document contains a series of C++ programming problems along with their solutions. It covers topics such as counting digits, reversing numbers, checking for palindromes, calculating GCD, identifying Armstrong numbers, printing divisors, checking for prime numbers, and using recursion. Each problem includes a description, example input/output, and the corresponding C++ code.

Uploaded by

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

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Step 1 : Learn the basics

PROBLEM:1

Question: Count Digits

Write a C++ program to count the number of digits in a given integer n.

Input:

 A single integer n (0 ≤ n ≤ 10^9).

Output:

 An integer representing the number of digits in n.

Example:

Input: 12345

Output: 5

C++ Code:

cpp

CopyEdit

#include <iostream>

int countDigits(int n) {

if (n == 0) return 1; // Special case for 0

int count = 0;

while (n > 0) {

count++;

n /= 10;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return count;

int main() {

int n;

std::cin >> n;

std::cout << countDigits(n) << std::endl;

return 0;

PROBLEM:2

Question: Reverse a number

Write a C++ program that takes an integer as input and outputs the number with its digits in
reverse order.

Example:

Input: 12345


Output: 54321

This code works for both positive and negative numbers.

C++ Code:

Cpp

#include <iostream>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

int num, reversedNum = 0, remainder

// Ask user to enter a number

cout << "Enter an integer: ";

cin >> num;

// Reverse the digits of the number

while (num != 0) {

remainder = num % 10; // Get the last digit

reversedNum = reversedNum * 10 + remainder;

// Append it to the reversed number

num /= 10; // Remove the last digit from the original number

// Output the reversed number

cout << "Reversed Number: " << reversedNum << endl;

return 0;

Explanation:

Input: The program asks for an integer input.

Logic:

It repeatedly extracts the last digit of the number using num % 10.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


It then adds that digit to the reversedNum (which is initially 0), shifting the digits of
reversedNum by one position.

The original number is divided by 10 (num /= 10) to remove the last digit, and this loop
continues until the original number becomes 0.

Output: Once the loop finishes, the reversed number is printed.

PROBLEM:2

Question: Check if a Number is a Palindrome

Write a C++ program that takes an integer as input and checks whether it is a
palindrome or not.

Example:

Input: 121


Output: 121 is a palindrome.


Input: 123


Output: 123 is not a palindrome.

C++ Code:

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Copy

#include <iostream>using namespace std;

int main() {

int num, reversedNum = 0, remainder, originalNum;

// Ask user to enter a number

cout << "Enter an integer: ";

cin >> num;

originalNum = num; // Store the original number for comparison later

// Reverse the digits of the number

while (num != 0) {

remainder = num % 10; // Get the last digit

reversedNum = reversedNum * 10 + remainder;

// Append it to the reversed number

num /= 10; // Remove the last digit from the original number

// Check if the original number is the same as the reversed number

if (originalNum == reversedNum) {

cout << originalNum << " is a palindrome." << endl;

} else {

cout << originalNum << " is not a palindrome." << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Explanation:

1.Input: The program prompts the user to enter an integer.

2.Logic:

1.The program first stores the original number in originalNum.

2.It then reverses the digits of the number using the same logic as the "Reverse
Digits" code.

3.Palindrome Check:

1.After reversing the number, it checks if the original number is equal to the reversed
number.

2.If they are equal, the number is a palindrome; otherwise, it is not.

Output: The program prints whether the number is a palindrome or not.

Example:

 Input: 121
 Output: 121 is a palindrome.
 Input: 123
 Output: 123 is not a palindrome.

This code works for both positive and negative numbers. If you want to handle
negative numbers as non-palindromes (because of the sign), you can add a
condition to check for negative values at the beginning.

PROBLEM:4

Question: GCD Or HCF

Write a C++ program to find the Greatest Common Divisor (GCD) or Highest
Common Factor (HCF) of two numbers using the Euclidean algorithm. The
program should take two integers as input and output their GCD.

C++ Code:

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


CopyEdit

#include <iostream>using namespace std;

// Function to calculate GCD using Euclidean Algorithmint gcd(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

int main() {

int num1, num2;

// Taking input from the user

cout << "Enter two numbers: ";

cin >> num1 >> num2;

// Calculating GCD

int result = gcd(num1, num2);

// Displaying the result

cout << "GCD (HCF) of " << num1 << " and " << num2 << " is: " << result << endl;

return 0;

Explanation:

1.The program defines a function gcd() that implements the Euclidean algorithm.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2.In the main() function, the user is asked to input two numbers.

3.The gcd() function is called, and the result is printed.

PROBLEM:5

Question: Check if a Number is a Palindrome

Write a C++ program that takes an integer as input and checks whether it is a
palindrome or not.

C++ Code:

cpp

Copy

#include <iostream>using namespace std;

int main() {

int num, reversedNum = 0, remainder, originalNum;

// Ask user to enter a number

cout << "Enter an integer: ";

cin >> num;

originalNum = num; // Store the original number for comparison later

// Reverse the digits of the number

while (num != 0) {

remainder = num % 10; // Get the last digit

reversedNum = reversedNum * 10 + remainder; // Append it to the reversed number

num /= 10; // Remove the last digit from the original number

// Check if the original number is the same as the reversed number

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (originalNum == reversedNum) {

cout << originalNum << " is a palindrome." << endl;

} else {

cout << originalNum << " is not a palindrome." << endl;

return 0;

Explanation:

 Input: The program prompts the user to enter an integer.


 Logic:

The program first stores the original number in originalNum.

It then reverses the digits of the number using the same logic as the "Reverse
Digits" code.

 Palindrome Check:

After reversing the number, it checks if the original number is equal to the
reversed number.

If they are equal, the number is a palindrome; otherwise, it is not.

 Output: The program prints whether the number is a palindrome or not.

Example:

Input: 121

Output: 121 is a palindrome.

Input: 123

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Output: 123 is not a palindrome.

This code works for both positive and negative numbers. If you want to
handle negative numbers as non-palindromes (because of the sign), you can
add a condition to check for negative values at the beginning

PROBLEM:5

Question: Check if a Number is an Armstrong Number

Write a C++ program that takes an integer as input and checks whether it is an
Armstrong number or not.

C++ Code:

cpp

Copy

#include <iostream>#include <cmath>using namespace std;

int main() {

int num, sum = 0, remainder, originalNum, n;

// Ask user to enter a number

cout << "Enter an integer: ";

cin >> num;

originalNum = num; // Store the original number for comparison later

// Find the number of digits in the original number

n = 0;

while (num != 0) {

num /= 10;

++n;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

num = originalNum; // Restore the original number

// Calculate the sum of the nth power of each digit

while (num != 0) {

remainder = num % 10; // Get the last digit

sum += pow(remainder, n); // Add the nth power of the digit to sum

num /= 10; // Remove the last digit from the number

// Check if the sum is equal to the original number

if (sum == originalNum) {

cout << originalNum << " is an Armstrong number." << endl;

} else {

cout << originalNum << " is not an Armstrong number." << endl;

return 0;

Explanation:

1. Input: The program prompts the user to enter an integer.


2. Logic: First, the program calculates how many digits the number has (n).

It then computes the sum of the nth power of each digit using pow(remainder,
n). This is the key to determining if the number is an Armstrong number.

3. Armstrong Check:

An Armstrong number (or Narcissistic number) is one where the sum of its own
digits raised to the power of the number of digits equals the number itself.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


For example, 153 is an Armstrong number because 13+53+33=1531^3 + 5^3 +
3^3 = 15313+53+33=153.

Output: The program prints whether the number is an Armstrong number or not.

Example:

Input: 153

Output: 153 is an Armstrong number.

Input: 123

Output: 123 is not an Armstrong number.

PROBLEM:6

Question: Print All Divisors of a Number

Write a C++ program that takes an integer as input and prints all its divisors.

C++ Code:

cpp

Copy

#include <iostream>using namespace std;

int main() {

int num;

// Ask user to enter a number

cout << "Enter an integer: ";

cin >> num;

cout << "Divisors of " << num << " are: ";

// Loop through all numbers from 1 to num to find divisors

for (int i = 1; i <= num; i++) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (num % i == 0) {

cout << i << " "; // Print the divisor

cout << endl;

return 0;

Explanation:

Input: The program prompts the user to enter an integer.

Logic:

The program iterates over all numbers from 1 to the entered number (num).

For each number i, it checks if num % i == 0 (i.e., if i divides num without leaving
a remainder).

If true, i is a divisor of num and is printed.

Output: The program prints all divisors of the entered number.

Example:

Input: 12

Output: Divisors of 12 are: 1 2 3 4 6 12

PROBLEM:7

Question: Check if a Number is Prime

Write a C++ program that takes an integer as input and checks whether it is a prime
number or not.

C++ Code:

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Copy

#include <iostream>using namespace std;

int main() {

int num;

bool isPrime = true;

// Ask user to enter a number

cout << "Enter an integer: ";

cin >> num;

// Check if the number is less than or equal to 1

if (num <= 1) {

isPrime = false;

// Check for factors from 2 to sqrt(num)

for (int i = 2; i * i <= num; i++) {

if (num % i == 0) {

isPrime = false;

break;

// Output whether the number is prime

if (isPrime) {

cout << num << " is a prime number." << endl;

} else {

cout << num << " is not a prime number." << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return 0;

Explanation:

Input: The program asks the user to enter an integer.

Logic:

The program first checks if the number is less than or equal to 1. If it is, it
immediately marks it as not prime because prime numbers are greater than 1.

It then loops through all integers starting from 2 up to the square root of the number
(i * i <= num). This is an optimization, as if a number is divisible by a number
greater than its square root, it would already have been detected by smaller divisors.

If a divisor is found (i.e., num % i == 0), the number is not prime, and the loop breaks
early.

Output: The program prints whether the number is prime or not.

Example:

Input: 29


Output: 29 is a prime number.


Input: 15


Output: 15 is not a prime number.

PROBLEM:8

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question:Understand recursion by print something N times

Write a C++ program to print a message N times using recursion. The program
should take an integer N as input and print "Hello, World!" N times recursively.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to print "Hello, World!" N timesvoid printMessage(int n) {

if (n <= 0) // Base case: Stop when n reaches 0

return;

cout << "Hello, World!" << endl;

// Recursive call with n-1

printMessage(n - 1);

int main() {

int N;

// Taking input from the user

cout << "Enter the number of times to print the message: ";

cin >> N;

// Calling the recursive function

printMessage(N);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Explanation:

Base Case: If n <= 0, stop the recursion.

Recursive Step: Print "Hello, World!" and call printMessage(n-1).

PROBLEM:9

Question:Print name N times using recursion

Write a C++ program to print a name N times using recursion. The program
should take an integer N and a name as input, then print the name N times
recursively.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to print name N timesvoid printName(string name, int n) {

if (n <= 0) // Base case: Stop when n reaches 0

return;

cout << name << endl;

// Recursive call with n-1

printName(name, n - 1);

int main() {

int N;

string name;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input from the user

cout << "Enter your name: ";

cin >> name;

cout << "Enter the number of times to print your name: ";

cin >> N;

// Calling the recursive function

printName(name, N);

return 0;

Explanation:

Base Case: If n <= 0, the function stops recursion.

Recursive Step: Print the name and call printName(name, n-1).

User Input: The user provides a name and a number N, and the function prints the
name N times recursively.

PROBLEM:10

Question: Print Numbers from 1 to N Using Recursion

Write a C++ program that uses recursion to print numbers from 1 to N.

C++ Code:

cpp

Copy

#include <iostream>using namespace std;

// Recursive function to print numbers from 1 to Nvoid printNumbers(int n) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Base case: If n is less than 1, return (stop recursion)

if (n <= 0) {

return;

// Recursive case: Print numbers from 1 to n-1, then print n

printNumbers(n - 1); // Recursively call with n-1

cout << n << " "; // Print the current number

int main() {

int N;

// Ask user to enter the value of N

cout << "Enter the value of N: ";

cin >> N;

cout << "Numbers from 1 to " << N << " are: ";

// Call the recursive function

printNumbers(N);

cout << endl;

return 0;

Explanation:

Input: The program prompts the user to enter an integer N.

Logic:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The function printNumbers(int n) is the recursive function that prints numbers from
1 to n.

Base case: If n <= 0, the function returns without doing anything, which stops the
recursion.

Recursive case: The function first calls itself with n - 1 (printing numbers from 1 to
n-1), and then prints the current number n. This ensures that numbers are printed in
order from 1 to N.

Output: The program prints the numbers from 1 to N.

1.

Example:

Input: 5


Output: Numbers from 1 to 5 are: 1 2 3 4 5

PROBLEM:11

Question:Print N to 1 using recursion

Write a C++ program to print numbers from N to 1 using recursion. The


program should take an integer N as input and print the numbers in
descending order using recursion.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to print numbers from N to 1void printDescending(int n) {

if (n <= 0) // Base case: Stop when n reaches 0

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << n << " "; // Print the current number

// Recursive call with n-1

printDescending(n - 1);

int main() {

int N;

// Taking input from the user

cout << "Enter a number: ";

cin >> N;

// Calling the recursive function

printDescending(N);

return 0;

Explanation:

1.

Base Case: If n <= 0, stop recursion.

2.
3.

Recursive Step: Print n, then call printDescending(n - 1).

4.
5.

User Input: The user provides N, and the function prints numbers from N to 1.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


6.

PROBLEM:12

Question: Sum of first N numbers

Write a C++ program to find the sum of the first N natural numbers using
recursion. The program should take an integer N as input and return the sum
of numbers from 1 to N.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to calculate sum of first N numbersint sumOfN(int n) {

if (n == 0) // Base case: sum of first 0 numbers is 0

return 0;

return n + sumOfN(n - 1); // Recursive step: n + sum of (n-1) numbers

int main() {

int N;

// Taking input from the user

cout << "Enter a number: ";

cin >> N;

// Calling the recursive function and displaying result

cout << "Sum of first " << N << " numbers is: " << sumOfN(N) << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Explanation:

1.

Base Case: If n == 0, return 0 (stopping condition).

2.
3.

Recursive Step: Add n to the sum of (n-1) numbers.

4.
5.

User Input: The user provides N, and the function returns the sum from 1 to N.

6.

PROBLEM:13

Question: Factorial of N numbers

Write a C++ program to find the factorial of a number N using recursion. The
program should take an integer N as input and return the factorial of N.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to calculate factoriallong long factorial(int n) {

if (n == 0 || n == 1) // Base case: factorial of 0 and 1 is 1

return 1;

return n * factorial(n - 1); // Recursive step: n * (n-1)!

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

int N;

// Taking input from the user

cout << "Enter a number: ";

cin >> N;

// Calling the recursive function and displaying result

cout << "Factorial of " << N << " is: " << factorial(N) << endl;

return 0;

Explanation:

1.

Base Case: If n == 0 or n == 1, return 1 (stopping condition).

2.
3.

Recursive Step: Multiply n by factorial(n-1).

4.
5.

User Input: The user provides N, and the function returns N!.

6.

PROBLEM:14

Question: Reverse an array

Write a C++ program to reverse an array using recursion. The program should
take an array and its size as input, then reverse the array using a recursive
function.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to reverse an arrayvoid reverseArray(int arr[], int start, int end) {

if (start >= end) // Base case: When start meets or crosses end

return;

// Swap elements at start and end

swap(arr[start], arr[end]);

// Recursive call to reverse remaining array

reverseArray(arr, start + 1, end - 1);

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Calling the recursive function to reverse the array

reverseArray(arr, 0, N - 1);

// Displaying the reversed array

cout << "Reversed array: ";

for (int i = 0; i < N; i++)

cout << arr[i] << " ";

cout << endl;

return 0;

Explanation:

1.

Base Case: If start >= end, stop recursion.

2.
3.

Recursive Step: Swap arr[start] and arr[end], then call reverseArray(arr,


start+1, end-1).

4.
5.

User Input: The user enters the array size and elements, and the function
reverses them.

7.

PROBLEM:15

Question: Check if a string is palindrome or not

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Write a C++ program to check if a given string is a palindrome using recursion.
The program should take a string as input and determine whether it reads the
same forward and backward.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to check if a string is palindromebool isPalindrome(string &str, int start,


int end) {

if (start >= end) // Base case: If start crosses end, it's a palindrome

return true;

if (str[start] != str[end]) // If characters don't match, not a palindrome

return false;

// Recursive call with the next inner characters

return isPalindrome(str, start + 1, end - 1);

int main() {

string str;

// Taking input from the user

cout << "Enter a string: ";

cin >> str;

// Checking if the string is palindrome

if (isPalindrome(str, 0, str.length() - 1))

cout << "The string is a palindrome." << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else

cout << "The string is not a palindrome." << endl;

return 0;

Explanation:

1.

Base Case: If start >= end, return true (it’s a palindrome).

2.
3.

Recursive Step: If str[start] is not equal to str[end], return false.


Otherwise, check the next inner pair.

4.
5.

User Input: The user enters a string, and the function determines if it's a
palindrome.

PROBLEM:16

Question: Fibonacci Number

Write a C++ program to find the Nth Fibonacci number using recursion. The
program should take an integer N as input and return the Nth Fibonacci
number.

C++ Code:

cpp

CopyEdit

#include <iostream>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Recursive function to find Nth Fibonacci numberint fibonacci(int n) {

if (n <= 1) // Base case: F(0) = 0, F(1) = 1

return n;

return fibonacci(n - 1) + fibonacci(n - 2); // Recursive step

int main() {

int N;

// Taking input from the user

cout << "Enter the position (N): ";

cin >> N;

// Calling the recursive function and displaying result

cout << "The " << N << "th Fibonacci number is: " << fibonacci(N) << endl;

return 0;

Explanation:

1.

Base Case: If n == 0, return 0; if n == 1, return 1.

2.
3.

Recursive Step: F(n) = F(n-1) + F(n-2), computing Fibonacci numbers


recursively.

4.
5.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


User Input: The user provides N, and the function returns the Nth Fibonacci
number.

PROBLEM:17

Question: Hashing Theory

Write a C++ program to demonstrate hashing using an unordered map (hash


table). The program should allow storing key-value pairs and retrieving values
based on keys.

C++ Code:

cpp

CopyEdit

#include <iostream>

#include <unordered_map>

using namespace std;

int main() {

// Creating an unordered map (hash table)

unordered_map<int, string> hashTable;

// Inserting key-value pairs

hashTable[1] = "Alice";

hashTable[2] = "Bob";

hashTable[3] = "Charlie";

// Taking key input from the user

int key;

cout << "Enter a key (1-3) to retrieve value: ";

cin >> key;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Searching for the key in the hash table

if (hashTable.find(key) != hashTable.end()) {

cout << "Value at key " << key << " is: " << hashTable[key] << endl;

} else {

cout << "Key not found in the hash table." << endl;

return 0;

Explanation:

1.

Unordered Map: A built-in hash table (unordered_map<int, string>) is used


for hashing.

2.
3.

Insertion: Key-value pairs (1 → "Alice", 2 → "Bob", 3 → "Charlie") are


inserted.

4.
5.

Lookup: The user enters a key, and the program retrieves the corresponding
value using hashing.

PROBLEM:18

Question: Counting frequencies of array elements

Write a C++ program to count the frequency of each element in an array using
hashing. The program should take an array as input and display the frequency
of each element.

C++ Code:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

CopyEdit

#include <iostream>

#include <unordered_map>

using namespace std;

// Function to count frequencies of array elementsvoid countFrequencies(int arr[], int size) {

unordered_map<int, int> freqMap; // Hash table to store frequencies

// Counting occurrences of each element

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

freqMap[arr[i]]++;

// Displaying frequencies

cout << "Element Frequencies:\n";

for (auto it : freqMap) {

cout << it.first << " appears " << it.second << " times\n";

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Calling the function to count frequencies

countFrequencies(arr, N);

return 0;

Explanation:

1.

Unordered Map: A hash table (unordered_map<int, int>) is used to store


the frequency of each number.

2.
3.

Insertion: Each element's count is updated as we traverse the array.

4.
5.

Display: The program prints each unique element with its frequency.

6.

PROBLEM:19

Question: Find the highest/lowest frequency element

Write a C++ program to find the element with the highest and lowest frequency
in an array using hashing. The program should take an array as input and
determine which element appears most and least frequently.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code:

cpp

CopyEdit

#include <iostream>#include <unordered_map>using namespace std;

// Function to find the highest and lowest frequency elementsvoid findFrequencyElements(int


arr[], int size) {

unordered_map<int, int> freqMap; // Hash table to store frequencies

// Counting occurrences of each element

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

freqMap[arr[i]]++;

// Finding elements with highest and lowest frequency

int maxFreq = 0, minFreq = size;

int maxElement, minElement;

for (auto it : freqMap) {

if (it.second > maxFreq) {

maxFreq = it.second;

maxElement = it.first;

if (it.second < minFreq) {

minFreq = it.second;

minElement = it.first;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Displaying the results

cout << "Element with highest frequency: " << maxElement << " (appears " << maxFreq << "
times)" << endl;

cout << "Element with lowest frequency: " << minElement << " (appears " << minFreq << "
times)" << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Calling the function to find highest and lowest frequency elements

findFrequencyElements(arr, N);

return 0;

Explanation:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1.

Unordered Map: A hash table (unordered_map<int, int>) is used to count


the occurrences of each number.

2.
3.

Finding Max/Min Frequency:

4.
1.

The element with the highest frequency is stored in maxElement.

2.
3.

The element with the lowest frequency is stored in minElement.

4.
5.

User Input: The user provides an array, and the


program finds and prints the most and least frequency

PROBLEM:20

Question: Selection Sort

Write a C++ program to implement Selection Sort. The program should take an
array as input and sort it in ascending order using the Selection Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to perform Selection Sortvoid selectionSort(int arr[], int n) {

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

int minIndex = i; // Assume the first element is the minimum

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Find the index of the smallest element in the remaining array

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex])

minIndex = j;

// Swap the found minimum element with the first element of the unsorted part

swap(arr[i], arr[minIndex]);

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cin >> arr[i];

// Sorting the array using Selection Sort

selectionSort(arr, N);

// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

return 0;

Explanation:

1.

Selection Sort Algorithm:

2.
1.

Find the smallest element in the unsorted part of the array.

2.
3.

Swap it with the first element of the unsorted part.

4.
5.

Repeat for the remaining elements.

6.
3.

Time Complexity: O(N²) in the worst and average case.

4.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


5.

User Input: The user provides an array, and the program sorts it using
Selection Sort.

6.

PROBLEM:21
Question: Bubble Sort

Write a C++ program to implement Bubble Sort. The program should take an
array as input and sort it in ascending order using the Bubble Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to perform Bubble Sortvoid bubbleSort(int arr[], int n) {

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

bool swapped = false; // Optimization: Track if swapping occurred

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

if (arr[j] > arr[j + 1]) {

swap(arr[j], arr[j + 1]); // Swap if elements are in the wrong order

swapped = true;

// If no swapping happened, the array is already sorted

if (!swapped)

break;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array using Bubble Sort

bubbleSort(arr, N);

// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

Explanation:

1.

Bubble Sort Algorithm:

2.
1.

Repeatedly compare adjacent elements and swap them if they are in


the wrong order.

2.
3.

The largest element "bubbles up" to the correct position in each pass.

4.
5.

The process is repeated until the entire array is sorted.

6.
3.

Optimization: If no swaps occur in a pass, the array is already sorted, and


we break early.

4.
5.

Time Complexity:

6.

1.

Worst & Average Case: O(N²)

2.
3.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Best Case (Already Sorted): O(N) (due to the optimization)

4.

PROBLEM:22
Question: Insertion Sort

Write a C++ program to implement Insertion Sort. The program should take an
array as input and sort it in ascending order using the Insertion Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to perform Insertion Sortvoid insertionSort(int arr[], int n) {

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

int key = arr[i]; // The element to be inserted in the sorted part

int j = i - 1;

// Move elements greater than 'key' one position ahead

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = key; // Insert 'key' at its correct position

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array using Insertion Sort

insertionSort(arr, N);

// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

return 0;

Explanation:

1.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Insertion Sort Algorithm:

2.
1.

Consider the first element as already sorted.

2.
3.

Take the next element and insert it into the correct position within the
sorted part.

4.
5.

Repeat for all elements.

6.
3.

Time Complexity:

4.

1.

Worst & Average Case: O(N²)

2.
3.

Best Case (Already Sorted): O(N)

4.

5.

User Input: The user enters an array, and the program sorts it using Insertion
Sort.

6.

5.

PROBLEM:23

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question: Merge Sort

Write a C++ program to implement Merge Sort. The program should take an
array as input and sort it in ascending order using the Merge Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to merge two sorted halvesvoid merge(int arr[], int left, int mid, int right) {

int n1 = mid - left + 1;

int n2 = right - mid;

int leftArr[n1], rightArr[n2];

// Copy data to temporary arrays

for (int i = 0; i < n1; i++)

leftArr[i] = arr[left + i];

for (int i = 0; i < n2; i++)

rightArr[i] = arr[mid + 1 + i];

// Merge the temporary arrays back into the original array

int i = 0, j = 0, k = left;

while (i < n1 && j < n2) {

if (leftArr[i] <= rightArr[j]) {

arr[k] = leftArr[i];

i++;

} else {

arr[k] = rightArr[j];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


j++;

k++;

// Copy any remaining elements from leftArr[]

while (i < n1) {

arr[k] = leftArr[i];

i++;

k++;

// Copy any remaining elements from rightArr[]

while (j < n2) {

arr[k] = rightArr[j];

j++;

k++;

// Function to implement Merge Sortvoid mergeSort(int arr[], int left, int right) {

if (left < right) {

int mid = left + (right - left) / 2;

// Recursively sort the left and right halves

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

// Merge the sorted halves

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


merge(arr, left, mid, right);

// Function to print the arrayvoid printArray(int arr[], int size) {

for (int i = 0; i < size; i++)

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array using Merge Sort

mergeSort(arr, 0, N - 1);

// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

Explanation:

1.

Merge Sort Algorithm:

2.
1.

Recursively divide the array into two halves until each half has one
element.

2.
3.

Merge the sorted halves back together in sorted order.

4.
3.

Merge Function: Combines two sorted subarrays into one sorted array.

4.
5.

Time Complexity:

6.

1.

Worst, Best, and Average Case: O(N log N) (efficient for large
datasets).

2.

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:24

Question: Recursive Bubble Sort

Write a C++ program to implement Bubble Sort using recursion. The program
should take an array as input and sort it in ascending order using the
recursive Bubble Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to perform Bubble Sortvoid recursiveBubbleSort(int arr[], int n) {

// Base case: If the array has 1 or no elements, it is already sorted

if (n == 1)

return;

// Perform one pass of Bubble Sort (largest element moves to the end)

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

if (arr[i] > arr[i + 1]) {

swap(arr[i], arr[i + 1]);

// Recursive call for the remaining unsorted part

recursiveBubbleSort(arr, n - 1);

// Function to print the arrayvoid printArray(int arr[], int n) {

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

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array using recursive Bubble Sort

recursiveBubbleSort(arr, N);

// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

return 0;

Explanation:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1.

Recursive Bubble Sort Algorithm:

2.
1.

In each recursive call, perform one pass of Bubble Sort to move the
largest element to the end.

2.
3.

Recursively call the function for the remaining unsorted portion.

4.
5.

Base case: If only one element remains, stop recursion.

6.
3.

Time Complexity:

4.

1.

Worst & Average Case: O(N²)

2.
3.

Best Case (Already Sorted): O(N²) (still has recursive calls).

4.

5.

User Input: The user enters an array, and the program sorts it recursively.

6.

7.

PROBLEM:25

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question: Recursive Insertion Sort

Write a C++ program to implement Insertion Sort using recursion. The program
should take an array as input and sort it in ascending order using the
recursive Insertion Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Recursive function to perform Insertion Sortvoid recursiveInsertionSort(int arr[], int n) {

// Base case: If array has 1 or no elements, it is already sorted

if (n <= 1)

return;

// Sort the first (n-1) elements recursively

recursiveInsertionSort(arr, n - 1);

// Insert the last element at its correct position

int last = arr[n - 1];

int j = n - 2;

// Shift elements of the sorted part to make space for 'last'

while (j >= 0 && arr[j] > last) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = last;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array using recursive Insertion Sort

recursiveInsertionSort(arr, N);

// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Explanation:

1.

Recursive Insertion Sort Algorithm:

2.
1.

Base Case: If the array has only one element, it is already sorted.

2.
3.

Recursive Case:

4.
1.

Recursively sort the first (N-1) elements.

2.
3.

Insert the last element at its correct position by shifting elements.

4.
3.

Time Complexity:

4.

1.

Worst & Average Case: O(N²)

2.
3.

Best Case (Already Sorted): O(N)

4.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


5. s

User Input: The user enters an array, and the program sorts it recursively
using Insertion Sort.

6.

PROBLEM:25
Question: Quick Sort

Write a C++ program to implement Quick Sort. The program should take an
array as input and sort it in ascending order using the Quick Sort algorithm.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to partition the arrayint partition(int arr[], int low, int high) {

int pivot = arr[high]; // Choosing the last element as pivot

int i = low - 1; // Index of smaller element

for (int j = low; j < high; j++) {

if (arr[j] < pivot) { // If current element is smaller than pivot

i++;

swap(arr[i], arr[j]);

swap(arr[i + 1], arr[high]); // Place pivot at the correct position

return i + 1;

// Function to perform Quick Sortvoid quickSort(int arr[], int low, int high) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (low < high) {

int pivotIndex = partition(arr, low, high); // Find pivot position

quickSort(arr, low, pivotIndex - 1); // Recursively sort left part

quickSort(arr, pivotIndex + 1, high); // Recursively sort right part

// Function to print the arrayvoid printArray(int arr[], int size) {

for (int i = 0; i < size; i++)

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array using Quick Sort

quickSort(arr, 0, N - 1);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Displaying the sorted array

cout << "Sorted array: ";

printArray(arr, N);

return 0;

Explanation:

1.

Quick Sort Algorithm:

2.
1.

Select a pivot element (last element in this case).

2.
3.

Partition the array so that elements smaller than the pivot are on the
left, and larger elements are on the right.

4.
5.

Recursively apply Quick Sort on the left and right subarrays.

6.
3.

Partition Function:

4.

1.

Swaps elements to ensure proper placement of the pivot.

2.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


5.

Time Complexity:

6.

1.

Worst Case: O(N²) (if pivot is always the smallest or largest element).

2.
3.

Best & Average Case: O(N log N) (if the pivot is well chosen).

4.

7.
8.

PROBLEM:26
Question: Largest Element in an Array

Write a C++ program to find the largest element in an array. The program
should take an array as input and return the maximum element present in the
array.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the largest element in the arrayint findLargestElement(int arr[], int n) {

int maxElement = arr[0]; // Assume the first element is the largest

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

if (arr[i] > maxElement) {

maxElement = arr[i]; // Update maxElement if a larger element is found

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return maxElement;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding the largest element in the array

int largest = findLargestElement(arr, N);

// Displaying the largest element

cout << "The largest element in the array is: " << largest << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Explanation:

1.

Algorithm:

2.
1.

Assume the first element is the largest.

2.
3.

Iterate through the array, comparing each element with the current
maximum.

4.
5.

Update the maximum if a larger element is found.

6.
3.

Time Complexity: O(N) (Linear scan through the array).

4.
5.

User Input: The user enters an array, and the program finds and displays the
largest element.

6.

PROBLEM:27
Question: Second Largest Element in an Array

Write a C++ program to find the largest element in an array. The program
should take an array as input and return the maximum element present in the
array.

C++ Code:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the largest element in the arrayint findLargestElement(int arr[], int n) {

int maxElement = arr[0]; // Assume the first element is the largest

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

if (arr[i] > maxElement) {

maxElement = arr[i]; // Update maxElement if a larger element is found

return maxElement;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Finding the largest element in the array

int largest = findLargestElement(arr, N);

// Displaying the largest element

cout << "The largest element in the array is: " << largest << endl;

return 0;

Explanation:

1.

Algorithm:

2.
1.

Assume the first element is the largest.

2.
3.

Iterate through the array, comparing each element with the current
maximum.

4.
5.

Update the maximum if a larger element is found.

6.
3.

Time Complexity: O(N) (Linear scan through the array).

4.
5.

User Input: The user enters an array, and the program finds and displays the
largest element.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


6.

Would you like a program that also finds the second-largest element? �

4o

You said:

Second Largest Element in an Array without sorting write a code in cpp and highlight the
question espically

ChatGPT said:

Question:

Write a C++ program to find the second largest element in an array without
sorting. The program should take an array as input and return the second
largest element present in the array.

C++ Code:

cpp

CopyEdit

#include <iostream>#include <climits> // For INT_MINusing namespace std;

// Function to find the second largest element in the arrayint findSecondLargest(int arr[], int n) {

if (n < 2) {

cout << "Array must have at least two elements!" << endl;

return -1; // Invalid case

int firstLargest = INT_MIN, secondLargest = INT_MIN;

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

if (arr[i] > firstLargest) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


secondLargest = firstLargest; // Update second largest

firstLargest = arr[i]; // Update first largest

} else if (arr[i] > secondLargest && arr[i] != firstLargest) {

secondLargest = arr[i]; // Update second largest

return (secondLargest == INT_MIN) ? -1 : secondLargest;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding the second largest element in the array

int secondLargest = findSecondLargest(arr, N);

if (secondLargest != -1)

cout << "The second largest element in the array is: " << secondLargest << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else

cout << "No second largest element found!" << endl;

return 0;

Explanation:

1.

Algorithm (Without Sorting):

2.

1.

Initialize firstLargest and secondLargest to INT_MIN.

2.
3.

Traverse the array once:

4.

1.

If a number is greater than firstLargest, update secondLargest


first, then update firstLargest.

2.
3.

If a number is not equal to firstLargest but greater than


secondLargest, update secondLargest.

4.

5.

If secondLargest remains INT_MIN, no second largest exists.

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3.

Time Complexity: O(N) (Only a single pass is required).

4.
5.

Space Complexity: O(1) (No extra storage is used).

6.

PROBLEM:28
Question: Check if the array is sorted

Write a C++ program to check if an array is sorted in non-decreasing order.


The program should take an array as input and return whether it is sorted or
not.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to check if the array is sortedbool isSorted(int arr[], int n) {

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

if (arr[i] < arr[i - 1]) {

return false; // If any element is smaller than its previous one, the array is not sorted

return true; // If no such condition is met, the array is sorted

int main() {

int N;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Checking if the array is sorted

if (isSorted(arr, N))

cout << "The array is sorted." << endl;

else

cout << "The array is NOT sorted." << endl;

return 0;

Explanation:

1.

Algorithm:

2.
1.

Start from index 1 and check if every element is greater than or equal
to its previous one.

2.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3.

If we find arr[i] < arr[i-1], return false (not sorted).

4.
5.

If we traverse the whole array without finding a violation, return true


(sorted).

6.
3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (No extra storage used).

6.

PROBLEM:29
Question: Remove duplicates from Sorted array

Write a C++ program to remove duplicate elements from a sorted array. The
program should take a sorted array as input and modify it to contain only
unique elements while maintaining the original order.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to remove duplicates from a sorted arrayint removeDuplicates(int arr[], int n) {

if (n == 0 || n == 1) {

return n; // If array has 0 or 1 elements, no duplicates exist

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int j = 0; // Pointer for the unique elements

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

if (arr[i] != arr[i + 1]) {

arr[j++] = arr[i]; // Store unique elements

arr[j++] = arr[n - 1]; // Store the last element (always unique)

return j; // Return the new size of the array

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the sorted array: ";

cin >> N;

int arr[N];

// Taking input for sorted array elements

cout << "Enter " << N << " sorted elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Removing duplicates

int newSize = removeDuplicates(arr, N);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Displaying the modified array

cout << "Array after removing duplicates: ";

for (int i = 0; i < newSize; i++)

cout << arr[i] << " ";

cout << endl;

return 0;

Explanation:

1.

Algorithm:

2.
1.

Since the array is sorted, duplicates will be adjacent.

2.
3.

Traverse the array and copy only unique elements to a new position (j).

4.
5.

Return the new length of the modified array.

6.
3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (Modifies the array in place without extra storage).

PROBLEM:30
The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)
Question:

Write a C++ program to left rotate an array by one place. The program should
take an array as input and shift all elements one position to the left, with the
first element moving to the last position.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to left rotate an array by one placevoid leftRotateByOne(int arr[], int n) {

if (n <= 1) return; // No rotation needed for arrays of size 0 or 1

int first = arr[0]; // Store the first element

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

arr[i] = arr[i + 1]; // Shift elements left

arr[n - 1] = first; // Move first element to the last position

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Left rotating the array by one place

leftRotateByOne(arr, N);

// Displaying the rotated array

cout << "Array after left rotation by one place: ";

printArray(arr, N);

return 0;

Explanation:

1.

Algorithm:

2.
1.

Store the first element in a temporary variable.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2.
3.

Shift all elements to the left (i.e., move arr[i] to arr[i-1]).

4.
5.

Place the first element at the last index.

6.
3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (In-place modification).

6.

PROBLEM:31
Question: Left rotate an array by D places

Write a C++ program to left rotate an array by D places. The program should
take an array and a rotation count D as input and shift all elements D positions
to the left, wrapping around the elements that move past the first position.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to reverse a part of the arrayvoid reverseArray(int arr[], int start, int end) {

while (start < end) {

swap(arr[start], arr[end]);

start++;

end--;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Function to left rotate the array by D placesvoid leftRotateByD(int arr[], int n, int d) {

d = d % n; // Handle cases where D > N

// Step 1: Reverse the first D elements

reverseArray(arr, 0, d - 1);

// Step 2: Reverse the remaining elements

reverseArray(arr, d, n - 1);

// Step 3: Reverse the entire array

reverseArray(arr, 0, n - 1);

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

int N, D;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Taking input for number of places to rotate

cout << "Enter the number of places to rotate: ";

cin >> D;

// Left rotating the array by D places

leftRotateByD(arr, N, D);

// Displaying the rotated array

cout << "Array after left rotation by " << D << " places: ";

printArray(arr, N);

return 0;

Explanation:

1.

Algorithm (Using Reversal Method - O(N) Time Complexity, O(1) Space


Complexity):

2.
1.

Step 1: Reverse the first D elements.

2.
3.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Step 2: Reverse the remaining N - D elements.

4.
5.

Step 3: Reverse the entire array to get the final rotated array.

6.
3.

Handling Large D:

4.

1.

If D > N, we take D % N to avoid unnecessary rotations.

2.

5.

Time Complexity: O(N) (Efficient single-pass reversal).

6.
7.

Space Complexity: O(1) (In-place rotation without extra storage).

PROBLEM:32
Question: Move Zeros to end

Write a C++ program to move all zeros in an array to the end while maintaining
the order of non-zero elements. The program should take an array as input and
modify it in-place without using extra space.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to move all zeros to the end of the arrayvoid moveZerosToEnd(int arr[], int n) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int nonZeroIndex = 0; // Position to place non-zero elements

// Traverse the array and move non-zero elements forward

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

if (arr[i] != 0) {

swap(arr[i], arr[nonZeroIndex]);

nonZeroIndex++;

// Function to print the arrayvoid printArray(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Moving zeros to the end

moveZerosToEnd(arr, N);

// Displaying the modified array

cout << "Array after moving zeros to the end: ";

printArray(arr, N);

return 0;

Explanation:

1.

Algorithm:

2.
1.

Use a pointer nonZeroIndex to track the position where non-zero


elements should be placed.

2.
3.

Traverse the array, and whenever a non-zero element is found, swap it


with the nonZeroIndex.

4.
5.

This method ensures all non-zero elements are placed at the beginning
while maintaining their order, and zeros are shifted to the end.

6.
3.

Time Complexity: O(N) (Single pass through the array).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4.
5.

Space Complexity: O(1) (In-place modification, no extra storage used).

PROBLEM:33
Question: Linear Search

Write a C++ program to implement Linear Search. The program should take an
array and a target element as input, search for the target in the array, and
return its index if found. If the element is not present, return -1.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to perform Linear Searchint linearSearch(int arr[], int n, int target) {

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

if (arr[i] == target) {

return i; // Return the index of the target element

return -1; // Return -1 if the element is not found

int main() {

int N, target;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Taking input for target element

cout << "Enter the element to search: ";

cin >> target;

// Performing Linear Search

int index = linearSearch(arr, N, target);

// Displaying the result

if (index != -1)

cout << "Element found at index: " << index << endl;

else

cout << "Element not found in the array." << endl;

return 0;

Explanation:

1.

Algorithm:

2.
1.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Traverse the array from the start.

2.
3.

Compare each element with the target.

4.
5.

If found, return the index.

6.
7.

If the loop completes without finding the element, return -1.

8.
3.

Time Complexity: O(N) (Worst case: The target is at the last position or not
present).

4.
5.

Space Complexity: O(1) (No extra space used).

PROBLEM:34
Question: Find the Union

Write a C++ program to find the union of two arrays. The program should take
two arrays as input and return a new array containing all unique elements from
both arrays.

C++ Code:

cpp

CopyEdit

#include <iostream>#include <set>using namespace std;

// Function to find the union of two arraysvoid findUnion(int arr1[], int n1, int arr2[], int n2) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


set<int> unionSet; // Using a set to store unique elements

// Insert all elements of the first array

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

unionSet.insert(arr1[i]);

// Insert all elements of the second array

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

unionSet.insert(arr2[i]);

// Printing the union of both arrays

cout << "Union of the two arrays: ";

for (int element : unionSet) {

cout << element << " ";

cout << endl;

int main() {

int n1, n2;

// Taking input for the first array

cout << "Enter the size of the first array: ";

cin >> n1;

int arr1[n1];

cout << "Enter " << n1 << " elements: ";

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

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cin >> arr1[i];

// Taking input for the second array

cout << "Enter the size of the second array: ";

cin >> n2;

int arr2[n2];

cout << "Enter " << n2 << " elements: ";

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

cin >> arr2[i];

// Finding and printing the union

findUnion(arr1, n1, arr2, n2);

return 0;

Explanation:

1.

Algorithm:

2.
1.

Use a set to store only unique elements.

2.
3.

Insert elements from both arrays into the set.

4.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


5.

Print the set, which contains the union of both arrays.

6.
3.

Time Complexity: O(N + M) (Each element is inserted into a set in constant


time on average).

4.
5.

Space Complexity: O(N + M) (Set stores unique elements from both arrays).

6.

PROBLEM:35
Question: Find missing number in an array

Write a C++ program to find the missing number in an array containing N


distinct numbers from 1 to N+1. The program should take an array of size N as
input and return the missing number.

C++ Code:

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the missing number using sum formulaint findMissingNumber(int arr[], int n)
{

int totalSum = (n + 1) * (n + 2) / 2; // Sum of first (N+1) natural numbers

int arraySum = 0;

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

arraySum += arr[i]; // Sum of elements in the given array

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return totalSum - arraySum; // Missing number = Total sum - Array sum

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array (N): ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements (1 to " << N + 1 << " with one missing): ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying the missing number

int missingNumber = findMissingNumber(arr, N);

cout << "The missing number is: " << missingNumber << endl;

return 0;

Explanation:

1.

Algorithm:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2.
1.

The sum of the first (N+1) natural numbers is calculated using the
formula:

2. Sum=(N+1)×(N+2)2\text{Sum} = \frac{(N+1) \times


(N+2)}{2}Sum=2(N+1)×(N+2)​
3.

Compute the sum of the given array.

4.
5.

The missing number is found by subtracting the array sum from the
total sum.

6.
3.

Time Complexity: O(N) (Single pass to compute the sum).

4.
5.

Space Complexity: O(1) (No extra space used).

6.

PROBLEM:36

Question: Maximum Consecutive Ones

Write a C++ program to find the maximum number of consecutive 1s in a


binary array. The program should take a binary array (containing only 0s and
1s) as input and return the maximum count of consecutive 1s.

C++ Code:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the maximum consecutive ones in a binary arrayint maxConsecutiveOnes(int


arr[], int n) {

int maxCount = 0, currentCount = 0;

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

if (arr[i] == 1) {

currentCount++; // Increase count if 1 is found

maxCount = max(maxCount, currentCount); // Update max count

} else {

currentCount = 0; // Reset count if 0 is found

return maxCount;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the binary array: ";

cin >> N;

int arr[N];

// Taking input for array elements (only 0s and 1s)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Enter " << N << " elements (only 0s and 1s): ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying the maximum consecutive ones

int result = maxConsecutiveOnes(arr, N);

cout << "Maximum consecutive ones: " << result << endl;

return 0;

Explanation:

1.

Algorithm:

2.
1.

Traverse the array and keep counting consecutive 1s.

2.
3.

If a 0 is encountered, reset the count.

4.
5.

Update maxCount whenever currentCount is greater.

6.
3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Space Complexity: O(1) (Only variables used, no extra space required).

PROBLEM:37

Question: Find the number that appears once, and other numbers twice.

Write a C++ program to find the number that appears only once in an array
where every other number appears exactly twice. The program should take an
array as input and return the unique number.

C++ Code (Using XOR Method - Optimal Approach)

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the number that appears onceint findUniqueNumber(int arr[], int n) {

int unique = 0;

// XOR all elements of the array

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

unique ^= arr[i]; // XOR cancels out duplicate numbers

return unique; // The remaining number is the unique one

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array (odd number, as one element appears once): ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " elements (where every number appears twice except one): ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying the unique number

int uniqueNumber = findUniqueNumber(arr, N);

cout << "The unique number is: " << uniqueNumber << endl;

return 0;

Explanation:

1.

Algorithm (Using XOR Property):

2.
1.

x ^ x = 0 (A number XORed with itself cancels out).

2.
3.

x ^ 0 = x (XOR with zero leaves the number unchanged).

4.
5.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


XORing all numbers in the array cancels out the duplicate elements,
leaving only the unique number.

6.
3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (Uses only a single variable).

6.

PROBLEM:38
Question: Longest subarray with given sum K(positives)

Write a C++ program to find the length of the longest subarray with a given
sum K. The program should take an array of positive integers as input and
return the maximum length of a contiguous subarray whose sum equals K.

C++ Code (Using Two-Pointer/Sliding Window Approach - Optimal for


Positive Numbers)

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the longest subarray with sum Kint longestSubarrayWithSumK(int arr[], int n,
int K) {

int left = 0, right = 0, sum = 0, maxLength = 0;

while (right < n) {

sum += arr[right]; // Expand the window by adding the right element

// Shrink the window from the left if sum exceeds K

while (sum > K && left <= right) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


sum -= arr[left];

left++;

// Update max length if the current sum equals K

if (sum == K) {

maxLength = max(maxLength, right - left + 1);

right++; // Move right pointer forward

return maxLength;

int main() {

int N, K;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " positive integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input for sum K

cout << "Enter the target sum K: ";

cin >> K;

// Finding and displaying the longest subarray length

int maxLength = longestSubarrayWithSumK(arr, N, K);

cout << "Length of the longest subarray with sum " << K << " is: " << maxLength << endl;

return 0;

Explanation:

1.

Algorithm (Using Two-Pointer/Sliding Window Technique - O(N)):

2.
1.

Maintain a window using two pointers (left and right).

2.
3.

Expand the window (right++) and keep adding elements to sum.

4.
5.

If sum > K, shrink the window by moving left++.

6.
7.

If sum == K, update the maximum length.

8.
9.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Continue until the entire array is processed.

10.
3.

Time Complexity: O(N) (Each element is processed at most twice).

4.
5.

Space Complexity: O(1) (Only variables used, no extra space).

6.

PROBLEM:39
Question: Longest subarray with sum K (Positives + Negatives)

Write a C++ program to find the length of the longest subarray with a given
sum K, where the array may contain both positive and negative numbers. The
program should take an array and K as input and return the maximum length of
a contiguous subarray whose sum equals K.

C++ Code (Using HashMap for Efficient Computation - Works with Positive
& Negative Numbers)

cpp

CopyEdit

#include <iostream>#include <unordered_map>using namespace std;

// Function to find the longest subarray with sum K (works for positives + negatives)int
longestSubarrayWithSumK(int arr[], int n, int K) {

unordered_map<int, int> prefixSumMap; // Stores (prefix_sum, first_index)

int sum = 0, maxLength = 0;

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

sum += arr[i]; // Compute prefix sum

// If sum itself becomes K, update maxLength

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (sum == K) {

maxLength = i + 1;

// Check if (sum - K) exists in the map (it means subarray sum K exists)

if (prefixSumMap.find(sum - K) != prefixSumMap.end()) {

maxLength = max(maxLength, i - prefixSumMap[sum - K]);

// Store the first occurrence of prefix sum

if (prefixSumMap.find(sum) == prefixSumMap.end()) {

prefixSumMap[sum] = i;

return maxLength;

int main() {

int N, K;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers (positive, negative, or zero): ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = 0; i < N; i++)

cin >> arr[i];

// Taking input for sum K

cout << "Enter the target sum K: ";

cin >> K;

// Finding and displaying the longest subarray length

int maxLength = longestSubarrayWithSumK(arr, N, K);

cout << "Length of the longest subarray with sum " << K << " is: " << maxLength << endl;

return 0;

Explanation:

1.

Algorithm (Using HashMap - O(N)):

2.
1.

Maintain a prefix sum while traversing the array.

2.
3.

If sum == K, update maxLength to the current index +1.

4.
5.

If (sum - K) exists in the hashmap, it means a subarray with sum K


exists. Update maxLength.

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


7.

Store the first occurrence of each prefix sum in the hashmap.

8.
3.

Time Complexity: O(N) (Each element is processed once).

4.
5.

Space Complexity: O(N) (Uses hashmap for prefix sums).

PROBLEM:40

Question: 2Sum Problem


Write a C++ program to find two numbers in an array that add up to a given
sum K. The program should take an array and K as input and return the indices
of the two numbers (or a message if no such pair exists).

C++ Code (Using HashMap for Optimal Solution - O(N))

cpp

CopyEdit

#include <iostream>#include <unordered_map>using namespace std;

// Function to find the indices of two numbers that sum up to Kvoid twoSum(int arr[], int n, int K)
{

unordered_map<int, int> numIndexMap; // Stores (value, index)

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

int complement = K - arr[i]; // Find the required pair

// If the complement is found in the map, return the indices

if (numIndexMap.find(complement) != numIndexMap.end()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Pair found at indices: " << numIndexMap[complement] << " and " << i <<
endl;

return;

// Store the current number's index in the map

numIndexMap[arr[i]] = i;

// If no pair is found

cout << "No pair found that sums up to " << K << endl;

int main() {

int N, K;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Taking input for target sum K

cout << "Enter the target sum K: ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cin >> K;

// Finding and displaying the pair of indices

twoSum(arr, N, K);

return 0;

Explanation:

1.

Algorithm (Using HashMap - O(N)):

2.
1.

Maintain a hashmap to store numbers and their indices.

2.
3.

For each number, calculate its complement (K - arr[i]).

4.
5.

If the complement exists in the hashmap, print the pair's indices.

6.
7.

Otherwise, store the number's index in the hashmap.

8.
3.

Time Complexity: O(N) (Each element is processed once).

4.
5.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Space Complexity: O(N) (Stores elements in a hashmap).

6.

PROBLEM:41
Question: Sort an array of 0's 1's and 2's

Write a C++ program to sort an array consisting only of 0s, 1s, and 2s in O(N)
time complexity without using extra space. The program should take an array
as input and return the sorted array.

C++ Code (Using Dutch National Flag Algorithm - Optimal Approach)

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to sort the array of 0s, 1s, and 2svoid sortArray(int arr[], int n) {

int low = 0, mid = 0, high = n - 1;

while (mid <= high) {

if (arr[mid] == 0) {

swap(arr[low], arr[mid]);

low++;

mid++;

} else if (arr[mid] == 1) {

mid++; // Move forward if it's 1

} else { // arr[mid] == 2

swap(arr[mid], arr[high]);

high--;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements (only 0s, 1s, and 2s)

cout << "Enter " << N << " elements (only 0s, 1s, and 2s): ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Sorting the array

sortArray(arr, N);

// Displaying the sorted array

cout << "Sorted array: ";

for (int i = 0; i < N; i++)

cout << arr[i] << " ";

cout << endl;

return 0;

Explanation:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1.

Algorithm (Using Dutch National Flag Algorithm - O(N)):

2.
1.

Maintain three pointers:

2.
1.

low (tracks the position for 0s).

2.
3.

mid (current element being checked).

4.
5.

high (tracks the position for 2s).

6.
3.

Traverse the array:

4.

1.

If arr[mid] == 0, swap with low, and move both pointers right.

2.
3.

If arr[mid] == 1, just move mid forward.

4.
5.

If arr[mid] == 2, swap with high, and move high left.

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (No extra space used).

6.

7.

PROBLEM:42
Question: Majority Element (>n/2 times)

Write a C++ program to find the majority element in an array, where the
majority element is defined as an element that appears more than N/2 times.
The program should take an array as input and return the majority element. If
no majority element exists, return -1.

C++ Code (Using Moore's Voting Algorithm - Optimal Approach)

cpp

CopyEdit

#include <iostream>using namespace std;

// Function to find the majority element using Moore’s Voting Algorithmint


findMajorityElement(int arr[], int n) {

int candidate = -1, count = 0;

// Step 1: Find the candidate for the majority element

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

if (count == 0) {

candidate = arr[i];

count = 1;

} else if (arr[i] == candidate) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


count++;

} else {

count--;

// Step 2: Verify if the candidate is actually a majority element

count = 0;

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

if (arr[i] == candidate)

count++;

return (count > n / 2) ? candidate : -1;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Finding and displaying the majority element

int majorityElement = findMajorityElement(arr, N);

if (majorityElement != -1)

cout << "The majority element is: " << majorityElement << endl;

else

cout << "No majority element found." << endl;

return 0;

Explanation:

1.

Algorithm (Using Moore’s Voting Algorithm - O(N)):

2.
1.

Step 1 (Find Candidate):

2.
1.

Maintain a candidate and a count.

2.
3.

If count == 0, update candidate to the current element.

4.
5.

If the current element matches candidate, increase count;


otherwise, decrease it.

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3.

Step 2 (Verify Candidate):

4.

1.

Count occurrences of candidate and check if it's > N/2.

2.

3.

Time Complexity: O(N) (Two passes: one for candidate selection, one for
verification).

4.
5.

Space Complexity: O(1) (Uses only a few variables).

8.

PROBLEM:43
Question: Kadane's Algorithm, maximum subarray sum

Write a C++ program to find the maximum sum of a contiguous subarray using
Kadane's Algorithm. The program should take an array as input and return the
maximum subarray sum. If all elements are negative, it should return the least
negative number.

C++ Code (Using Kadane’s Algorithm - Optimal Approach)

cpp

CopyEdit

#include <iostream>#include <climits>using namespace std;

// Function to find the maximum subarray sum using Kadane's Algorithmint


maxSubarraySum(int arr[], int n) {

int maxSum = INT_MIN, currentSum = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


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

currentSum += arr[i]; // Add the current element to the running sum

// Update maxSum if the current sum is greater

maxSum = max(maxSum, currentSum);

// If current sum becomes negative, reset it to 0

if (currentSum < 0) {

currentSum = 0;

return maxSum;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Finding and displaying the maximum subarray sum

int maxSum = maxSubarraySum(arr, N);

cout << "The maximum subarray sum is: " << maxSum << endl;

return 0;

Explanation:

1.

Algorithm (Kadane’s Algorithm - O(N)):

2.
1.

Maintain two variables:

2.
1.

currentSum → Keeps track of the sum of the current subarray.

2.
3.

maxSum → Stores the maximum sum found so far.

4.
3.

Iterate through the array:

4.

1.

Add each element to currentSum.

2.
3.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Update maxSum if currentSum is greater.

4.
5.

If currentSum becomes negative, reset it to 0 (start a new


subarray).

6.

3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (Uses only a few variables).

6.

PROBLEM:44
Question: Print subarray with maximum subarray sum (extended version of above problem)

Write a C++ program to find the maximum sum of a contiguous subarray using
Kadane's Algorithm and also print the subarray. The program should take an
array as input and return both the maximum subarray sum and the subarray
itself.

C++ Code (Kadane’s Algorithm - Extended Version)

cpp

CopyEdit

#include <iostream>#include <climits>using namespace std;

// Function to find the maximum subarray sum and print the subarrayvoid
maxSubarraySumWithIndices(int arr[], int n) {

int maxSum = INT_MIN, currentSum = 0;

int start = 0, end = 0, tempStart = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


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

currentSum += arr[i];

if (currentSum > maxSum) {

maxSum = currentSum;

start = tempStart;

end = i;

if (currentSum < 0) {

currentSum = 0;

tempStart = i + 1;

// Output the results

cout << "The maximum subarray sum is: " << maxSum << endl;

cout << "The subarray with the maximum sum is: ";

for (int i = start; i <= end; i++)

cout << arr[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying the maximum subarray sum and subarray

maxSubarraySumWithIndices(arr, N);

return 0;

Explanation:

1.

Algorithm (Kadane’s Algorithm - O(N)):

2.
1.

Maintain currentSum, maxSum, and indices (start, end) to track the


subarray.

2.
3.

If currentSum > maxSum, update maxSum and save indices.

4.
5.

If currentSum < 0, reset it and move the temporary start index to i+1.

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3.

Time Complexity: O(N) (Single pass through the array).

4.
5.

Space Complexity: O(1) (Only a few variables used).

6.

PROBLEM:45
Question: Stock Buy and Sell

Write a C++ program to find the maximum profit from buying and selling a
stock once. The program should take an array of stock prices (where prices[i]
represents the stock price on day i) as input and return the maximum profit
possible. If no profit can be made, return 0.

C++ Code (Optimal Solution - O(N))

cpp

CopyEdit

#include <iostream>#include <climits>using namespace std;

// Function to find the maximum profit from buying and selling a stockint maxProfit(int prices[],
int n) {

int minPrice = INT_MAX; // Minimum price to buy the stock

int maxProfit = 0; // Maximum profit achievable

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

if (prices[i] < minPrice) {

minPrice = prices[i]; // Update the minimum price

} else {

maxProfit = max(maxProfit, prices[i] - minPrice); // Calculate profit

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return maxProfit;

int main() {

int N;

// Taking input for number of days

cout << "Enter the number of days: ";

cin >> N;

int prices[N];

// Taking input for stock prices

cout << "Enter " << N << " stock prices: ";

for (int i = 0; i < N; i++)

cin >> prices[i];

// Finding and displaying the maximum profit

int profit = maxProfit(prices, N);

cout << "The maximum profit is: " << profit << endl;

return 0;

Explanation:

1.

Algorithm (O(N) - Single Pass):

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2.
1.

Keep track of the minimum stock price (minPrice).

2.
3.

At each step, calculate the profit if the stock was sold on that day
(prices[i] - minPrice).

4.
5.

Update maxProfit if a higher profit is found.

6.
3.

Time Complexity: O(N) (Traverses the array once).

4.
5.

Space Complexity: O(1) (Uses only a few variables).

6.

7.

PROBLEM:46

Question: Rearrange the array in alternating positive and


negative items

Write a C++ program to rearrange an array such that positive and negative
numbers appear in alternating positions. If extra positive or negative numbers
remain, they should be placed at the end while maintaining their relative order.

C++ Code (Rearrange Array Alternately - O(N))

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


CopyEdit

#include <iostream>#include <vector>using namespace std;

// Function to rearrange the array in alternating positive and negative ordervoid


rearrangeArray(int arr[], int n) {

vector<int> pos, neg;

// Separate positive and negative numbers

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

if (arr[i] >= 0)

pos.push_back(arr[i]);

else

neg.push_back(arr[i]);

// Merge them in alternating fashion

int i = 0, j = 0, k = 0;

while (i < pos.size() && j < neg.size()) {

arr[k++] = pos[i++];

arr[k++] = neg[j++];

// Add remaining positive numbers

while (i < pos.size())

arr[k++] = pos[i++];

// Add remaining negative numbers

while (j < neg.size())

arr[k++] = neg[j++];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers (positive and negative): ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Rearranging and displaying the array

rearrangeArray(arr, N);

cout << "Rearranged array: ";

for (int i = 0; i < N; i++)

cout << arr[i] << " ";

cout << endl;

return 0;

Explanation:

1.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Algorithm (Two-Pass Approach - O(N)):

2.
1.

Step 1: Separate positive and negative numbers into two vectors.

2.
3.

Step 2: Merge them alternately into the original array.

4.
5.

Step 3: If any extra elements remain, append them at the end.

6.
3.

Time Complexity: O(N) (Single pass for separation + Single pass for
merging).

4.
5.

Space Complexity: O(N) (Uses extra vectors for separation).

6.

PROBLEM:47
Question: Next Permutation

Write a C++ program to find the next lexicographically greater permutation of


an array of numbers. If no such permutation exists (i.e., the array is in
descending order), the function should return the smallest permutation (sorted
in ascending order).

C++ Code (Using STL - Optimal Approach in O(N))

cpp

CopyEdit

#include <iostream>#include <vector>#include <algorithm>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to find the next permutation of the arrayvoid nextPermutation(vector<int>& arr) {

int n = arr.size();

int i = n - 2;

// Step 1: Find the first decreasing element from the right

while (i >= 0 && arr[i] >= arr[i + 1])

i--;

if (i >= 0) {

// Step 2: Find the next greater element than arr[i] from the right

int j = n - 1;

while (arr[j] <= arr[i])

j--;

swap(arr[i], arr[j]); // Swap the elements

// Step 3: Reverse the elements after index i to get the next permutation

reverse(arr.begin() + i + 1, arr.end());

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

vector<int> arr(N);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying the next permutation

nextPermutation(arr);

cout << "Next permutation: ";

for (int num : arr)

cout << num << " ";

cout << endl;

return 0;

Explanation:

1.

Algorithm (O(N)):

2.
1.

Step 1: Find the first decreasing element from the right (arr[i]).

2.
3.

Step 2: Find the smallest number (arr[j]) greater than arr[i] on the
right, then swap them.

4.
5.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Step 3: Reverse the elements after i to get the next permutation.

6.
7.

If the array is in descending order, it gets reversed to the smallest


permutation.

8.
3.

Time Complexity: O(N) (Finding i + finding j + reversing).

4.
5.

Space Complexity: O(1) (No extra space used).

6.

PROBLEM:48
Question: Leaders in an Array problem

Write a C++ program to find all the "leaders" in an array.


A leader is an element that is greater than or equal to all the elements to its right
in the array. The rightmost element is always a leader.

C++ Code (Optimal Solution - O(N))

cpp

CopyEdit

#include <iostream>#include <vector>using namespace std;

// Function to find and print all leaders in an arrayvoid findLeaders(int arr[], int n) {

vector<int> leaders;

int maxRight = arr[n - 1]; // The last element is always a leader

leaders.push_back(maxRight);

// Traverse from right to left

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = n - 2; i >= 0; i--) {

if (arr[i] >= maxRight) { // Found a new leader

maxRight = arr[i];

leaders.push_back(maxRight);

// Printing leaders in the correct order

cout << "Leaders in the array: ";

for (int i = leaders.size() - 1; i >= 0; i--)

cout << leaders[i] << " ";

cout << endl;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying leaders in the array

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


findLeaders(arr, N);

return 0;

Explanation:

1.

Algorithm (O(N), Single Pass from Right to Left):

2.
1.

Start from the rightmost element (which is always a leader).

2.
3.

Keep track of the maximum element (maxRight) seen so far.

4.
5.

If the current element is greater than or equal to maxRight, it is a


leader.

6.
7.

Store the leaders and print them in the correct order.

8.
3.

Time Complexity: O(N) (Single pass from right to left).

4.
5.

Space Complexity: O(N) (For storing leaders, can be reduced to O(1) if


printed directly).

6.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:49
Question: Longest Consecutive Sequence in an Array

Write a C++ program to find the length of the longest consecutive sequence in
an unsorted array.
A consecutive sequence means numbers appear in order (but not necessarily
adjacent in the array). The solution should run in O(N) time complexity.

C++ Code (Optimal Solution - O(N) Using Hashing)

cpp

CopyEdit

#include <iostream>#include <unordered_set>using namespace std;

// Function to find the length of the longest consecutive sequenceint longestConsecutive(int arr[],
int n) {

unordered_set<int> nums(arr, arr + n); // Store all elements in a hash set

int maxLength = 0;

// Iterate over the array

for (int num : nums) {

// Start a sequence only if it's the first element (num-1 doesn't exist)

if (nums.find(num - 1) == nums.end()) {

int currentNum = num;

int currentLength = 1;

// Count consecutive numbers

while (nums.find(currentNum + 1) != nums.end()) {

currentNum++;

currentLength++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


maxLength = max(maxLength, currentLength); // Update max length

return maxLength;

int main() {

int N;

// Taking input for array size

cout << "Enter the size of the array: ";

cin >> N;

int arr[N];

// Taking input for array elements

cout << "Enter " << N << " integers: ";

for (int i = 0; i < N; i++)

cin >> arr[i];

// Finding and displaying the longest consecutive sequence length

int maxSeq = longestConsecutive(arr, N);

cout << "Length of the longest consecutive sequence: " << maxSeq << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Explanation:

1.

Algorithm (O(N) Using Hashing - Efficient Approach):

2.
1.

Store all elements in an unordered_set for fast lookup.

2.
3.

Traverse the array and check only the start of sequences (num-1
should not exist).

4.
5.

Count consecutive numbers using a while loop.

6.
7.

Keep track of the maximum sequence length.

8.
3.

Time Complexity: O(N) (Each element is processed once).

4.
5.

Space Complexity: O(N) (Used hash set to store elements).

6.

PROBLEM:50
Question: Set Matrix Zeros

Write a C++ program to modify a given matrix such that if any element is 0, the
entire row and column containing that 0 should also be set to 0.
The solution should aim for O(1) extra space complexity (modifying in-place).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code (Optimized In-Place Solution - O(N*M))

cpp

CopyEdit

#include <iostream>#include <vector>using namespace std;

// Function to set entire row and column to zero if an element is zerovoid


setMatrixZeros(vector<vector<int>>& matrix) {

int rows = matrix.size();

int cols = matrix[0].size();

bool firstRowZero = false, firstColZero = false;

// Step 1: Check if first row or first column needs to be zeroed

for (int i = 0; i < rows; i++)

if (matrix[i][0] == 0) firstColZero = true;

for (int j = 0; j < cols; j++)

if (matrix[0][j] == 0) firstRowZero = true;

// Step 2: Use first row and column as markers for zeroing

for (int i = 1; i < rows; i++) {

for (int j = 1; j < cols; j++) {

if (matrix[i][j] == 0) {

matrix[i][0] = 0; // Mark the row

matrix[0][j] = 0; // Mark the column

// Step 3: Zero out marked rows and columns

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = 1; i < rows; i++) {

if (matrix[i][0] == 0) {

for (int j = 1; j < cols; j++)

matrix[i][j] = 0;

for (int j = 1; j < cols; j++) {

if (matrix[0][j] == 0) {

for (int i = 1; i < rows; i++)

matrix[i][j] = 0;

// Step 4: Zero out first row/column if needed

if (firstColZero) {

for (int i = 0; i < rows; i++) matrix[i][0] = 0;

if (firstRowZero) {

for (int j = 0; j < cols; j++) matrix[0][j] = 0;

// Function to display the matrixvoid printMatrix(vector<vector<int>>& matrix) {

for (auto row : matrix) {

for (auto num : row) {

cout << num << " ";

cout << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

int rows, cols;

// Taking input for matrix size

cout << "Enter number of rows and columns: ";

cin >> rows >> cols;

vector<vector<int>> matrix(rows, vector<int>(cols));

// Taking input for matrix elements

cout << "Enter the matrix elements: \n";

for (int i = 0; i < rows; i++)

for (int j = 0; j < cols; j++)

cin >> matrix[i][j];

// Modifying the matrix

setMatrixZeros(matrix);

// Displaying the modified matrix

cout << "Modified matrix:\n";

printMatrix(matrix);

return 0;

Explanation:

1.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Algorithm (O(N*M) Time, O(1) Extra Space):

2.
1.

Step 1: Check if the first row/column needs to be zeroed.

2.
3.

Step 2: Use the first row & column as markers for zeros.

4.
5.

Step 3: Modify the matrix using these markers.

6.
7.

Step 4: Finally, zero out the first row/column if needed.

8.
3.

Time Complexity: O(N*M) (Every element is visited once).

4.
5.

Space Complexity: O(1) (Modified in-place, no extra space used).

6.

Congratulations on completing the PDF created by SYNTAX ERROR, also known as


Abhishek Rathor!
Your dedication and perseverance are truly commendable. For more insights and
updates, feel free
to connect on Instagram at SYNTAX ERROR. Keep up the great work!

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

You might also like