Problems - Set 1
Prime Number
Apply Sieve of Eratosthenes Algorithm
import java.util.ArrayList;
public class SieveOfEratosthenes {
public static ArrayList<Integer> findPrimes(int n) {
// Step 1: Initialize a boolean array to keep track of prime numbers
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true; // Assume all numbers from 2 to n are prime initially
}
// Step 2: Apply the sieve algorithm
for (int p = 2; p * p <= n; p++) {
if (isPrime[p]) {
// Mark all multiples of p as non-prime
for (int multiple = p * p; multiple <= n; multiple += p) {
isPrime[multiple] = false;
}
}
}
// Step 3: Collect all prime numbers into an ArrayList
ArrayList<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.add(i); // Add prime number to the list
}
}
return primes; // Return the sorted ArrayList of primes
}
public static void main(String[] args) {
int n = 50; // Example: Find all primes up to 50
ArrayList<Integer> primes = findPrimes(n);
System.out.println("Prime numbers up to " + n + ": " + primes);
}
}Time Complexity Analysis
The algorithm consists of three main parts:
Step 1: Initializing the Boolean Array
We initialize an array of size
n + 1and set all values totrue.This requires a single loop that runs O(n) times.
Step 2: Marking Non-Prime Numbers
We iterate from
p = 2to√n. Ifpis prime, we mark all multiples ofpstarting fromp²as non-prime.The number of times a number is marked reduces significantly for higher values of
p.Time Complexity: O(n log log n)
Step 3: Collecting Prime Numbers
We loop through the
isPrimearray and add numbers that are stilltrueto the result list.This runs in O(n) time
Space Complexity Analysis
Boolean
isPrimearray:Takes O(n) space.
ArrayList
primesstoring prime numbers:The number of primes up to
nis approximately O(n / log n).Space Complexity: O(n / log n).
Overall Space Complexity: O(n)
Program to Swap Two Numbers
Approaches based on time and space complexity
Creating an temporary variable.
Time Complexity: O(1) - Constant time. This is because the swapping operation only involves a few assignment statements, which are independent of the input size (number size).
Space Complexity: O(1) - Constant space. Only a single temporary variable is used, regardless of the size of the numbers being swapped.
Using maths addition and subtraction (Without Using Third Variable)
Time Complexity: O(1) - Constant time. Similar to the temporary variable approach, this method involves a fixed number of operations regardless of the input size.
Space Complexity: O(1) - Constant space. No additional memory is allocated beyond the variables holding the numbers.
Using exclusive OR (Bitwise XOR) operator
Time Complexity: O(1) - Constant time. Like the previous approaches, this method has a fixed number of operations.
Space Complexity: O(1) - Constant space. No extra memory is used beyond the variables holding the numbers.
Convert Decimal number to Binary number
There are many approaches.
Using Arrays

Using Bitwise Operators
Without using arrays
Using inbuit method
Convert Binary number to Decimal number
Using Math.pow(...) function
Binary Arithmetic
Add two binary numbers given in long format
Input first binary number: 10 Input second binary number: 11
Expected Output: Sum of two binary numbers: 101
Method 1: Using inbuilt method
Method 2: Using Modulo Division
Multiply two binary numbers given in long format
Input first binary number: 10 Input second binary number: 11
Expected Output: Sum of two binary numbers: 110
Method 1: Using inbuilt method
Method 2: Using Modulo operation
Factorial of a number
Small number
Iterative Solution
Time Complexity: O(n) Auxiliary Space: O(1)
Using Recursive Method
Time Complexity: O(n) Auxiliary Space: O(n)
Using Stream
Time Complexity: O(n) Auxiliary Space: O(1)
Large number
Using BigIntegers
Time Complexity: O(N) Auxiliary Space: O(1)
Using Basic Maths Operation with the help of array i.e. storing digits in array and considering carry which helps in increasing size of array.
Time Complexity: O(N log (N!)), where O(N) is for loop and O(log N!) is for nested while loop Auxiliary Space: O(max(digits in factorial))
Print Pascal Triangle

Using nCr formula

Time complexity: O(2n) due to recursive method
Auxiliary Space: O(n) due to recursive stack space
Using Binomial Coefficient
Method 1:
Method 2:
Using C = C * (line - a) / a
The ‘A’th entry in a line number line is Binomial Coefficient C(line, a) and all lines start with value 1. The idea is to calculate C(line, a) using C(line, a-1).
Time complexity: O(n^2) where n is given input for no of rows of pascal triangle
Auxiliary Space: O(1)
Print fibonacci series
Using Iterative Method
Using Recursive Method
Print number triangle


Find Transpose of Matrix
Square Matrix
Method 1: Using additional array
Method 2: WIthout using additional array
Rectangular Matrix

GCD or HCF of two numbers

Using Iteration
Time Complexity: O(min(a,b)) Auxiliary Space: O(1)
Using Euclidean algorithm for GCD of two numbers (Involves Recursion)

Time Complexity: O(min(a,b)) Auxiliary Space: O(1) No space is used as it is a tail recursion i.e. no extra space is used apart from the space needed for the function call stack.
Optimization Euclidean algorithm by checking divisibility

Time Complexity: O(min(a, b)) Auxiliary Space: O(1)
Optimization using division
Instead of the Euclidean algorithm by subtraction, a better approach is that we don’t perform subtraction but continuously divide the bigger number by the smaller number.
Time Complexity: O(log(min(a,b)))
Auxiliary Space: O(log(min(a,b))
Iterative implementation using Euclidean Algorithm
Time Complexity: O(log(min(a,b))) Auxiliary Space: O(1)
Using in-built function in Java for BigIntegers
Time Complexity: O(log(min(a, b))) Auxiliary Space: O(1)
LCM of two numbers
LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers.
For example, LCM of 15 and 20 is 60, and LCM of 5 and 7 is 35.
Using GCD of 2 numbers and Formula
Time Complexity: O(log(min(a,b)) Auxiliary Space: O(log(min(a,b))
Using Iterative method
Time Complexity: O(min(a,b)) Auxiliary Space: O(1)
Find All Factors of a Number
Last updated