Show 25 50 100
PDF
30 result(s) in Problem Solving Clear

Index

Showing 30 topics
  1. Largest of Three Numbers
  2. Sum of 1 to N
  3. Swap Two Numbers
  4. Prime Number
  5. GCD / HCF
  6. LCM
  7. Armstrong Number
  8. Perfect Number
  9. Anagram Check
  10. Even or Odd
  11. Leap Year
  12. Factorial
  13. Fibonacci Series
  14. Reverse a Number
  15. Palindrome Number
  16. Reverse a String
  17. Count Vowels
  18. Sum of Digits
  19. Decimal to Binary
  20. Second Largest Element
  21. Remove Duplicates from Array
  22. Length of an Array
  23. Length (count digits) of a number
  24. Power (x^n)
  25. Largest & Smallest Digit of a Number
  26. Bit Manipulation (common)
  27. Palindrome String
  28. Largest & Smallest Element of an Array
  29. Reverse an Array
  30. Missing Number (1 to N)
1 Index
Solution 1: if - else if C++ 6 lines
if(a >= b && a >= c)
    cout << a;
else if(b >= a && b >= c)
    cout << b;
else
    cout << c;
Solution 2: Nested max() C++ 1 line
cout << max(a, max(b, c));
Solution 3: max() with initializer list (shortest) C++ 1 line
cout << max({a, b, c});

Note: max() needs #include <algorithm>.

2 Index

Formula: (n * (n + 1)) / 2

Solution 1: Formula O(1) [BEST] C++ 2 lines
int n = 100;
cout << (n * (n + 1)) / 2; // 5050

Note: If N is big, use long long (n * (n + 1) can overflow int).

C++ 2 lines
long long n = 100000;
cout << (n * (n + 1)) / 2; // 5000050000
Solution 2: Loop O(n) C++ 4 lines
int n = 100, sum = 0;
for(int i = 1; i <= n; i++)
    sum += i;
cout << sum;
Solution 3: Recursion ★★★ C++ 4 lines
int sum(int n){
    if(n == 0) return 0;
    return n + sum(n - 1);
}
3 Index

Viva te 'swap without 3rd variable' khub jigges kore. Real code e std::swap use korbe.

Solution 1: Using 3rd variable C++ 4 lines
int a = 10, b = 20;
int temp = b;
b = a;
a = temp;
Solution 2: Without 3rd variable (+ / -) C++ 3 lines
a = a + b;
b = a - b;
a = a - b;
Solution 3: Without 3rd variable (XOR) C++ 3 lines
a = a ^ b;
b = a ^ b;
a = a ^ b;
Solution 4: std::swap (best in practice) C++ 2 lines
int a = 10, b = 20;
swap(a, b);

Note: swap() needs #include <utility> and #include <algorithm>.

4 Index

Note:

0 and 1 are not prime numbers.

2 is the smallest prime number.

A prime number is a number that can be divided only by 1 and itself.

Solution 1: Basic O(n) C++ 7 lines
bool isPrime(int n){
    if(n < 2) return false;
    for(int i = 2; i < n; i++){
        if(n % i == 0) return false;
    }
    return true;
}
Solution 2: Optimized O(sqrt n) ★★★★★ C++ 34 lines
#include <iostream>
using namespace std;

int main() {
    int n = 5;
    bool prime = true;
    if (n < 2)
        prime = false;

    // i*i means i × i.
    // We check only up to √n.
    // Example: n = 5
    // i = 2 → 2×2 = 4 <= 5 → check 5 % 2
    // i = 3 → 3×3 = 9 > 5 → stop
    //
    // We don't need to check after √n,
    // because the factors after √n are already covered.
    //
    // Advantage: Fewer checks and faster execution.
    // Time Complexity: O(√n)
    // Space Complexity: O(1)
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            prime = false;
            break;
        }
    }

    if (prime)
        cout << "Prime";
    else
        cout << "Not Prime";
    return 0;
}
5 Index

Note:

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two or more numbers is the largest number that divides all of them exactly (with no remainder).

