Word formation using concatenation of two dictionary words
Last Updated :
23 Jul, 2025
Given a dictionary find out if given word can be made by two words in the dictionary.
Note: Words in the dictionary must be unique and the word to be formed should not be a repetition of same words that are present in the Trie.
Examples:
Input : dictionary[] = {"news", "abcd", "tree",
"geeks", "paper"}
word = "newspaper"
Output : Yes
We can form "newspaper" using "news" and "paper"
Input : dictionary[] = {"geeks", "code", "xyz",
"forgeeks", "paper"}
word = "geeksforgeeks"
Output : Yes
Input : dictionary[] = {"geek", "code", "xyz",
"forgeeks", "paper"}
word = "geeksforgeeks"
Output : No
The idea is store all words of dictionary in a Trie. We do prefix search for given word. Once we find a prefix, we search for rest of the word.
Algorithm :
1- Store all the words of the dictionary in a Trie.
2- Start searching for the given word in Trie.
If it partially matched then split it into two
parts and then search for the second part in
the Trie.
3- If both found, then return true.
4- Otherwise return false.
Below is the implementation of above idea.
C++
// C++ program to check if a string can be
// formed by concatenating two words
#include<bits/stdc++.h>
using namespace std;
// Converts key current character into index
// use only 'a' through 'z'
#define char_int(c) ((int)c - (int)'a')
// Alphabet size
#define SIZE (26)
// Trie Node
struct TrieNode
{
TrieNode *children[SIZE];
// isLeaf is true if the node represents
// end of a word
bool isLeaf;
};
// Returns new trie node (initialized to NULLs)
TrieNode *getNode()
{
TrieNode * newNode = new TrieNode;
newNode->isLeaf = false;
for (int i =0 ; i< SIZE ; i++)
newNode->children[i] = NULL;
return newNode;
}
// If not present, inserts key into Trie
// If the key is prefix of trie node, just
// mark leaf node
void insert(TrieNode *root, string Key)
{
int n = Key.length();
TrieNode * pCrawl = root;
for (int i=0; i<n; i++)
{
int index = char_int(Key[i]);
if (pCrawl->children[index] == NULL)
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
// make last node as leaf node
pCrawl->isLeaf = true;
}
// Searches a prefix of key. If prefix is present,
// returns its ending position in string. Else
// returns -1.
int findPrefix(struct TrieNode *root, string key)
{
int pos = -1, level;
struct TrieNode *pCrawl = root;
for (level = 0; level < key.length(); level++)
{
int index = char_int(key[level]);
if (pCrawl->isLeaf == true)
pos = level;
if (!pCrawl->children[index])
return pos;
pCrawl = pCrawl->children[index];
}
if (pCrawl != NULL && pCrawl->isLeaf)
return level;
}
// Function to check if word formation is possible
// or not
bool isPossible(struct TrieNode* root, string word)
{
// Search for the word in the trie and
// store its position upto which it is matched
int len = findPrefix(root, word);
// print not possible if len = -1 i.e. not
// matched in trie
if (len == -1)
return false;
// If word is partially matched in the dictionary
// as another word
// search for the word made after splitting
// the given word up to the length it is
// already,matched
string split_word(word, len, word.length()-(len));
int split_len = findPrefix(root, split_word);
// check if word formation is possible or not
return (len + split_len == word.length());
}
// Driver program to test above function
int main()
{
// Let the given dictionary be following
vector<string> dictionary = {"geeks", "forgeeks",
"quiz", "geek"};
string word = "geeksquiz"; //word to be formed
// root Node of trie
TrieNode *root = getNode();
// insert all words of dictionary into trie
for (int i=0; i<dictionary.size(); i++)
insert(root, dictionary[i]);
isPossible(root, word) ? cout << "Yes":
cout << "No";
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
// Java program to check if a string can be
// formed by concatenating two words
public class GFG {
// Alphabet size
final static int SIZE = 26;
// Trie Node
static class TrieNode
{
TrieNode[] children = new TrieNode[SIZE];
// isLeaf is true if the node represents
// end of a word
boolean isLeaf;
// constructor
public TrieNode() {
isLeaf = false;
for (int i =0 ; i< SIZE ; i++)
children[i] = null;
}
}
static TrieNode root;
// If not present, inserts key into Trie
// If the key is prefix of trie node, just
// mark leaf node
static void insert(TrieNode root, String Key)
{
int n = Key.length();
TrieNode pCrawl = root;
for (int i=0; i<n; i++)
{
int index = Key.charAt(i) - 'a';
if (pCrawl.children[index] == null)
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
// make last node as leaf node
pCrawl.isLeaf = true;
}
// Searches a prefix of key. If prefix is present,
// returns its ending position in string. Else
// returns -1.
static List<Integer> findPrefix(TrieNode root, String key)
{
List<Integer> prefixPositions = new ArrayList<Integer>();
int level;
TrieNode pCrawl = root;
for (level = 0; level < key.length(); level++)
{
int index = key.charAt(level) - 'a';
if (pCrawl.isLeaf == true)
prefixPositions.add(level);
if (pCrawl.children[index] == null)
return prefixPositions;
pCrawl = pCrawl.children[index];
}
if (pCrawl != null && pCrawl.isLeaf)
prefixPositions.add(level);
return prefixPositions;
}
// Function to check if word formation is possible
// or not
static boolean isPossible(TrieNode root, String word)
{
// Search for the word in the trie and get its prefix positions
// upto which there is matched
List<Integer> prefixPositions1 = findPrefix(root, word);
// Word formation is not possible if the word did not have
// at least one prefix match
if (prefixPositions1.isEmpty())
return false;
// Search for rest of substring for each prefix match
for (Integer len1 : prefixPositions1) {
String restOfSubstring = word.substring(len1, word.length());
List<Integer> prefixPositions2 = findPrefix(root, restOfSubstring);
for (Integer len2 : prefixPositions2) {
// check if word formation is possible
if (len1 + len2 == word.length())
return true;
}
}
return false;
}
// Driver program to test above function
public static void main(String args[])
{
// Let the given dictionary be following
String[] dictionary = {"news", "newspa", "paper", "geek"};
String word = "newspaper"; //word to be formed
// root Node of trie
root = new TrieNode();
// insert all words of dictionary into trie
for (int i=0; i<dictionary.length; i++)
insert(root, dictionary[i]);
if(isPossible(root, word))
System.out.println( "Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sumit Ghosh
// Updated by Narendra Jha
Python3
class TrieNode:
def __init__(self):
# Initialize a new TrieNode with a list of 26 children and isLeaf flag set to False
self.children = [None]*26
self.isLeaf = False
def charToInt(ch):
# Helper function to convert character to corresponding integer value (0-25)
return ord(ch) - ord('a')
def insert(root, key):
# Insert a new key into the Trie
pCrawl = root
for ch in key:
# Convert character to integer index value
index = charToInt(ch)
# If child node doesn't exist, create one
if not pCrawl.children[index]:
pCrawl.children[index] = TrieNode()
# Move to next child node
pCrawl = pCrawl.children[index]
# Mark the last node as a leaf node
pCrawl.isLeaf = True
def findPrefix(root, key):
# Find the length of the longest prefix of the key that exists in the Trie
pos = -1
pCrawl = root
for i, ch in enumerate(key):
index = charToInt(ch)
if pCrawl.isLeaf:
pos = i
if not pCrawl.children[index]:
return pos
pCrawl = pCrawl.children[index]
return len(key)
def isPossible(root, word):
# Check if it is possible to split the word into two dictionary words
len1 = findPrefix(root, word)
if len1 == -1:
return False
split_word = word[len1:]
len2 = findPrefix(root, split_word)
return len1 + len2 == len(word)
# Driver program to test above function
if __name__ == "__main__":
# Define dictionary and word to test
dictionary = ["geeks", "forgeeks", "quiz", "geek"]
word = "geeksquiz"
# Create root node of Trie
root = TrieNode()
# Insert each dictionary word into the Trie
for key in dictionary:
insert(root, key)
# Check if it is possible to split the word into two dictionary words and print result
print("Yes" if isPossible(root, word) else "No")
C#
// C# program to check if a string can be
// formed by concatenating two words
using System;
using System.Collections.Generic;
class GFG
{
// Alphabet size
readonly public static int SIZE = 26;
// Trie Node
public class TrieNode
{
public TrieNode []children = new TrieNode[SIZE];
// isLeaf is true if the node
// represents end of a word
public bool isLeaf;
// constructor
public TrieNode()
{
isLeaf = false;
for (int i = 0 ; i < SIZE ; i++)
children[i] = null;
}
}
static TrieNode root;
// If not present, inserts key into Trie
// If the key is prefix of trie node, just
// mark leaf node
static void insert(TrieNode root, String Key)
{
int n = Key.Length;
TrieNode pCrawl = root;
for (int i = 0; i < n; i++)
{
int index = Key[i] - 'a';
if (pCrawl.children[index] == null)
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
// make last node as leaf node
pCrawl.isLeaf = true;
}
// Searches a prefix of key. If prefix
// is present, returns its ending position
// in string. Else returns -1.
static List<int> findPrefix(TrieNode root, String key)
{
List<int> prefixPositions = new List<int>();
int level;
TrieNode pCrawl = root;
for (level = 0; level < key.Length; level++)
{
int index = key[level] - 'a';
if (pCrawl.isLeaf == true)
prefixPositions.Add(level);
if (pCrawl.children[index] == null)
return prefixPositions;
pCrawl = pCrawl.children[index];
}
if (pCrawl != null && pCrawl.isLeaf)
prefixPositions.Add(level);
return prefixPositions;
}
// Function to check if word
// formation is possible or not
static bool isPossible(TrieNode root, String word)
{
// Search for the word in the trie
// and get its prefix positions
// upto which there is matched
List<int> prefixPositions1 = findPrefix(root, word);
// Word formation is not possible
// if the word did not have
// at least one prefix match
if (prefixPositions1.Count==0)
return false;
// Search for rest of substring
// for each prefix match
foreach (int len1 in prefixPositions1)
{
String restOfSubstring = word.Substring(len1,
word.Length-len1);
List<int> prefixPositions2 = findPrefix(root,
restOfSubstring);
foreach (int len2 in prefixPositions2)
{
// check if word formation is possible
if (len1 + len2 == word.Length)
return true;
}
}
return false;
}
// Driver code
public static void Main(String []args)
{
// Let the given dictionary be following
String[] dictionary = {"news", "newspa", "paper", "geek"};
// word to be formed
String word = "newspaper";
// root Node of trie
root = new TrieNode();
// insert all words of dictionary into trie
for (int i = 0; i < dictionary.Length; i++)
insert(root, dictionary[i]);
if(isPossible(root, word))
Console.WriteLine( "Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to check if a string
// can be formed by concatenating two words
// Alphabet size
let SIZE = 26;
// Trie Node
class TrieNode
{
constructor()
{
this.isLeaf = false;
this.children = new Array(SIZE);
for(let i = 0 ; i < SIZE; i++)
this.children[i] = null;
}
}
let root;
// If not present, inserts key into Trie
// If the key is prefix of trie node, just
// mark leaf node
function insert(root, Key)
{
let n = Key.length;
let pCrawl = root;
for(let i = 0; i < n; i++)
{
let index = Key[i].charCodeAt(0) -
'a'.charCodeAt(0);
if (pCrawl.children[index] == null)
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
// Make last node as leaf node
pCrawl.isLeaf = true;
}
// Searches a prefix of key. If prefix
// is present, returns its ending
// position in string. Else returns -1.
function findPrefix(root, key)
{
let prefixPositions = [];
let level;
let pCrawl = root;
for(level = 0; level < key.length; level++)
{
let index = key[level].charCodeAt(0) -
'a'.charCodeAt(0);
if (pCrawl.isLeaf == true)
prefixPositions.push(level);
if (pCrawl.children[index] == null)
return prefixPositions;
pCrawl = pCrawl.children[index];
}
if (pCrawl != null && pCrawl.isLeaf)
prefixPositions.push(level);
return prefixPositions;
}
// Function to check if word formation
// is possible or not
function isPossible(root, word)
{
// Search for the word in the trie and
// get its prefix positions upto which
// there is matched
let prefixPositions1 = findPrefix(root, word);
// Word formation is not possible if
// the word did not have at least one
// prefix match
if (prefixPositions1.length == 0)
return false;
// Search for rest of substring for
// each prefix match
for(let len1 = 0;
len1 < prefixPositions1.length;
len1++)
{
let restOfSubstring = word.substring(
prefixPositions1[len1], word.length);
let prefixPositions2 = findPrefix(
root, restOfSubstring);
for(let len2 = 0;
len2 < prefixPositions2.length;
len2++)
{
// Check if word formation is possible
if (prefixPositions1[len1] +
prefixPositions2[len2] == word.length)
return true;
}
}
return false;
}
// Driver code
let dictionary = [ "news", "newspa",
"paper", "geek" ];
// word to be formed
let word = "newspaper";
// Root Node of trie
root = new TrieNode();
// Insert all words of dictionary into trie
for(let i = 0; i < dictionary.length; i++)
insert(root, dictionary[i]);
if (isPossible(root, word))
document.write("Yes");
else
document.write("No");
// This code is contributed by rag2127
</script>
Output:
Yes
Exercise :
A generalized version of the problem is to check if a given word can be formed using concatenation of 1 or more dictionary words. Write code for the generalized version.
Time Complexity: The time complexity of the given program is O(MN), where M is the length of the given word and N is the number of words in the dictionary. This is because the program needs to traverse the given word and perform a prefix search in the trie for each substring of the word, which takes O(M) time. Additionally, the program needs to insert all the words in the dictionary into the trie, which takes O(NM) time.
Auxiliary Space: The space complexity of the program is O(NM), where N is the number of words in the dictionary and M is the maximum length of a word in the dictionary. This is because the program needs to store the trie data structure, which requires O(NM) space.
Another Approach
The above approach is implementing the Trie data structure to efficiently store and search the dictionary words. However, we can optimize the code by using the unordered_set data structure instead of Trie. The unordered_set is a hash-based data structure that has an average constant time complexity O(1) for insertion and search operations. Therefore, it can be used to efficiently search for words in the dictionary.
Approach:
- Check if the given word exists in the dictionary. If it does, return true.
- If the given word is not found in the dictionary, then check if it can be formed by concatenating two or more words from the dictionary recursively.
- To check if a word can be formed by concatenating two or more words from the dictionary, the code splits the word into a prefix and a suffix at every possible position and then checks if the prefix exists in the dictionary.
- If the prefix exists in the dictionary, then the suffix is checked recursively to see if it can be formed by concatenating two or more words from the dictionary. This is done by calling the "isPossible" function recursively with the suffix and the dictionary as input.
- If the suffix can be formed by concatenating two or more words from the dictionary, then the entire word can be formed by concatenating the prefix and suffix. In this case, the function returns true.
- If none of the prefixes can be found in the dictionary, or if none of the suffixes can be formed by concatenating two or more words from the dictionary, then the function returns false.
Algorithm:
This code uses recursion to check whether a given word can be formed by concatenating two words from a given dictionary.
- The function "isPossible" takes two parameters: an unordered_set "dict" containing the dictionary of words and a string word to be checked.
- If the word is found in the dictionary, the function returns true. Otherwise, it recursively checks all possible prefixes and suffixes of the word to see if they can be formed by concatenating two words from the "dict".
- The recursion stops when either the prefix is not found in the dictionary, or the suffix cannot be formed by concatenating two words from the "dict".
- If the word can be formed by concatenating two words from the "dict", the function returns true. Otherwise, it returns false.
- The "main" function creates an "unordered_set" of strings containing the dictionary, and then calls the "isPossible" function to check if the given word can be formed by concatenating two words from the dictionary. Finally, it prints "Yes" if the word can be formed, and "No" otherwise.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if word formation is possible
// or not
bool isPossible(unordered_set<string>& dict, string word)
{
// If word is found in the dictionary, it can be formed
if (dict.find(word) != dict.end())
return true;
// Check if word can be formed by concatenating
// two words from the dictionary
int n = word.length();
for (int i = 1; i < n; i++) {
string prefix = word.substr(0, i);
string suffix = word.substr(i);
// Check if prefix exists in dictionary and
// suffix can be formed by concatenating two
// words from the dictionary recursively
if (dict.find(prefix) != dict.end() && isPossible(dict, suffix))
return true;
}
// Word cannot be formed by concatenating
// two words from the dictionary
return false;
}
// Driver program to test above function
int main()
{
// Let the given dictionary be following
unordered_set<string> dictionary = {"geeks", "forgeeks", "quiz", "geek"};
string word = "geeksquiz"; //word to be formed
isPossible(dictionary, word) ? cout << "Yes" : cout << "No";
return 0;
}
//This code is contributed by rudra1807raj
Java
import java.util.*;
public class WordFormation {
// Function to check if word formation is possible or not
public static boolean isPossible(Set<String> dict, String word) {
// If word is found in the dictionary, it can be formed
if (dict.contains(word))
return true;
// Check if word can be formed by concatenating
// two words from the dictionary
int n = word.length();
for (int i = 1; i < n; i++) {
String prefix = word.substring(0, i);
String suffix = word.substring(i);
// Check if prefix exists in dictionary and
// suffix can be formed by concatenating two
// words from the dictionary recursively
if (dict.contains(prefix) && isPossible(dict, suffix))
return true;
}
// Word cannot be formed by concatenating
// two words from the dictionary
return false;
}
// Driver program to test above function
public static void main(String[] args) {
// Let the given dictionary be following
Set<String> dictionary = new HashSet<String>();
dictionary.add("geeks");
dictionary.add("forgeeks");
dictionary.add("quiz");
dictionary.add("geek");
String word = "geeksquiz"; // word to be formed
System.out.println(isPossible(dictionary, word) ? "Yes" : "No");
}
}
//This code is contributed by rudra1807raj
Python3
# Python Code
# importing the required library
import itertools
# Function to check if word formation is possible or not
def isPossible(dict, word):
# If word is found in the dictionary, it can be formed
if word in dict:
return True
# Check if word can be formed by concatenating
# two words from the dictionary
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
# Check if prefix exists in dictionary and
# suffix can be formed by concatenating two
# words from the dictionary recursively
if prefix in dict and isPossible(dict, suffix):
return True
# Word cannot be formed by concatenating
# two words from the dictionary
return False
# Driver program to test above function
if __name__ == '__main__':
# Let the given dictionary be following
dictionary = {'geeks', 'forgeeks', 'quiz', 'geek'}
word = 'geeksquiz' # word to be formed
if isPossible(dictionary, word):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
public class WordFormation {
// Function to check if word formation is possible or not
public static bool IsPossible(HashSet<string> dict, string word) {
// If word is found in the dictionary, it can be formed
if (dict.Contains(word))
return true;
// Check if word can be formed by concatenating
// two words from the dictionary
int n = word.Length;
for (int i = 1; i < n; i++) {
string prefix = word.Substring(0, i);
string suffix = word.Substring(i);
// Check if prefix exists in dictionary and
// suffix can be formed by concatenating two
// words from the dictionary recursively
if (dict.Contains(prefix) && IsPossible(dict, suffix))
return true;
}
// Word cannot be formed by concatenating
// two words from the dictionary
return false;
}
// Driver program to test above function
public static void Main() {
// Let the given dictionary be following
HashSet<string> dictionary = new HashSet<string>();
dictionary.Add("geeks");
dictionary.Add("forgeeks");
dictionary.Add("quiz");
dictionary.Add("geek");
string word = "geeksquiz"; // word to be formed
Console.WriteLine(IsPossible(dictionary, word) ? "Yes" : "No");
}
}
//This code is contributed by rudra1807raj
JavaScript
function isPossible(dict, word) {
// If word is found in the dictionary, it can be formed
if (dict.has(word)) {
return true;
}
// Check if word can be formed by concatenating
// two words from the dictionary
let n = word.length;
for (let i = 1; i < n; i++) {
let prefix = word.substring(0, i);
let suffix = word.substring(i);
// Check if prefix exists in dictionary and
// suffix can be formed by concatenating two
// words from the dictionary recursively
if (dict.has(prefix) && isPossible(dict, suffix)) {
return true;
}
}
// Word cannot be formed by concatenating
// two words from the dictionary
return false;
}
// Driver program to test above function
let dictionary = new Set(["geeks", "forgeeks", "quiz", "geek"]);
let word = "geeksquiz"; //word to be formed
isPossible(dictionary, word) ? console.log("Yes") : console.log("No");
//Note that the unordered_set used in the C++ code has been replaced with
//a Set in JavaScript. The Set in JavaScript is similar to unordered_set in
//C++ and allows for fast lookup of elements. The substring function in
//JavaScript is used to extract a portion of a string. The console.log function
//is used to print the output.
//This code is contributed by rudra1807raj
Output:
Yes
Time Complexity: The time complexity of the "isPossible" function in this code is O(N^3), where N is the length of the input word. This is because, in the worst case, the function will need to check every possible partition of the word into two parts, which is O(N^2), and for each partition, it may need to recursively check both parts, which can take an additional O(N) time.
Auxiliary Space: The space complexity of this function is also O(N^3) in the worst case, due to the recursion stack. Specifically, in the worst case, the recursion depth will be O(N), and at each level of the recursion, the function may need to store a string of length up to N. Therefore, the overall space complexity is O(N^3).
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