An ugly number is a positive integer whose only prime factors are 2, 3, and 5, with 1 included by convention. The sequence begins as 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, and so on. Given an integer n, return the nth ugly number.
Examples:
Input: n = 5
Output: 5
Explanation: Ugly Numbers - 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.
So, 5th Ugly Number is 5.
Input: n = 10
Output: 12
Explanation: 12 is the 10th ugly number.
[Naive Approach] - Using Iteration - Exponential Time and O(1) Space
The idea is to loop over all positive integers starting from 1 until the count of ugly numbers in less than n. To check if number is ugly, divide the number by greatest divisible powers of 2, 3 and 5, if the number becomes 1 then it is an ugly number otherwise not.
C++
// C++ program to find nth ugly number
#include <bits/stdc++.h>
using namespace std;
// This function divides a by greatest
// divisible power of b
int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count)
{
i++;
if (isUgly(i))
count++;
}
return i;
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
C
#include <stdio.h>
// This function divides a by greatest
// divisible power of b
int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count)
{
i++;
if (isUgly(i))
count++;
}
return i;
}
int main()
{
int n = 10;
printf("%d", uglyNumber(n));
return 0;
}
Java
// This function divides a by greatest
// divisible power of b
class GfG {
// This function divides a by greatest
// divisible power of b
static int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
static int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
static int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count) {
i++;
if (isUgly(i) == 1)
count++;
}
return i;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n));
}
}
Python
# This function divides a by greatest
# divisible power of b
def maxDivide(a, b):
while a % b == 0:
a = a // b
return a
# Function to check if a number is ugly or not
def isUgly(val):
val = maxDivide(val, 2)
val = maxDivide(val, 3)
val = maxDivide(val, 5)
return 1 if val == 1 else 0
# Function to get the nth ugly number
def uglyNumber(n):
i = 1
# Ugly number count
count = 1
# Check for all integers until ugly
# count becomes n
while n > count:
i += 1
if isUgly(i):
count += 1
return i
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
C#
// This function divides a by greatest
// divisible power of b
using System;
class GfG {
// This function divides a by greatest
// divisible power of b
static int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
static int isUgly(int val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val == 1) ? 1 : 0;
}
// Function to get the nth ugly number
static int uglyNumber(int n)
{
int i = 1;
// Ugly number count
int count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count) {
i++;
if (isUgly(i) == 1)
count++;
}
return i;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n));
}
}
JavaScript
// This function divides a by greatest
// divisible power of b
function maxDivide(a, b)
{
while (a % b === 0)
a = a / b;
return a;
}
// Function to check if a number is ugly or not
function isUgly(val)
{
val = maxDivide(val, 2);
val = maxDivide(val, 3);
val = maxDivide(val, 5);
return (val === 1) ? 1 : 0;
}
// Function to get the nth ugly number
function uglyNumber(n)
{
let i = 1;
// Ugly number count
let count = 1;
// Check for all integers until ugly
// count becomes n
while (n > count) {
i++;
if (isUgly(i))
count++;
}
return i;
}
let n = 10;
console.log(uglyNumber(n));
Time Complexity: The time complexity is O(n^(1/3) * exp(n^(1/3))) since ugly numbers are sparse, and the nth ugly number is approximately exp(n^(1/3)). As a result, the loop runs up to exp(n^(1/3)) times, with each check taking O(n^(1/3)) time, leading to the overall complexity.
Space Complexity: O(1)
[Better Approach] - Using Sorted Set - O(n * log n) Time and O(n) Space
The idea is to use Set (set in C++, TreeSet in Java) to store the unique ugly numbers in sorted order. To do so, firstly insert the first ugly number i.e. 1 in the set and run a loop until the Nth ugly number is not found. At each iteration take out the smallest number x from the set, and insert three numbers (x * 2), (x * 3), and (x * 5), representing the next three ugly numbers. At last return the Nth number in the set.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to get the nth ugly number
int uglyNumber(int n)
{
// to store the ugly numbers in sorted order
set<long long> s; // Use long long to prevent overflow
// insert the first ugly number i.e. 1.
s.insert(1);
n--;
while (n)
{
long long x = *(s.begin()); // Use long long
s.erase(s.begin());
s.insert(x * 2);
s.insert(x * 3);
s.insert(x * 5);
// Decrement n
n--;
}
// return the first element of the set, which is the nth ugly number
return *(s.begin());
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
TreeSet<Long> s
= new TreeSet<>(); // Use TreeSet<Long> to store
// ugly numbers
s.add(1L); // Add the first ugly number
n--;
while (n > 0) {
long x
= s.first(); // Get the smallest ugly number
s.remove(x); // Remove it from the set
s.add(x * 2);
s.add(x * 3);
s.add(x * 5);
n--;
}
// Return the nth ugly number (casted to int)
return s.first().intValue();
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n)); // Output: 12
}
}
Python
# Function to get the nth ugly number
def uglyNumber(n):
# to store the ugly numbers in sorted order
# (using a list to simulate a sorted set)
s = [1]
n -= 1
# loop until n becomes 0
while n:
x = s[0]
s.pop(0)
if x * 2 not in s:
s.append(x * 2)
if x * 3 not in s:
s.append(x * 3)
if x * 5 not in s:
s.append(x * 5)
# sort the list to maintain sorted order
s.sort()
# Decrement n
n -= 1
# return the first element of the set
# which is the nth ugly number
return s[0]
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
SortedSet<long> s
= new SortedSet<long>(); // Use long to prevent
// overflow
s.Add(1); // Insert the first ugly number
n--;
while (n > 0) {
long x = s.Min; // Get the smallest ugly number
s.Remove(x); // Remove it from the set
s.Add(x * 2);
s.Add(x * 3);
s.Add(x * 5);
n--;
}
// Return the nth ugly number (casted to int)
return (int)s.Min;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n)); // Output: 12
}
}
JavaScript
// Function to get the nth ugly number
function uglyNumber(n)
{
// to store the ugly numbers in sorted order
// (using an array to simulate a sorted set)
let s = [ 1 ];
// insert the first ugly number i.e. 1.
n--;
// loop until n becomes 0
while (n > 0) {
let x = s[0];
// Deleting the first element
s.shift();
s.push(x * 2);
s.push(x * 3);
s.push(x * 5);
// Remove duplicates and sort the array
s = Array.from(new Set(s));
s.sort(function(a, b) { return a - b; });
// Decrement n
n--;
}
// return the first element of the set
// which is the nth ugly number
return s[0];
}
let n = 10;
console.log(uglyNumber(n));
[Expected Approach 1 ] - Using Dynamic Programming O(n) Time and O(n) Space
The ugly number sequence consists of numbers that can only be divided by 2, 3, or 5, starting with 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …. One way to view this sequence is by breaking it into three groups:
- Multiples of 2 → (1×2, 2×2, 3×2, …)
- Multiples of 3 → (1×3, 2×3, 3×3, …)
- Multiples of 5 → (1×5, 2×5, 3×5, …)
To generate ugly numbers efficiently, we maintain an array dp[]
of size n, initializing dp[0] = 1
(the first ugly number). Additionally, we use:
- Three index pointers to track the next multiple of 2, 3, and 5.
- Three variables to store these next multiples.
Initially, the index pointers are set to 0, and the multiples are set to 2, 3, and 5. For each iteration from 1 to n, we:
- Select the smallest among the three multiples as the next ugly number.
- Store this number in dp
[]
. - Update the corresponding index and compute its next multiple using
arr[ind] * factor
, where the factor is 2, 3, or 5.
Illustration: Finding the 5th Ugly Number
C++
#include <bits/stdc++.h>
using namespace std;
// Function to get the nth ugly number
int uglyNumber(int n)
{
// To store ugly numbers
vector<int> arr(n);
// stores the index of the next
// multiple of 2, 3, and 5.
int ind2 = 0, ind3 = 0, ind5 = 0;
int mulTwo = 2, mulThree = 3, mulFive = 5;
int nextNum = 1;
arr[0] = 1;
// loop to fill up the array up to n
for (int i = 1; i < n; i++)
{
// find the minimum of the multiples
nextNum = min({mulTwo, mulThree, mulFive});
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum == mulTwo)
{
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum == mulThree)
{
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum == mulFive)
{
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
Java
// Function to get the nth ugly number
import java.util.*;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// To store ugly numbers
int[] arr = new int[n];
// stores the index of the next
// multiple of 2, 3, and 5.
int ind2 = 0, ind3 = 0, ind5 = 0;
// to next multiple of 2, 3, and 5
int mulTwo = 2, mulThree = 3, mulFive = 5;
// stores next ugly number
int nextNum = 1;
// 1 is the first ugly number
arr[0] = 1;
// loop to fill up the array up to n
for (int i = 1; i < n; i++) {
// find the minimum of the multiples
nextNum = Math.min(mulTwo,
Math.min(mulThree, mulFive));
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum == mulTwo) {
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum == mulThree) {
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum == mulFive) {
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n));
}
}
Python
# Function to get the nth ugly number
def uglyNumber(n):
# To store ugly numbers
arr = [0] * n
# stores the index of the next
# multiple of 2, 3, and 5.
ind2 = 0
ind3 = 0
ind5 = 0
# to next multiple of 2, 3, and 5
mulTwo = 2
mulThree = 3
mulFive = 5
# stores next ugly number
nextNum = 1
# 1 is the first ugly number
arr[0] = 1
# loop to fill up the array up to n
for i in range(1, n):
# find the minimum of the multiples
nextNum = min(mulTwo, mulThree, mulFive)
arr[i] = nextNum
# if nextNum is equal to any of the multiples
# then increment the value of the multiple
if nextNum == mulTwo:
ind2 += 1
mulTwo = arr[ind2] * 2
if nextNum == mulThree:
ind3 += 1
mulThree = arr[ind3] * 3
if nextNum == mulFive:
ind5 += 1
mulFive = arr[ind5] * 5
# return the nth ugly number
return nextNum
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
C#
// Function to get the nth ugly number
using System;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// To store ugly numbers
int[] arr = new int[n];
// stores the index of the next
// multiple of 2, 3, and 5.
int ind2 = 0, ind3 = 0, ind5 = 0;
// to next multiple of 2, 3, and 5
int mulTwo = 2, mulThree = 3, mulFive = 5;
// stores next ugly number
int nextNum = 1;
// 1 is the first ugly number
arr[0] = 1;
// loop to fill up the array up to n
for (int i = 1; i < n; i++) {
// find the minimum of the multiples
nextNum = Math.Min(mulTwo,
Math.Min(mulThree, mulFive));
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum == mulTwo) {
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum == mulThree) {
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum == mulFive) {
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n));
}
}
JavaScript
// Function to get the nth ugly number
function uglyNumber(n)
{
// To store ugly numbers
let arr = new Array(n).fill(0);
// stores the index of the next
// multiple of 2, 3, and 5.
let ind2 = 0, ind3 = 0, ind5 = 0;
// to next multiple of 2, 3, and 5
let mulTwo = 2, mulThree = 3, mulFive = 5;
// stores next ugly number
let nextNum = 1;
// 1 is the first ugly number
arr[0] = 1;
// loop to fill up the array up to n
for (let i = 1; i < n; i++) {
// find the minimum of the multiples
nextNum
= Math.min(mulTwo, Math.min(mulThree, mulFive));
arr[i] = nextNum;
// if nextNum is equal to any of the multiples
// then increment the value of the multiple
if (nextNum === mulTwo) {
ind2++;
mulTwo = arr[ind2] * 2;
}
if (nextNum === mulThree) {
ind3++;
mulThree = arr[ind3] * 3;
}
if (nextNum === mulFive) {
ind5++;
mulFive = arr[ind5] * 5;
}
}
// return the nth ugly number
return nextNum;
}
let n = 10;
console.log(uglyNumber(n));
[Expected Approach 2 ] - Using Binary Search - O((log r) ^ 3) Time and O(1) Space
Note: This approach works best when we know the highest possible value of the ugly number. In our case, we are considering the maximum possible value to be 21474836647.
The idea is to use binary search to find the value such that the count of ugly numbers up to that value is equal to n. To do so, firstly create an array power[] of size 31, to store the power of 2 raised up to 30, this will be used to calculate the number of ugly numbers. Now perform binary search, taking low as 1, and high as 21474836647, which we are considering to be highest possible ugly number. At each iteration find the mid value.
Now, to calculate the count of ugly numbers up to mid value, use nested loops where outer loop increase in multiple of 5, and the inner loop increase in multiple of 3. For each iteration find the index of the first value greater than mid / i * j, (where i is multiple of 5, and j is multiple of 3) in array powers[]. Increment the count by the index.
At last check if count is greater than or equal to n, if so, update the answer to mid, and reduce high to mid - 1, otherwise increase low to mid + 1.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to get the nth ugly number
int uglyNumber(int n)
{
// stores power of two
vector<int> power(31, 1);
for (int i = 1; i <= 30; i++)
{
power[i] = power[i - 1] * 2;
}
// initialize low and high
int l = 1, r = 2147483647;
int ans = -1;
while (l <= r)
{
int mid = l + ((r - l) / 2);
// to stores count of ugly
// numbers less than mid
int cnt = 0;
for (int i = 1; i <= mid; i *= 5)
{
for (int j = 1; j * i <= mid; j *= 3)
{
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (pow) we are
// trying to find the max power of 2 such
// that i*j*power of 2 is less than mid
cnt += upper_bound(power.begin(), power.end(), mid / (i * j)) - power.begin();
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else
r = mid - 1, ans = mid;
}
return ans;
}
int main()
{
int n = 10;
cout << uglyNumber(n);
return 0;
}
Java
// Function to get the nth ugly number
import java.util.*;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// stores power of two
int[] power = new int[31];
Arrays.fill(power, 1);
for (int i = 1; i <= 30; i++) {
power[i] = power[i - 1] * 2;
}
int l = 1, r = 2147483647;
int ans = -1;
while (l <= r) {
int mid = l + ((r - l) / 2);
int cnt = 0;
for (int i = 1; i <= mid; i *= 5) {
for (int j = 1; j * i <= mid; j *= 3) {
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (power) we
// are trying to find the max power of 2
// such that i*j*power of 2 is less than
// mid
cnt += upperBound(power, mid / (i * j));
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
// Helper function to find upper bound in a sorted array
static int upperBound(int[] arr, int key)
{
int low = 0, high = arr.length;
while (low < high) {
int mid = low + ((high - low) / 2);
if (arr[mid] <= key)
low = mid + 1;
else
high = mid;
}
return low;
}
public static void main(String[] args)
{
int n = 10;
System.out.println(uglyNumber(n));
}
}
Python
# Function to get the nth ugly number
def uglyNumber(n):
# stores power of two
power = [1] * 31
for i in range(1, 31):
power[i] = power[i - 1] * 2
# initialize low and high
l = 1
r = 2147483647
ans = -1
while l <= r:
mid = l + ((r - l) // 2)
cnt = 0
i = 1
while i <= mid:
j = 1
while j * i <= mid:
# possible powers of 3 and 5 such that
# their product is less than mid
# using the power array of 2 (power) we are
# trying to find the max power of 2 such
# that i*j*power of 2 is less than mid
cnt += upperBound(power, mid // (i * j))
j *= 3
i *= 5
# if count of ugly numbers less than mid
# is less than n we update l to mid + 1
if cnt < n:
l = mid + 1
# else update r to mid - 1
# and upate the answer
else:
r = mid - 1
ans = mid
return ans
def upperBound(arr, key):
low = 0
high = len(arr)
while low < high:
mid = low + ((high - low) // 2)
if arr[mid] <= key:
low = mid + 1
else:
high = mid
return low
if __name__ == "__main__":
n = 10
print(uglyNumber(n))
C#
// Function to get the nth ugly number
using System;
using System.Collections.Generic;
class GfG {
// Function to get the nth ugly number
static int uglyNumber(int n)
{
// stores power of two
int[] power = new int[31];
for (int i = 0; i < 31; i++) {
power[i] = 1;
}
for (int i = 1; i <= 30; i++) {
power[i] = power[i - 1] * 2;
}
int l = 1, r = 2147483647;
int ans = -1;
while (l <= r) {
int mid = l + ((r - l) / 2);
// to stores count of ugly
// numbers less than mid
int cnt = 0;
for (int i = 1; i <= mid; i *= 5) {
for (int j = 1; j * i <= mid; j *= 3) {
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (power) we
// are trying to find the max power of 2
// such that i*j*power of 2 is less than
// mid
cnt += upperBound(power, mid / (i * j));
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
// Helper function to find upper bound in a sorted array
static int upperBound(int[] arr, int key)
{
int low = 0, high = arr.Length;
while (low < high) {
int mid = low + ((high - low) / 2);
if (arr[mid] <= key)
low = mid + 1;
else
high = mid;
}
return low;
}
static void Main()
{
int n = 10;
Console.WriteLine(uglyNumber(n));
}
}
JavaScript
// Function to get the nth ugly number
function uglyNumber(n)
{
let power = new Array(31).fill(1);
for (let i = 1; i <= 30; i++) {
power[i] = power[i - 1] * 2;
}
// initialize low and high
let l = 1, r = 2147483647;
let ans = -1;
while (l <= r) {
// find the mid value
let mid = l + Math.floor((r - l) / 2);
// to stores count of ugly
// numbers less than mid
let cnt = 0;
for (let i = 1; i <= mid; i *= 5) {
for (let j = 1; j * i <= mid; j *= 3) {
// possible powers of 3 and 5 such that
// their product is less than mid
// using the power array of 2 (power) we are
// trying to find the max power of 2 such
// that i*j*power of 2 is less than mid
cnt += upperBound(
power, Math.floor(mid / (i * j)));
}
}
// if count of ugly numbers less than mid
// is less than n we update l to mid + 1
if (cnt < n)
l = mid + 1;
// else update r to mid - 1
// and upate the answer
else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
function upperBound(arr, key)
{
let low = 0, high = arr.length;
while (low < high) {
let mid = low + Math.floor((high - low) / 2);
if (arr[mid] <= key)
low = mid + 1;
else
high = mid;
}
return low;
}
let n = 10;
console.log(uglyNumber(n));
Time Complexity: O((log r)³), where r is the value of the Nth ugly number. Since we assume r = 21,474,836,647.
Auxiliary Space: O(1)
C++ Program to Check if a Given Number is Ugly Number or not
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem