Longest Arithmetic Progression
Last Updated :
22 Nov, 2024
Given an array arr[] of sorted integers and distinct positive integers, find the length of the Longest Arithmetic Progression in it.
Note: A sequence seq is an arithmetic progression if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).
Examples:
Input: arr[] = [1, 7, 10, 15, 27, 29]
Output: 3
Explanation: The longest arithmetic progression is [1, 15, 29] having common difference 14.
Input: arr []= [5, 10, 15, 20, 25, 30]
Output: 6
Explanation: The whole set is in AP having common difference 5.
Using Recursion - O(n^3) Time and O(n) Space
For the recursive approach to finding the length of the longest arithmetic progression (AP), there are two main cases:
Include the current element in the AP
- If the difference between the current element and a previous element matches the desired difference, extend the AP by considering the current element.
Mathematically: solve(i, diff) = 1 + solve(j, diff) for all j < i such that arr[i] - arr[j] = diff.
Exclude the current element from the AP:
- Skip the current element and proceed with the remaining elements.
Mathematically: solve(i, diff) = max(solve(i - 1, diff), solve(j, diff)) where j < i.
Base Case: solve(i, diff) = 0 when i < 0. This means if there are no elements left to form an AP, the length is zero.
For every pair of indices (i, j), compute the maximum AP length as:
- Length = max(Length, 2 + solve(i, arr[j] - arr[i]))
C++
// C++ program to find the length of the longest
// arithmetic progression (AP) using recursion
#include <bits/stdc++.h>
using namespace std;
// Recursive function to find the length of AP
// ending at index `index` with difference `diff`
int solve(int index, int diff, vector<int> &arr) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0)
return 0;
int ans = 0;
for (int j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr[index] - arr[j] == diff) {
ans = max(ans, 1 + solve(j, diff, arr));
}
}
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
int lengthOfLongestAP(vector<int> &arr) {
int n = arr.size();
if (n <= 2)
return n;
int ans = 0;
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Calculate difference and find
// AP using recursion
ans = max(ans, 2 + solve(i,
arr[j] - arr[i], arr));
}
}
return ans;
}
int main() {
vector<int> arr = {1, 7, 10, 15, 27, 29};
cout << lengthOfLongestAP(arr) << endl;
return 0;
}
Java
// Java program to find the length of the longest
// arithmetic progression (AP) using recursion
import java.util.ArrayList;
class GfG {
// Recursive function to find the length of AP
// ending at index `index` with difference `diff`
static int solve(int index, int diff,
ArrayList<Integer> arr) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0) {
return 0;
}
int ans = 0;
// Iterate through previous elements
// to find matching differences
for (int j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr.get(index) - arr.get(j) == diff) {
ans = Math.max(ans,
1 + solve(j, diff, arr));
}
}
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
static int lengthOfLongestAP(ArrayList<Integer> arr) {
int n = arr.size();
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
int ans = 0;
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Calculate difference and find AP
// using recursion
int diff = arr.get(j) - arr.get(i);
ans = Math.max(ans,
2 + solve(i, diff, arr));
}
}
return ans;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(7);
arr.add(10);
arr.add(15);
arr.add(27);
arr.add(29);
System.out.println(lengthOfLongestAP(arr));
}
}
Python
# Python program to find the length of the longest
# arithmetic progression (AP) using recursion
# Function to find the length of AP ending at
# index `index` with difference `diff`
def solve(index, diff, arr):
# Base case: if index goes out of bounds,
# return 0
if index < 0:
return 0
ans = 0
# Iterate through previous elements to find
# matching differences
for j in range(index - 1, -1, -1):
# If the difference matches, extend the AP
if arr[index] - arr[j] == diff:
ans = max(ans, 1 + solve(j, diff, arr))
return ans
# Function to find the length of the longest
# arithmetic progression (AP) in the array
def lengthOfLongestAP(arr):
n = len(arr)
# If there are less than 3 elements,
# return the size
if n <= 2:
return n
ans = 0
# Iterate through all pairs of elements as
# possible first two terms
for i in range(n):
for j in range(i + 1, n):
# Calculate difference and find AP
# using recursion
diff = arr[j] - arr[i]
ans = max(ans, 2 + solve(i, diff, arr))
return ans
if __name__ == "__main__":
arr = [1, 7, 10, 15, 27, 29]
print(lengthOfLongestAP(arr))
C#
// C# program to find the length of the longest
// arithmetic progression (AP) using recursion
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to find the length of AP
// ending at index `index` with difference `diff`
static int Solve(int index, int diff,
List<int> arr) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0) {
return 0;
}
int ans = 0;
// Iterate through previous elements
// to find matching differences
for (int j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr[index] - arr[j] == diff) {
ans = Math.Max(ans,
1 + Solve(j, diff, arr));
}
}
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
static int LengthOfLongestAP(List<int> arr) {
int n = arr.Count;
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
int ans = 0;
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Calculate difference and find AP
// using recursion
int diff = arr[j] - arr[i];
ans = Math.Max(ans,
2 + Solve(i, diff, arr));
}
}
return ans;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 1, 7, 10,
15, 27, 29 };
Console.WriteLine(LengthOfLongestAP(arr));
}
}
JavaScript
// Javascript program to find the length of the longest
// arithmetic progression (AP) using recursion
// Function to find the length of AP ending at
// index `index` with difference `diff`
function solve(index, diff, arr) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0) {
return 0;
}
let ans = 0;
// Iterate through previous elements to find
// matching differences
for (let j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr[index] - arr[j] === diff) {
ans = Math.max(ans,
1 + solve(j, diff, arr));
}
}
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
function lengthOfLongestAP(arr) {
const n = arr.length;
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
let ans = 0;
// Iterate through all pairs of elements as
// possible first two terms
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Calculate difference and find AP
// using recursion
const diff = arr[j] - arr[i];
ans = Math.max(ans,
2 + solve(i, diff, arr));
}
}
return ans;
}
const arr = [1, 7, 10, 15, 27, 29];
console.log(lengthOfLongestAP(arr));
Using Top-Down DP (Memoization) - O(n^2) Time and O(n^2) Space
1. Optimal Substructure: The solution to the problem can be derived from optimal solutions of smaller subproblems. Specifically, If the difference diff between two elements matches the desired difference for an AP ending at index, we extend the progression:
- solve(index, diff) = 1 + solve(j, diff) where j < index and arr[index] - arr[j] = diff.
If no such j exists, the result for solve(index, diff) remains the same.
2. Overlapping Subproblems: In the recursive solution, many subproblems are recomputed multiple times. For example, solve(i, diff) for a specific index and difference can be computed repeatedly for different calls in the recursion tree. Memoization stores these results to avoid redundant calculations.
If the value for solve(index, diff) is already computed and stored in memo[index][diff], it is directly returned to avoid redundant computation:
- solve(index, diff) = memo[index][diff], if memo[index][diff] exists.
C++
// C++ program to find the length of the longest
// arithmetic progression (AP) using recursion
// with memoization
#include <bits/stdc++.h>
using namespace std;
// Recursive function to find the length of AP
// ending at index `index` with difference `diff`
int solve(int index, int diff, vector<int> &arr,
unordered_map<int, unordered_map<int, int>> &memo) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0)
return 0;
// Check memo table for precomputed result
if (memo[index].count(diff))
return memo[index][diff];
int ans = 0;
for (int j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr[index] - arr[j] == diff) {
ans = max(ans, 1 + solve(j, diff, arr, memo));
}
}
// Store the result in the memo table
return memo[index][diff] = ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
int lengthOfLongestAP(vector<int> &arr) {
int n = arr.size();
if (n <= 2)
return n;
int ans = 0;
// Memoization table to store results for solve()
unordered_map<int, unordered_map<int, int>> memo;
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Calculate difference and find
// AP using memoized recursion
ans = max(ans, 2 + solve(i,
arr[j] - arr[i], arr, memo));
}
}
return ans;
}
int main() {
vector<int> arr = {1, 7, 10, 15, 27, 29};
cout << lengthOfLongestAP(arr) << endl;
return 0;
}
Java
// Java program to find the length of the longest
// arithmetic progression (AP) using recursion
// with memoization
import java.util.ArrayList;
import java.util.HashMap;
class GfG {
// Recursive function to find the length of AP
// ending at index `index` with difference `diff`
static int solve(int index, int diff,
ArrayList<Integer> arr,
HashMap<Integer, HashMap<Integer, Integer>> memo) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0) {
return 0;
}
// Check memo table for precomputed result
if (memo.containsKey(index) &&
memo.get(index).containsKey(diff)) {
return memo.get(index).get(diff);
}
int ans = 0;
// Iterate through previous elements
// to find matching differences
for (int j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr.get(index) - arr.get(j) == diff) {
ans = Math.max(ans,
1 + solve(j, diff, arr, memo));
}
}
// Store the result in the memo table
memo.putIfAbsent(index, new HashMap<>());
memo.get(index).put(diff, ans);
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
static int lengthOfLongestAP(ArrayList<Integer> arr) {
int n = arr.size();
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
int ans = 0;
// Memoization table to store results for solve()
HashMap<Integer, HashMap<Integer, Integer>> memo =
new HashMap<>();
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Calculate difference and find AP
// using memoized recursion
int diff = arr.get(j) - arr.get(i);
ans = Math.max(ans,
2 + solve(i, diff, arr, memo));
}
}
return ans;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(7);
arr.add(10);
arr.add(15);
arr.add(27);
arr.add(29);
System.out.println(lengthOfLongestAP(arr));
}
}
Python
# Python program to find the length of the longest
# arithmetic progression (AP) using recursion
# with memoization
# Function to find the length of AP ending at
# index `index` with difference `diff`
def solve(index, diff, arr, memo):
# Base case: if index goes out of bounds,
# return 0
if index < 0:
return 0
# Check if the result is already computed
if (index, diff) in memo:
return memo[(index, diff)]
ans = 0
# Iterate through previous elements to find
# matching differences
for j in range(index - 1, -1, -1):
# If the difference matches, extend the AP
if arr[index] - arr[j] == diff:
ans = max(ans, 1 + solve(j, diff, arr, memo))
# Store the result in the memo dictionary
memo[(index, diff)] = ans
return ans
# Function to find the length of the longest
# arithmetic progression (AP) in the array
def lengthOfLongestAP(arr):
n = len(arr)
# If there are less than 3 elements,
# return the size
if n <= 2:
return n
ans = 0
# Memoization dictionary to store results for solve
memo = {}
# Iterate through all pairs of elements as
# possible first two terms
for i in range(n):
for j in range(i + 1, n):
# Calculate difference and find AP
# using memoized recursion
diff = arr[j] - arr[i]
ans = max(ans, 2 + solve(i, diff, arr, memo))
return ans
if __name__ == "__main__":
arr = [1, 7, 10, 15, 27, 29]
print(lengthOfLongestAP(arr))
C#
// C# program to find the length of the longest
// arithmetic progression (AP) using recursion
// with memoization
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to find the length of AP
// ending at index `index` with difference `diff`
static int Solve(int index, int diff,
List<int> arr,
Dictionary<(int, int), int> memo) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0) {
return 0;
}
// Check if the result is already computed
if (memo.ContainsKey((index, diff))) {
return memo[(index, diff)];
}
int ans = 0;
// Iterate through previous elements
// to find matching differences
for (int j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr[index] - arr[j] == diff) {
ans = Math.Max(ans,
1 + Solve(j, diff, arr, memo));
}
}
// Store the result in the memo dictionary
memo[(index, diff)] = ans;
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
static int LengthOfLongestAP(List<int> arr) {
int n = arr.Count;
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
int ans = 0;
// Memoization dictionary to store results for Solve
var memo = new Dictionary<(int, int), int>();
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Calculate difference and find AP
// using memoized recursion
int diff = arr[j] - arr[i];
ans = Math.Max(ans,
2 + Solve(i, diff, arr, memo));
}
}
return ans;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 1, 7, 10,
15, 27, 29 };
Console.WriteLine(LengthOfLongestAP(arr));
}
}
JavaScript
// Javascript program to find the length of the longest
// arithmetic progression (AP) using recursion with memoization
// Function to find the length of AP ending at
// index `index` with difference `diff`
function solve(index, diff, arr, memo) {
// Base case: if index goes out of bounds,
// return 0
if (index < 0) {
return 0;
}
// Check if the result is already computed
const key = `${index}-${diff}`;
if (memo[key] !== undefined) {
return memo[key];
}
let ans = 0;
// Iterate through previous elements to find
// matching differences
for (let j = index - 1; j >= 0; j--) {
// If the difference matches, extend the AP
if (arr[index] - arr[j] === diff) {
ans = Math.max(ans,
1 + solve(j, diff, arr, memo));
}
}
// Store the result in the memo object
memo[key] = ans;
return ans;
}
// Function to find the length of the longest
// arithmetic progression (AP) in the array
function lengthOfLongestAP(arr) {
const n = arr.length;
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
let ans = 0;
// Memoization object to store results for solve
const memo = {};
// Iterate through all pairs of elements as
// possible first two terms
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Calculate difference and find AP
// using memoized recursion
const diff = arr[j] - arr[i];
ans = Math.max(ans,
2 + solve(i, diff, arr, memo));
}
}
return ans;
}
const arr = [1, 7, 10, 15, 27, 29];
console.log(lengthOfLongestAP(arr));
Using Bottom-Up DP (Tabulation) - O(n^2) Time and O(n^2) Space
The tabulation approach iteratively builds the solution in a bottom-up manner, avoiding the use of recursion. Instead of solving smaller subproblems recursively, we use a table to store and update solutions for progressively larger subproblems.
We will create a 2D table of size n x diffRange, where dp[i][diff] represents the length of the arithmetic progression (AP) ending at index i with a common difference of diff.
The dynamic programming relation is as follows:
- For each pair of indices (j, i) where j < i: Calculate the common difference: diff = arr[i] - arr[j]
- If there is an AP ending at index j with the same diff: dp[i][diff] = dp[j][diff] + 1
- Otherwise, start a new AP of length 2: dp[i][diff] = 2
C++
// C++ program to find the length of the longest
// arithmetic progression (AP) using tabulation
#include <bits/stdc++.h>
using namespace std;
// Function to find the length of the longest
// arithmetic progression (AP) in the array
int lengthOfLongestAP(vector<int> &arr) {
int n = arr.size();
// If there are less than 3 elements,
// return the size
if (n <= 2)
return n;
int ans = 2;
// Create a 2D dp table where dp[i][j] stores the
// length of the AP ending at indices i and j
vector<unordered_map<int, int>> dp(n);
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
// Calculate the common difference
int diff = arr[i] - arr[j];
// If there's an AP ending at j with this diff,
// extend it; otherwise, start a new AP of length 2
dp[i][diff] = dp[j].count(diff) ? dp[j][diff] + 1 : 2;
// Update the overall maximum length
ans = max(ans, dp[i][diff]);
}
}
return ans;
}
int main() {
vector<int> arr = {1, 7, 10, 15, 27, 29};
cout << lengthOfLongestAP(arr) << endl;
return 0;
}
Java
// Java program to find the length of the longest
// arithmetic progression (AP) using tabulation
import java.util.ArrayList;
import java.util.HashMap;
class GfG {
// Function to find the length of the longest
// arithmetic progression (AP) in the array
static int lengthOfLongestAP(ArrayList<Integer> arr) {
int n = arr.size();
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
int ans = 0;
// Create a 2D HashMap to store the lengths of
// APs ending at each index with a given difference
HashMap<Integer, Integer>[] dp = new HashMap[n];
for (int i = 0; i < n; i++) {
dp[i] = new HashMap<>();
}
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
// Calculate the common difference
int diff = arr.get(i) - arr.get(j);
// Check if this difference was seen before
int length = dp[j].getOrDefault(diff, 1);
// Update the length of the AP ending at index `i`
dp[i].put(diff, length + 1);
// Update the global maximum length
ans = Math.max(ans, dp[i].get(diff));
}
}
return ans;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(7);
arr.add(10);
arr.add(15);
arr.add(27);
arr.add(29);
System.out.println(lengthOfLongestAP(arr));
}
}
Python
# Python program to find the length of the longest
# arithmetic progression (AP) using tabulation
# Function to find the length of the longest
# AP in the array
def lengthOfLongestAP(arr):
n = len(arr)
# If there are less than 3 elements,
# return the size
if n <= 2:
return n
# Create a list of dictionaries to store
# lengths of APs
dp = [{} for _ in range(n)]
ans = 0
# Iterate through all pairs of elements as
# possible first two terms
for i in range(1, n):
for j in range(i):
# Calculate the common difference
diff = arr[i] - arr[j]
# Get the previous length or start with 1
length = dp[j].get(diff, 1)
# Update the length of the AP ending at index `i`
dp[i][diff] = length + 1
# Update the global maximum length
ans = max(ans, dp[i][diff])
return ans
if __name__ == "__main__":
arr = [1, 7, 10, 15, 27, 29]
print(lengthOfLongestAP(arr))
C#
// C# program to find the length of the longest
// arithmetic progression (AP) using tabulation
using System;
using System.Collections.Generic;
class GfG {
// Function to find the length of the longest
// arithmetic progression (AP) in the array
static int LengthOfLongestAP(List<int> arr) {
int n = arr.Count;
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
// Create a list of dictionaries to store
// lengths of APs
var dp = new List<Dictionary<int, int>>();
for (int i = 0; i < n; i++) {
dp.Add(new Dictionary<int, int>());
}
int ans = 0;
// Iterate through all pairs of elements as
// possible first two terms
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
// Calculate the common difference
int diff = arr[i] - arr[j];
// Get the previous length or start with 1
int length = dp[j].ContainsKey(diff)
? dp[j][diff] : 1;
// Update the length of the AP ending
// at index `i`
if (!dp[i].ContainsKey(diff)) {
dp[i][diff] = length + 1;
} else {
dp[i][diff] = Math.Max(dp[i][diff],
length + 1);
}
// Update the global maximum length
ans = Math.Max(ans, dp[i][diff]);
}
}
return ans;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 1, 7, 10,
15, 27, 29 };
Console.WriteLine(LengthOfLongestAP(arr));
}
}
JavaScript
// Javascript program to find the length of the longest
// arithmetic progression (AP) using tabulation
function lengthOfLongestAP(arr) {
const n = arr.length;
// If there are less than 3 elements,
// return the size
if (n <= 2) {
return n;
}
// Create an array of maps to store lengths of APs
const dp = Array.from({ length: n }, () => new Map());
let ans = 0;
// Iterate through all pairs of elements as
// possible first two terms
for (let i = 1; i < n; i++) {
for (let j = 0; j < i; j++) {
// Calculate the common difference
const diff = arr[i] - arr[j];
// Get the previous length or start with 1
const length = dp[j].get(diff) || 1;
// Update the length of the AP ending at index `i`
dp[i].set(diff, Math.max(dp[i].get(diff) || 0, length + 1));
// Update the global maximum length
ans = Math.max(ans, dp[i].get(diff));
}
}
return ans;
}
const arr = [1, 7, 10, 15, 27, 29];
console.log(lengthOfLongestAP(arr));
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