2 Sum - Find a pair with given sum
Last Updated :
23 Jul, 2025
Given an array of integers arr[] and an integer target, print a pair of two numbers such that they add up to target. You cannot use the same element twice.
Examples:
Input: arr[] = {2, 9, 10, 4, 15}, target = 12
Output: {2, 10}
Explanation: As sum of 2 and 10 is equal to 12.
Input: arr[] = {3, 2, 4}, target = 8
Output: { }
Explanation: As no such pair exist whose sum is equal to 8, so return empty array
[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space
The idea is to check every possible pair of elements in the array to see if their sum equals the target value. This can be implemented using nested for loops, outer loop for first element and inner loop for second element of the pair. If sum of current two elements is equal to target then return this pair.
C++
// C++ program to find two numbers of array
// such that they add up to target.
#include <iostream>
#include <vector>
using namespace std;
// function to find two sum pair
vector<int> twoSum(vector<int>& arr, int target) {
vector<int> res;
// Check all possible pairs
for(int i = 0; i < arr.size(); i++) {
for(int j = i+1; j < arr.size(); j++) {
// If sum of current pair is equal
// to target then copy it to result
if(arr[i] + arr[j] == target) {
res.push_back(arr[i]);
res.push_back(arr[j]);
return res;
}
}
}
return res;
}
int main() {
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find two numbers of array
// such that they add up to target.
#include <stdio.h>
// Function to find two sum pair
int* twoSum(int arr[], int n, int target, int* resSize) {
int* res = (int*)malloc(2 * sizeof(int));
// Check all possible pairs
for(int i = 0; i < n - 1; i++) {
for(int j = i + 1; j < n; j++) {
// If sum of current pair is equal
// to target then copy it to result
if(arr[i] + arr[j] == target) {
res[0] = arr[i];
res[1] = arr[j];
*resSize = 2;
return res;
}
}
}
return res;
}
int main() {
int arr[] = {2, 9, 10, 4, 15};
int n = sizeof(arr)/sizeof(arr[0]);
int target = 12;
int resSize = 0;
int* res = twoSum(arr, n, target, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find two numbers of array
// such that they add up to target.
import java.util.List;
import java.util.ArrayList;
class GfG {
// function to find two sum pair
static int[] twoSum(int[] arr, int target) {
int[] res = {};
// Check all possible pairs
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
// If sum of current pair is equal
// to target then copy it to result
if (arr[i] + arr[j] == target) {
res = new int[2];
res[0] = arr[i];
res[1] = arr[j];
return res;
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
int[] res = twoSum(arr, target);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Python program to find two numbers of array
# such that they add up to target
def twoSum(arr, target):
res = []
# Check all possible pairs
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
# If sum of current pair is equal
# to target then copy it to result
if arr[i] + arr[j] == target:
res = [arr[i], arr[j]]
return res
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for x in res:
print(x, end=" ")
C#
// C# program to find two numbers of array
// such that they add up to target.
using System;
class GfG {
static int[] twoSum(int[] arr, int target) {
int[] res = { };
// Check all possible pairs
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
// If sum of current pair is equal
// to target then copy it to result
if (arr[i] + arr[j] == target) {
res = new int[] {arr[i], arr[j]};
return res;
}
}
}
return res;
}
static void Main() {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
int[] res = twoSum(arr, target);
foreach (int x in res) {
Console.Write(x + " ");
}
}
}
JavaScript
// JavaScript program to find two numbers of array
// such that they add up to target.
function twoSum(arr, target) {
let res = [ ];
// Check all possible pairs
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
// If sum of current pair is equal
// to target then copy it to result
if (arr[i] + arr[j] === target) {
res = [arr[i], arr[j]];
return res;
}
}
}
return res;
}
let arr = [2, 9, 10, 4, 15];
let target = 12;
let res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n^2), as we are generating all the pairs using two nested loops.
Auxiliary Space: O(1)
[Better Approach 1] Sorting and Binary Search – O(n*log(n)) Time and O(1) Space
We can also solve this problem using binary search. The idea is to sort the array and for each number, we calculate its complement ( target - current number ) and then use binary search to check if the complement exists in the remaining elements of the array. If a valid pair is found, we return it. Otherwise, we return empty array.
C++
// C++ program to find pair with given sum
// using sorting and binary search
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to perform binary search
int binarySearch(vector<int> &arr, int lo, int hi, int target) {
while (lo <= hi){
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
vector<int> twoSum(vector<int> &arr, int target) {
int n = arr.size();
vector<int> res = { };
sort(arr.begin(), arr.end());
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res.push_back(arr[i]);
res.push_back(arr[idx]);
break;
}
}
return res;
}
int main() {
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find pair with given sum
// using sorting and binary search
#include <stdio.h>
// Function to perform binary search
int binarySearch(int arr[], int lo, int hi, int target) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Comparison function for qsort
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
int* twoSum(int arr[], int n, int target, int* resSize) {
int* res = (int*)malloc(2 * sizeof(int));
*resSize = 0;
// Sorting the array using qsort
qsort(arr, n, sizeof(int), compare);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res[0] = arr[i];
res[1] = arr[idx];
*resSize = 2;
break;
}
}
return res;
}
int main() {
int arr[] = {2, 9, 10, 4, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 12;
int resSize;
int* res = twoSum(arr, n, target, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find pair with given sum
// using sorting and binary search
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to perform binary search
static int binarySearch(int[] arr, int lo, int hi, int target) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<Integer> twoSum(int[] arr, int target) {
int n = arr.length;
List<Integer> res = new ArrayList<>();
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res.add(arr[i]);
res.add(arr[idx]);
break;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
List<Integer> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python program to find pair with given sum
# using sorting and binary search
# Function to perform binary search
def binarySearch(arr, lo, hi, target):
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
# Function to check whether any pair exists
# whose sum is equal to the given target value
def twoSum(arr, target):
n = len(arr)
res = []
arr.sort()
for i in range(n):
complement = target - arr[i]
# Use binary search to find the complement
idx = binarySearch(arr, i + 1, n - 1, complement)
if idx != -1:
res.append(arr[i])
res.append(arr[idx])
break
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for x in res:
print(x, end=" ")
C#
// C# program to find pair with given sum
// using sorting and binary search
using System;
using System.Collections.Generic;
class GfG {
// Function to perform binary search
static int binarySearch(int[] arr, int lo, int hi, int target) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<int> twoSum(int[] arr, int target) {
int n = arr.Length;
List<int> res = new List<int>();
Array.Sort(arr);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res.Add(arr[i]);
res.Add(arr[idx]);
break;
}
}
return res;
}
static void Main() {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
List<int> res = twoSum(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find pair with given sum
// using sorting and binary search
// Function to perform binary search
function binarySearch(arr, lo, hi, target) {
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (arr[mid] === target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
function twoSum(arr, target) {
const n = arr.length;
const res = [];
arr.sort((a, b) => a - b);
for (let i = 0; i < n; i++) {
const complement = target - arr[i];
// Use binary search to find the complement
const idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx !== -1) {
res.push(arr[i]);
res.push(arr[idx]);
break;
}
}
return res;
}
const arr = [2, 9, 10, 4, 15];
const target = 12;
const res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n*log(n)), for sorting the array.
Auxiliary Space: O(1)
[Better Approach 2] Sorting and Two Pointers – O(n*log(n)) Time and O(1) Space
The approach involves using the two pointer technique, which requires the array to be sorted first. After sorting, we can set one pointer at the beginning (left) and another at the end (right) of the array. We then check the sum of the elements at these two pointers:
- If sum < target, move left pointer to the right to increase the sum.
- If sum > target, move right pointer to the left to decrease the sum.
- If sum == target, we've found the pair.
C++
// C++ program to find pair with given sum
// using sorting and two pointers
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to check whether any pair exists
// whose sum is equal to the given target value
vector<int> twoSum(vector<int> &arr, int target){
vector<int> res = {};
// Sort the array
sort(arr.begin(), arr.end());
int left = 0, right = arr.size() - 1;
// Iterate while left pointer is less than right
while (left < right){
int sum = arr[left] + arr[right];
// Check if the sum matches the target
if (sum == target) {
res = {arr[left], arr[right]};
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
int main(){
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find pair with given sum
// using sorting and two pointers
#include <stdio.h>
// Function to compare two integers for qsort
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
int* twoSum(int *arr, int size, int target, int *resSize) {
*resSize = 0;
qsort(arr, size, sizeof(int), compare);
int left = 0, right = size - 1;
while (left < right) {
int sum = arr[left] + arr[right];
// Check if the sum matches the target
if (sum == target) {
static int res[2];
res[0] = arr[left];
res[1] = arr[right];
*resSize = 2;
return res;
}
else if (sum < target)
left++;
else
right--;
}
// No pair found
return NULL;
}
int main() {
int arr[] = {2, 9, 10, 4, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 12;
int resSize;
int *res = twoSum(arr, n, target, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find pair with given sum
// using sorting and two pointers
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<Integer> twoSum(int[] arr, int target) {
List<Integer> res = new ArrayList<>();
Arrays.sort(arr);
int left = 0, right = arr.length - 1;
// Iterate while left pointer is less than right
while (left < right) {
int sum = arr[left] + arr[right];
// Check if the sum matches the target
if (sum == target) {
res.add(arr[left]);
res.add(arr[right]);
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
List<Integer> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python program to find pair with given sum
# using sorting and two pointers
# Function to check whether any pair exists
# whose sum is equal to the given target value
def twoSum(arr, target):
res = []
arr.sort()
left = 0
right = len(arr) - 1
# Iterate while left pointer is less than right
while left < right:
sum = arr[left] + arr[right]
# Check if the sum matches the target
if sum == target:
res = [arr[left], arr[right]]
break
elif sum < target:
left += 1
else:
right -= 1
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for x in res:
print(x, end=" ")
C#
// C# program to find pair with given sum
// using sorting and two pointers
using System;
using System.Collections.Generic;
class GfG {
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<int> twoSum(List<int> arr, int target) {
List<int> res = new List<int>();
arr.Sort();
int left = 0, right = arr.Count - 1;
// Iterate while left pointer is less than right
while (left < right) {
int sum = arr[left] + arr[right];
// Check if the sum matches the target
if (sum == target) {
res.Add(arr[left]);
res.Add(arr[right]);
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> {2, 9, 10, 4, 15};
int target = 12;
List<int> res = twoSum(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find pair with given sum
// using sorting and two pointers
// Function to check whether any pair exists
// whose sum is equal to the given target value
function twoSum(arr, target) {
let res = [];
arr.sort((a, b) => a - b);
let left = 0, right = arr.length - 1;
// Iterate while left pointer is less than right
while (left < right) {
let sum = arr[left] + arr[right];
// Check if the sum matches the target
if (sum === target) {
res = [arr[left], arr[right]];
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
const arr = [2, 9, 10, 4, 15];
const target = 12;
const res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n*log(n)), for sorting the array
Auxiliary Space: O(1)
[Expected Approach] Using Hash Set – O(n) Time and O(n) Space
The idea is to store each number in hash set while iterating over the elements. For each element, we calculate its complement (i.e., target – current number) and check if this complement exists in the set. If it does, we have found the pair with sum equal to target.
C++
// C++ program to find pair with given sum
// using HashSet
#include <bits/stdc++.h>
using namespace std;
// Function to find a pair whose sum is equal to
// the given target value
vector<int> twoSum(vector<int> &arr, int target){
vector<int> res = { };
unordered_set<int> st;
for (int i = 0; i < arr.size(); i++){
// Calculate the complement such that
// arr[i] + complement = target
int complement = target - arr[i];
// Check if the complement exists in the set
if (st.find(complement) != st.end()){
res.push_back(complement);
res.push_back(arr[i]);
break;
}
// Add the current element to the set
st.insert(arr[i]);
}
return res;
}
int main(){
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
// Java program to find pair with given sum
// using HashSet
import java.util.HashSet;
class GfG {
// Function to find a pair whose sum is equal to
// the given target value
static int[] twoSum(int[] arr, int target) {
int[] res = new int[2];
HashSet<Integer> st = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
// Calculate the complement such that
// arr[i] + complement = target
int complement = target - arr[i];
// Check if the complement exists in the set
if (st.contains(complement)) {
res[0] = complement;
res[1] = arr[i];
return res;
}
// Add the current element to the set
st.add(arr[i]);
}
return new int[0];
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
int[] res = twoSum(arr, target);
for (int i = 0; i < res.length; i++) {
if (res.length > 0) {
System.out.print(res[i] + " ");
}
}
}
}
Python
# Python program to find pair with given sum
# using HashSet
# Function to find a pair whose sum is equal to
# the given target value
def twoSum(arr, target):
res = []
st = set()
for i in range(len(arr)):
# Calculate the complement such that
# arr[i] + complement = target
complement = target - arr[i]
# Check if the complement exists in the set
if complement in st:
res.append(complement)
res.append(arr[i])
break
# Add the current element to the set
st.add(arr[i])
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for i in range(len(res)):
print(res[i], end=" ")
C#
// C# program to find pair with given sum
// using HashSet
using System;
using System.Collections.Generic;
class GfG {
// Function to find a pair whose sum is equal to
// the given target value
static List<int> twoSum(List<int> arr, int target) {
List<int> res = new List<int>();
HashSet<int> st = new HashSet<int>();
for (int i = 0; i < arr.Count; i++) {
// Calculate the complement such that
// arr[i] + complement = target
int complement = target - arr[i];
// Check if the complement exists in the set
if (st.Contains(complement)) {
res.Add(complement);
res.Add(arr[i]);
break;
}
// Add the current element to the set
st.Add(arr[i]);
}
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> {2, 9, 10, 4, 15};
int target = 12;
List<int> res = twoSum(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find pair with given sum
// using HashSet
// Function to find a pair whose sum is equal to
// the given target value
function twoSum(arr, target) {
let res = [];
let st = new Set();
for (let i = 0; i < arr.length; i++) {
// Calculate the complement such that
// arr[i] + complement = target
let complement = target - arr[i];
// Check if the complement exists in the set
if (st.has(complement)) {
res.push(complement);
res.push(arr[i]);
break;
}
// Add the current element to the set
st.add(arr[i]);
}
return res;
}
const arr = [2, 9, 10, 4, 15];
const target = 12;
const res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n), for single iteration over the array
Auxiliary Space: O(n) as we are using hash set to store the elements.
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