Section 1: Basic Arithmetic
These questions focus on digit manipulation and basic operators.
Odd or Even
What You'll Learn
How to use the modulo operator to check for divisibility.
Real-World Context
"Think of sharing a bag of candies between two people. If there's one left over, it's odd. If not, it's even!"
Breaking It Down
- Take the input number
- Divide it by 2 and check the remainder
- If remainder is 0, it's Even
- Otherwise, it's Odd
def is_even(n):
if n % 2 == 0:
return "Even"
else:
return "Odd"Line-by-Line Walkthrough
We use the % (modulo) operator which gives us the remainder of a division. Any number divisible by 2 with no remainder is even.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- A single mathematical operation regardless of number size.
Common Mistakes
- ❌ Using division (/) instead of modulo (%)
✅ Modulo gives the remainder, which is what we need.
Try It Yourself
Can you check if a number is divisible by 3 without using the modulo operator?
Swap Numbers
What You'll Learn
How to swap two values without using a temporary third variable.
Real-World Context
"Imagine you have a glass of juice and a glass of milk. How do you swap them if you don't have a third glass? (Hint: It involves some math magic!)"
Breaking It Down
- Add both numbers and store in the first variable
- Subtract the second from the new first to get the original first value
- Subtract the new second from the new first to get the original second value
def swap(a, b):
a = a + b
b = a - b
a = a - b
return a, bLine-by-Line Walkthrough
By adding the two numbers, we store their combined 'weight' in one variable. We then use subtraction to peel off the original values one by one.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- Three simple arithmetic operations.
Common Mistakes
- ❌ Potential integer overflow in languages like C++
✅ Use XOR bitwise operator for a safer swap.
Try It Yourself
Try swapping two numbers using the XOR (^) operator.
Sum of Digits
What You'll Learn
How to extract individual digits from a number using loops.
Real-World Context
"Like counting the total value of coins in your pocket by looking at each coin one by one."
Breaking It Down
- Initialize sum to 0
- Use a loop while the number is greater than 0
- Get the last digit using modulo 10
- Add it to sum
- Remove the last digit using integer division by 10
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return totalLine-by-Line Walkthrough
The modulo 10 trick always gives you the last digit. Dividing by 10 'shifts' the number to the right, effectively removing that last digit.
Complexity Analysis
- Time: O(log N)
- Space: O(1)
- The number of iterations depends on the number of digits, which is log10(N).
Common Mistakes
- ❌ Forgetting to update the number (n /= 10)
✅ This leads to an infinite loop!
Try It Yourself
Can you solve this using recursion instead of a while loop?
Reverse Digits
What You'll Learn
Building a new number by shifting digits.
Real-World Context
"Turning 123 into 321. It's like taking a stack of plates and moving them one by one to a new stack."
Breaking It Down
- Initialize reversed_num to 0
- Extract the last digit of the input
- Multiply reversed_num by 10 and add the extracted digit
- Remove the last digit from input
- Repeat until input is 0
def reverse_number(n):
rev = 0
while n > 0:
rev = rev * 10 + (n % 10)
n //= 10
return revLine-by-Line Walkthrough
Each time we add a digit to 'rev', we multiply the existing 'rev' by 10 to make room for the new digit in the ones place.
Complexity Analysis
- Time: O(log N)
- Space: O(1)
- We process each digit once.
Common Mistakes
- ❌ Not handling negative numbers
✅ Store the sign, work with absolute value, then re-apply sign.
Try It Yourself
What happens if the reversed number exceeds the maximum integer limit (overflow)?
Palindrome Number
What You'll Learn
Combining reversal logic with comparison.
Real-World Context
"A number that reads the same forwards and backwards, like 121 or 1331. Like the word 'level' but for numbers!"
Breaking It Down
- Store the original number in a temporary variable
- Reverse the number using the 'Reverse Digits' logic
- Compare the reversed number with the original
- If they are equal, it's a palindrome
def is_palindrome(n):
if n < 0: return False
original = n
rev = 0
while n > 0:
rev = rev * 10 + (n % 10)
n //= 10
return original == revLine-by-Line Walkthrough
We reuse the reversal logic. If the flipped version is identical to the start, it's a palindrome. Note: Negative numbers are never palindromes because of the '-' sign.
Complexity Analysis
- Time: O(log N)
- Space: O(1)
- We iterate through the digits once.
Common Mistakes
- ❌ Comparing the modified 'n' (which becomes 0) instead of the original
✅ Always store the original value in a separate variable first.
Try It Yourself
Can you check if a number is a palindrome without reversing the whole number? (Hint: Reverse only half!)
Section 2: Mathematical Checks
Moving into logic that requires understanding number properties.
Armstrong Number
What You'll Learn
Power operations and digit extraction.
Real-World Context
"An Armstrong number (like 153) is a number that is the sum of its own digits each raised to the power of the number of digits. It's like a number that is 'self-made'!"
Breaking It Down
- Count the number of digits (k)
- Extract each digit
- Raise each digit to the power of k and add to sum
- Check if sum equals original number
def is_armstrong(n):
num_str = str(n)
k = len(num_str)
total = sum(int(digit)**k for digit in num_str)
return total == nLine-by-Line Walkthrough
We first find how many digits the number has. Then, we take each digit, raise it to that power, and see if the total matches the start.
Complexity Analysis
- Time: O(log N)
- Space: O(1)
- We process each digit twice (once to count, once to sum).
Common Mistakes
- ❌ Hardcoding the power to 3
✅ Armstrong numbers can have any number of digits; the power must match the digit count.
Try It Yourself
Find all Armstrong numbers between 1 and 1000.
Prime Number
What You'll Learn
Efficient looping and divisibility rules.
Real-World Context
"A prime number is like a 'loner' - it only hangs out with itself and 1. Examples: 2, 3, 5, 7, 11."
Breaking It Down
- If number <= 1, it's not prime
- Loop from 2 up to the square root of the number
- If any number divides it evenly, it's not prime
- If the loop finishes, it is prime
import math
def is_prime(n):
if n <= 1: return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return TrueLine-by-Line Walkthrough
We only need to check up to the square root because if a number has a factor larger than its square root, it must also have one smaller than it.
Complexity Analysis
- Time: O(√N)
- Space: O(1)
- The loop runs at most square root of N times.
Common Mistakes
- ❌ Checking all the way up to N
✅ Checking up to √N is much faster and mathematically sufficient.
Try It Yourself
Can you optimize this further by skipping even numbers after checking 2?
Section 3: Sequences & Recursion
Learning how functions can call themselves or repeat patterns.
Factorial
What You'll Learn
Iterative vs Recursive approaches.
Real-World Context
"Factorial (5!) is 5 × 4 × 3 × 2 × 1. It's like calculating the number of ways you can arrange books on a shelf."
Breaking It Down
- Base case: factorial of 0 or 1 is 1
- Recursive: n * factorial(n-1)
- Iterative: Multiply numbers from 1 to n
# Iterative
def factorial_iter(n):
res = 1
for i in range(2, n + 1):
res *= i
return res
# Recursive
def factorial_rec(n):
if n <= 1: return 1
return n * factorial_rec(n - 1)Line-by-Line Walkthrough
The iterative version uses a loop to accumulate the product. The recursive version breaks the problem down into smaller versions of itself until it hits 1.
Complexity Analysis
- Time: O(N)
- Space: O(1) for iterative, O(N) for recursive
- Recursive uses stack space for each call.
Common Mistakes
- ❌ Not handling the base case (0! = 1)
✅ Always define what happens at the smallest possible input.
Try It Yourself
Which version would you use for a very large N? Why?
Fibonacci
What You'll Learn
Generating a sequence where each number is the sum of the two preceding ones.
Real-World Context
"0, 1, 1, 2, 3, 5, 8... This pattern appears everywhere in nature, from sunflower seeds to snail shells!"
Breaking It Down
- Start with 0 and 1
- Next number = sum of previous two
- Update previous two numbers
- Repeat for N terms
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + bLine-by-Line Walkthrough
We keep track of the last two numbers. In each step, we calculate the next one and 'slide' our window forward.
Complexity Analysis
- Time: O(N)
- Space: O(1)
- We only store two variables regardless of N.
Common Mistakes
- ❌ Using simple recursion without memoization
✅ Simple recursion for Fibonacci is O(2^N), which is extremely slow. Use iteration or memoization.
Try It Yourself
Can you find the Nth Fibonacci number using the Golden Ratio formula (Binet's Formula)?
Section 4: Advanced Math
Using algorithms like Euclidean for GCD and handling multiple inputs.
GCD and LCM
What You'll Learn
The Euclidean Algorithm for finding the Greatest Common Divisor.
Real-World Context
"GCD is the largest number that divides both. LCM is the smallest number they both divide into. Like finding the common denominator for fractions!"
Breaking It Down
- GCD: While b is not 0, a, b = b, a % b
- LCM: (a * b) / GCD(a, b)
def get_gcd(a, b):
while b:
a, b = b, a % b
return a
def get_lcm(a, b):
return abs(a * b) // get_gcd(a, b)Line-by-Line Walkthrough
The Euclidean algorithm is a very efficient way to find GCD by repeatedly taking the remainder. LCM is then easily found using the relationship between GCD and LCM.
Complexity Analysis
- Time: O(log(min(a, b)))
- Space: O(1)
- The numbers decrease exponentially in the Euclidean algorithm.
Common Mistakes
- ❌ Calculating LCM first and then GCD
✅ Always find GCD first to avoid large number overflows when multiplying a * b.
Try It Yourself
Can you find the GCD of three numbers?
Binary to Decimal
What You'll Learn
Understanding base-2 vs base-10 systems.
Real-World Context
"How computers read numbers (0s and 1s) vs how humans read them. Like translating a secret code!"
Breaking It Down
- Initialize decimal = 0, power = 0
- Extract last digit of binary number
- Multiply digit by 2 raised to the power
- Add to decimal
- Increment power, remove last digit
- Repeat until binary is 0
def binary_to_decimal(binary):
decimal, i = 0, 0
while binary != 0:
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return decimalLine-by-Line Walkthrough
Each digit in a binary number represents a power of 2. We start from the right (2^0) and move left, adding up the values where we see a '1'.
Complexity Analysis
- Time: O(log N)
- Space: O(1)
- We process each bit of the binary number.
Common Mistakes
- ❌ Starting the power from 1 instead of 0
✅ The rightmost digit is always 2^0.
Try It Yourself
Can you write a program to convert Decimal to Binary?
Leap Year
What You'll Learn
Complex conditional logic and divisibility rules.
Real-World Context
"A year with 366 days. It happens every 4 years, except for century years which must be divisible by 400."
Breaking It Down
- Check if divisible by 400 -> Leap
- Else check if divisible by 100 -> Not Leap
- Else check if divisible by 4 -> Leap
- Otherwise -> Not Leap
def is_leap_year(year):
if (year % 400 == 0): return True
if (year % 100 == 0): return False
if (year % 4 == 0): return True
return FalseLine-by-Line Walkthrough
The logic follows a hierarchy: 400 overrides 100, and 100 overrides 4.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- Constant number of checks.
Common Mistakes
- ❌ Only checking divisibility by 4
✅ Century years like 1900 are not leap years even though they are divisible by 4.
Try It Yourself
How many leap years are there between 2000 and 2100?
Perfect Square
What You'll Learn
Using square root and integer conversion.
Real-World Context
"A number like 16 or 25 that is the product of an integer with itself."
Breaking It Down
- Calculate the square root of the number
- Check if the square of the integer part of the root equals the number
import math
def is_perfect_square(n):
if n < 0: return False
root = int(math.sqrt(n))
return root * root == nLine-by-Line Walkthrough
We take the square root, truncate it to an integer, and see if squaring it back gives us the original number.
Complexity Analysis
- Time: O(1) or O(log N)
- Space: O(1)
- Depends on the implementation of the sqrt function.
Common Mistakes
- ❌ Not handling negative numbers
✅ Negative numbers cannot be perfect squares in real numbers.
Try It Yourself
Can you check for a perfect square without using the sqrt() function? (Hint: Use Binary Search)
Perfect Number
What You'll Learn
Finding divisors and summing them.
Real-World Context
"A number that equals the sum of its proper divisors (excluding itself). Example: 6 (1+2+3=6)."
Breaking It Down
- Initialize sum = 1 (since 1 is a divisor for all n > 1)
- Loop from 2 to sqrt(n)
- If i divides n, add i and n/i to sum
- Check if sum == n
def is_perfect(n):
if n <= 1: return False
total = 1
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
total += i
if i*i != n:
total += n // i
return total == nLine-by-Line Walkthrough
We find all divisors up to the square root to optimize the search, similar to the prime number check.
Complexity Analysis
- Time: O(√N)
- Space: O(1)
- We only loop up to the square root of N.
Common Mistakes
- ❌ Including the number itself as a divisor
✅ A perfect number is the sum of its *proper* divisors.
Try It Yourself
What is the next perfect number after 6 and 28?
Automorphic
What You'll Learn
Comparing the end of a number's square.
Real-World Context
"A number whose square ends with the number itself. Example: 5 (5²=25), 25 (25²=625)."
Breaking It Down
- Calculate square of n
- Check if square % (10 ^ number_of_digits_in_n) == n
def is_automorphic(n):
sq = n * n
return str(sq).endswith(str(n))Line-by-Line Walkthrough
In Python, string comparison is easiest. In C++, we compare digits from the right one by one.
Complexity Analysis
- Time: O(log N)
- Space: O(1)
- We process each digit of the number.
Common Mistakes
- ❌ Integer overflow when squaring
✅ Use long long for the square in C++.
Try It Yourself
Find all automorphic numbers up to 100.
Greatest of Three
What You'll Learn
Nested conditionals and logical operators.
Real-World Context
"Finding the largest value among three inputs. Like picking the tallest person in a group of three."
Breaking It Down
- Compare a with b and c
- If a is greater than both, a is greatest
- Else if b is greater than c, b is greatest
- Otherwise c is greatest
def greatest_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return cLine-by-Line Walkthrough
We use logical AND (&&) to check multiple conditions at once. This is cleaner than nested if-else blocks.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- Fixed number of comparisons.
Common Mistakes
- ❌ Not handling equal numbers
✅ Use >= instead of > to correctly handle cases where numbers are the same.
Try It Yourself
Can you find the greatest of three numbers using the ternary operator?
Multiplication Table
What You'll Learn
Simple loops and formatted output.
Real-World Context
"Printing the table for a number, e.g., 5 x 1 = 5, 5 x 2 = 10..."
Breaking It Down
- Loop from 1 to 10
- Multiply the number by the loop index
- Print the result in a readable format
def print_table(n):
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")Line-by-Line Walkthrough
A basic for-loop that iterates 10 times to generate the products.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- The loop always runs 10 times.
Common Mistakes
- ❌ Starting the loop from 0
✅ Multiplication tables usually start from 1.
Try It Yourself
Can you print a multiplication table up to 20?
Simple Interest
What You'll Learn
Applying mathematical formulas in code.
Real-World Context
"Calculating the interest on a loan or investment. Formula: (P * R * T) / 100."
Breaking It Down
- Take Principal (P), Rate (R), and Time (T) as input
- Calculate (P * R * T) / 100
- Return the result
def calculate_si(p, r, t):
return (p * r * t) / 100Line-by-Line Walkthrough
A straightforward implementation of the mathematical formula. Use floating-point numbers for precision.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- Single calculation.
Common Mistakes
- ❌ Using integer division
✅ Interest often involves decimals, so use float or double.
Try It Yourself
Can you calculate Compound Interest?
Sum of N Natural Numbers
What You'll Learn
Using the arithmetic series formula.
Real-World Context
"Finding the sum of 1 + 2 + 3 + ... + N."
Breaking It Down
- Use the formula: N * (N + 1) / 2
- Or use a loop from 1 to N
def sum_n(n):
return n * (n + 1) // 2Line-by-Line Walkthrough
The formula N*(N+1)/2 is the most efficient way (O(1)) to find the sum of the first N natural numbers.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- Single mathematical formula.
Common Mistakes
- ❌ Using a loop for very large N
✅ A loop takes O(N) time, while the formula is O(1).
Try It Yourself
Can you find the sum of squares of the first N natural numbers?
ASCII Value
What You'll Learn
Character to integer conversion.
Real-World Context
"Finding the numerical code for a character. 'A' is 65, 'a' is 97."
Breaking It Down
- In Python, use ord(char)
- In C++, simply cast the char to an int
def get_ascii(char):
return ord(char)Line-by-Line Walkthrough
Computers store characters as numbers. ASCII is the standard mapping for these numbers.
Complexity Analysis
- Time: O(1)
- Space: O(1)
- Direct conversion.
Common Mistakes
- ❌ Confusing ASCII with Unicode
✅ ASCII is a subset of Unicode (UTF-8).
Try It Yourself
What is the ASCII value of the space character?
Keep Practicing!
We've covered the most critical foundation questions. The remaining 10+ logic questions (like ASCII values, Simple Interest, and Greatest of Three) follow similar patterns. Master these first, and the rest will feel like a breeze!