It is found using the Euclidean Algorithm, which is very important for interviews.

Solution 1: Euclidean Algorithm (loop) C++ 7 lines
int a = 12, b = 18;
while(b != 0){
    int temp = b;
    b = a % b;
    a = temp;
}
cout << a; // 6
Solution 2: Recursive C++ 4 lines
int gcd(int a, int b){
    if(b == 0) return a;
    return gcd(b, a % b);
}
Solution 3: Built-in (C++17 std::gcd / __gcd) C++ 2 lines
cout << gcd(12, 18);   // <numeric>, C++17
cout << __gcd(12, 18);

Note: gcd() needs #include <numeric>.

Solution 4: GCD of multiple numbers ★★★★★ C++ 18 lines
int gcd(int a, int b){
    while(b != 0){
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main(){
    int arr[] = {12, 18, 24, 30, 36};
    int len = sizeof(arr) / sizeof(arr[0]);
    int result = arr[0];
    for(int i = 1; i < len; i++){
        result = gcd(result, arr[i]);
    }
    cout << result; // 6
}
6 Index

Note:

LCM (Least Common Multiple) is the smallest number that is a multiple of both numbers.

Example: LCM of 12 and 18 is 36.

Formula: LCM(a, b) = (a × b) / GCD(a, b)

Solution 1: Two numbers (using GCD) C++ 14 lines
int lcm(int a, int b){
    int x = a, y = b;
    while(y != 0){
        int temp = y;
        y = x % y;
        x = temp;
    }
    int gcd = x;
    return (a / gcd) * b;
}

int main(){
    cout << lcm(12, 18); // 36
}
Solution 2: Multiple numbers C++ 22 lines
int gcd(int a, int b){
    while(b != 0){
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int lcm(int a, int b){
    return (a / gcd(a, b)) * b;
}

int main(){
    int arr[] = {5, 10, 15, 30};
    int len = sizeof(arr) / sizeof(arr[0]);
    int result = arr[0];
    for(int i = 1; i < len; i++){
        result = lcm(result, arr[i]);
    }
    cout << "LCM " << result; // 30
}
7 Index

Note:

Let number = abcd and total digits = n.

If aⁿ + bⁿ + cⁿ + dⁿ = original number, then it is an Armstrong number.

Example 1: 153 → 1³ + 5³ + 3³ = 1 + 125 + 27 = 153

Example 2: 1634 → 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634

Solution 1: Manual power (safe, no double) C++ 19 lines
int main() {
    int n = 1634;
    int len = to_string(n).length();
    int temp = n;
    int sum = 0;

    while(temp != 0){
        int digit = temp % 10;
        int power = 1;
        for(int i = 0; i < len; i++){
            power = power * digit;
        }
        sum = sum + power;
        temp = temp / 10;
    }

    if(sum == n) cout << "Armstrong";
    else cout << "Not Armstrong";
}
Solution 2: Using pow() (round is needed) C++ 2 lines
int digit = temp % 10;
sum += (int)round(pow(digit, len));

Note: pow() returns a double, so a direct int cast can give a wrong answer (for example 124.99999 becomes 124). Use round() to be safe.

8 Index

Definition:

A perfect number is a number whose sum of all divisors (excluding the number itself) is equal to the number.

Example: 6 = 1 + 2 + 3

C++ 6 lines
int n = 28, sum = 0;
for(int i = 1; i <= n / 2; i++){
    if(n % i == 0) sum += i;
}
if(sum == n) cout << "Perfect";
else cout << "Not Perfect";
9 Index

Definition:

Two strings are anagrams if they have the same characters (same count) but in a different order.

Example: listen / silent

Solution 1: Sorting O(n log n) C++ 4 lines
string a = "listen", b = "silent";
sort(a.begin(), a.end());
sort(b.begin(), b.end());
cout << (a == b ? "Anagram" : "Not Anagram");

Note: sort() needs #include <algorithm>.

10 Index

A number is even if it is divisible by 2 (n % 2 == 0), otherwise it is odd.

Solution 1: Modulus C++ 3 lines
int n = 7;
if(n % 2 == 0) cout << "Even";
else cout << "Odd";
Solution 2: Bitwise AND (faster) C++ 3 lines
// The last bit of an odd number is always 1
if(n & 1) cout << "Odd";
else cout << "Even";
11 Index

Rule: a year is a leap year if it is divisible by 400, or divisible by 4 but not by 100.

Example: 2000 and 2024 are leap years; 1900 is not.

C++ 5 lines
int y = 2024;
if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
    cout << "Leap Year";
else
    cout << "Not Leap Year";
12 Index

Formula: n! = n × (n-1) × ... × 1, and 0! = 1.

Example: 5! = 120

Solution 1: Loop O(n) C++ 5 lines
int n = 5;
long long fact = 1;
for(int i = 1; i <= n; i++)
    fact *= i;
cout << fact; // 120
Solution 2: Recursion C++ 4 lines
long long fact(int n){
    if(n <= 1) return 1;
    return n * fact(n - 1);
}

Note: 20! is the largest factorial that fits in long long.

13 Index

Each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13 ...

Formula: F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1

Solution 1: Loop O(n) C++ 8 lines
int n = 10, a = 0, b = 1;
for(int i = 0; i < n; i++){
    cout << a << " ";
    int next = a + b;
    a = b;
    b = next;
}
// 0 1 1 2 3 5 8 13 21 34
Solution 2: Recursion O(2^n) (slow, viva only) C++ 4 lines
int fib(int n){
    if(n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}
Solution 3: Memoization O(n) C++ 6 lines
long long memo[100];
long long fib(int n){
    if(n <= 1) return n;
    if(memo[n]) return memo[n];
    return memo[n] = fib(n - 1) + fib(n - 2);
}

Q & A

  1. Why is plain recursive Fibonacci slow?
    The same values are computed again and again, so the calls grow like 2^n. Memoization stores each answer once and makes it O(n).
14 Index

Take the last digit with % 10, add it to the result, then drop it with / 10.

C++ 7 lines
int n = 1234, rev = 0;
while(n != 0){
    int digit = n % 10;
    rev = rev * 10 + digit;
    n /= 10;
}
cout << rev; // 4321
15 Index

A number is a palindrome if it reads the same backwards. Example: 121, 1331

Solution 1: Reverse and compare C++ 6 lines
int n = 121, temp = n, rev = 0;
while(temp != 0){
    rev = rev * 10 + temp % 10;
    temp /= 10;
}
cout << (rev == n ? "Palindrome" : "Not Palindrome");
Solution 2: Palindrome string (two pointers) C++ 5 lines
string s = "madam";
bool ok = true;
for(int i = 0, j = s.size() - 1; i < j; i++, j--)
    if(s[i] != s[j]) { ok = false; break; }
cout << (ok ? "Palindrome" : "Not Palindrome");
16 Index
Solution 1: std::reverse C++ 3 lines
string s = "hello";
reverse(s.begin(), s.end());
cout << s; // olleh
Solution 2: Two pointers C++ 6 lines
string s = "hello";
int i = 0, j = s.size() - 1;
while(i < j){
    swap(s[i], s[j]);
    i++; j--;
}

Note: reverse() needs #include <algorithm>.

17 Index
C++ 8 lines
string s = "Programming";
int count = 0;
for(char c : s){
    c = tolower(c);
    if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
        count++;
}
cout << count; // 3
19 Index

Divide by 2 repeatedly and read the remainders from bottom to top. Example: 13 = 1101

Solution 1: Repeated division C++ 7 lines
int n = 13;
string bin = "";
while(n > 0){
    bin = char('0' + n % 2) + bin;
    n /= 2;
}
cout << bin; // 1101
Solution 2: bitset C++ 2 lines
#include <bitset>
cout << bitset<8>(13); // 00001101
Binary to Decimal C++ 5 lines
string b = "1101";
int dec = 0;
for(char c : b)
    dec = dec * 2 + (c - '0');
cout << dec; // 13
20 Index
Single pass O(n) C++ 11 lines
int arr[] = {12, 35, 1, 10, 34, 1};
int first = INT_MIN, second = INT_MIN;
for(int x : arr){
    if(x > first){
        second = first;
        first = x;
    } else if(x > second && x != first){
        second = x;
    }
}
cout << second; // 34
21 Index
Solution 1: sort + unique C++ 4 lines
vector<int> v = {1, 2, 2, 3, 4, 4, 5};
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
// 1 2 3 4 5
Solution 2: set C++ 1 line
set<int> s(v.begin(), v.end()); // keeps one of each, sorted
23 Index
Problem Count the digits of a number (1234 -> 4).

A do-while loop is used so that the number 0 is counted as 1 digit.

Solution 1: do-while loop C++ 9 lines
int main() {
    int num = 1234;
    int len = 0;
    do{
        num = num / 10;
        len++;
    }while(num != 0);
    cout << len;   // 4
}
Solution 2: String method C++ 3 lines
int num = 1234;
int len = to_string(num).length();
cout << len;
24 Index
Problem Calculate x raised to the power n.
Solution 1: Loop O(n) C++ 7 lines
int x = 2, n = 5;
long long result = 1;
for(int i = 0; i < n; i++){
    result = result * x;
}
cout << result;   // 32
// STL: cout << pow(2, 5);
25 Index
Problem Find the largest and the smallest digit of a number.
Largest digit C++ 8 lines
int num = 234515;
int lrg = 0;
do{
    int digit = num % 10;
    if(digit > lrg) lrg = digit;
    num = num / 10;
}while(num != 0);
cout << lrg;   // 5
Smallest digit C++ 8 lines
int num = 234515;
int small = 9;
do{
    int digit = num % 10;
    if(digit < small) small = digit;
    num = num / 10;
}while(num != 0);
cout << small;   // 1
26 Index
Problem Power of 2 check and counting set bits.
Power of 2 check C++ 3 lines
bool isPow2(int n){
    return n > 0 && (n & (n - 1)) == 0;
}
Count set bits C++ 6 lines
int n = 13, count = 0;
while(n){
    count += n & 1;
    n >>= 1;
}
// or: __builtin_popcount(13)
27 Index
Problem Check whether a string is a palindrome (madam).
Solution 1: Two pointer (O(1) space) C++ 8 lines
string s = "madam";
int l = 0, r = s.length() - 1;
bool ok = true;
while(l < r){
    if(s[l] != s[r]){ ok = false; break; }
    l++; r--;
}
cout << (ok ? "Palindrome" : "Not Palindrome");
Solution 2: Reverse & compare C++ 4 lines
string s = "madam";
string r = s;
reverse(r.begin(), r.end());
cout << (s == r ? "Palindrome" : "Not Palindrome");
28 Index
Problem Find the largest and the smallest element of an array.
Solution 1: Single loop (interview best) C++ 10 lines
int arr[] = {10, 2, 4, 2, 10, 1};
int len = sizeof(arr) / sizeof(arr[0]);

int lrg = arr[0];
int small = arr[0];
for(int i = 1; i < len; i++){
    if(arr[i] > lrg) lrg = arr[i];
    if(arr[i] < small) small = arr[i];
}
cout << lrg << " " << small;   // 10 1
29 Index
Problem Reverse the elements of an array.
Solution 1: Two pointer [BEST] C++ 8 lines
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int l = 0, r = n - 1;
while(l < r){
    swap(arr[l], arr[r]);
    l++; r--;
}
for(int i = 0; i < n; i++) cout << arr[i] << " ";
Solution 2: STL reverse C++ 1 line
reverse(arr, arr + n);
30 Index
Problem Find the missing number in an array containing numbers from 1 to N.
Solution 1: Sum formula [BEST] C++ 6 lines
int arr[] = {1, 2, 4, 5, 6};
int n = 6;   // range 1..6
int expected = n * (n + 1) / 2;
int actual = 0;
for(int i = 0; i < 5; i++) actual += arr[i];
cout << expected - actual;   // 3