Encode an ASCII string into Base-64 Format
Last Updated :
28 Apr, 2024
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML.
Problem with sending normal binary data to a network is that bits can be misinterpreted by underlying protocols, produce incorrect data at receiving node and that is why we use this code.
Why base 64 ?
Resultant text after encoding our data has those characters which are widely present in many character sets so there is very less chance of data being corrupted or modified.
How to convert into base 64 format ?
The character set in base64 is
char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789+/"
// 64 character
Basic idea:
Lets take an example. We have to encode string "MENON" into base64 format. Lets call "MENON" as input_str, above base64 character set ("ABC..+/") as char_set and resultant encoded string as res_str.
- Take 3 characters from input_str i.e "MEN" since each character size is 8 bits we will have(8 * 3) 24 bits with us.
- Group them in a block of 6 bits each (24 / 6 = 4 blocks). (why 6?) because 2^6 = 64 characters, with 6 bits we can represent each character in char_set.
- Convert each block of 6 bits to its corresponding decimal value. Decimal value obtained is the index of resultant encoded character in char_set.
- So for each 3 characters from input_str we will receive 4 characters in res_str.
- What if we have less than 3 characters in input_str left i.e "ON". We have 16 bits and blocks will be 16 / 6 = 2 blocks. Rightmost 4 bits will not make a proper block (1 block = 6 bits) so we append zeros to right side of block to make it a proper block i.e 2 zeros will be appended to right. Now we have 3 proper blocks, find corresponding decimal value of each block to get index.
- Since There were less than 3 characters ("ON") in input_str we will append "=" in res_str. e.g "ON" here 3 - 2 = 1 padding of "=" in res_str.
Example
1. Convert "MENON" into its (8 bit) binary state format. Take each characters of the string and write its 8 - bit binary representation.
ASCII values of characters in string to be encoded
M : 77 (01001101), E : 69 (01000101),
N : 78 (01001110), O : 79 (01001111), N : 78 (01001110)
resultant binary data of above string is :
01001101 01000101 01001110 01001111 01001110
2. Starting from left make blocks of 6 bits until all bits are covered
BIT-STREAM :
(010011) (010100) (010101) (001110) (010011) (110100) (1110)
3. If the rightmost block is less than 6 bits just append zeros to the right of that block to make it 6 bits. Here in above example we have to appended 2 zeros to make it 6.
BIT-STREAM :
(010011) (010100) (010101) (001110) (010011) (110100) (111000)
Notice the bold zeros.
4. Take 3 characters from input_str ("MEN") i.e 24 bits and find corresponding decimal value (index to char_set).
BLOCKS :
INDEX --> (010011) : 19, (010100) : 20, (010101) : 21, (001110) : 14
char_set[19] = T, char_set[20] = U, char_set[21] = V, char_set[14] = O
So our input_str = "MEN" will be converted to encoded string "TUVO".
5. Take remaining characters ("ON"). We have to pad resultant encoded string with 1 "=" as number of characters is less than 3 in input_str. (3 - 2 = 1 padding)
BLOCKS :
INDEX --> (010011) : 19 (110100) : 52 (111000) : 56
char_set[19] = T char_set[52] = 0 char_set[56] = 4
So our input_str = "ON" will be converted to encoded string "T04=".
Examples:
Input : MENON // string in ASCII
Output :TUVOT04= // encoded string in Base 64.
Input : geeksforgeeks
Output : Z2Vla3Nmb3JnZWVrcw==
Approach :
We can use bitwise operators to encode our string. We can take an integer "val" (usually 4 bytes on most compilers) and store all characters of input_str (3 at a time) in val. The characters from input_str will be stored in val
in form of bits. We will use (OR operator) to store the characters and (LEFT - SHIFT) by 8 so to
make room for another 8 bits. In similar fashion we will use (RIGHT - SHIFT) to retrieve bits from val 6 at a time
and find value of bits by doing & with 63 (111111) which will give us index. Then we can get our resultant character by just going to that index of char_set.
C++
// C++ program to encode an ASCII
// string in Base64 format
#include <iostream>
using namespace std;
#define SIZE 1000
// Takes string to be encoded as input
// and its length and returns encoded string
char* base64Encoder(char input_str[], int len_str)
{
// Character set of base64 encoding scheme
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Resultant string
char *res_str = (char *) malloc(SIZE * sizeof(char));
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
int i, j, k = 0;
// Loop takes 3 characters at a time from
// input_str and stores it in val
for (i = 0; i < len_str; i += 3)
{
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < len_str && j <= i + 2; j++)
{
// binary data of input_str is stored in val
val = val << 8;
// (A + 0 = A) stores character in val
val = val | input_str[j];
// calculates how many time loop
// ran if "MEN" -> 3 otherwise "ON" -> 2
count++;
}
no_of_bits = count * 8;
// calculates how many "=" to append after res_str.
padding = no_of_bits % 3;
// extracts all bits from val (6 at a time)
// and find the value of each block
while (no_of_bits != 0)
{
// retrieve the value of each block
if (no_of_bits >= 6)
{
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
}
else
{
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
// padding is done here
for (i = 1; i <= padding; i++)
{
res_str[k++] = '=';
}
res_str[k] = '\0';
return res_str;
}
// Driver code
int main()
{
char input_str[] = "MENON";
int len_str;
// calculates length of string
len_str = sizeof(input_str) / sizeof(input_str[0]);
// to exclude '\0' character
len_str -= 1;
cout <<"Input string is : "<< input_str << endl;
cout <<"Encoded string is : "<< base64Encoder(input_str, len_str)<< endl;
return 0;
}
// This code is contributed by shivanisinghss2110
C
// C program to encode an ASCII
// string in Base64 format
#include <stdio.h>
#include <stdlib.h>
#define SIZE 1000
// Takes string to be encoded as input
// and its length and returns encoded string
char* base64Encoder(char input_str[], int len_str)
{
// Character set of base64 encoding scheme
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Resultant string
char *res_str = (char *) malloc(SIZE * sizeof(char));
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
int i, j, k = 0;
// Loop takes 3 characters at a time from
// input_str and stores it in val
for (i = 0; i < len_str; i += 3)
{
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < len_str && j <= i + 2; j++)
{
// binary data of input_str is stored in val
val = val << 8;
// (A + 0 = A) stores character in val
val = val | input_str[j];
// calculates how many time loop
// ran if "MEN" -> 3 otherwise "ON" -> 2
count++;
}
no_of_bits = count * 8;
// calculates how many "=" to append after res_str.
padding = no_of_bits % 3;
// extracts all bits from val (6 at a time)
// and find the value of each block
while (no_of_bits != 0)
{
// retrieve the value of each block
if (no_of_bits >= 6)
{
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
}
else
{
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
// padding is done here
for (i = 1; i <= padding; i++)
{
res_str[k++] = '=';
}
res_str[k] = '\0';
return res_str;
}
// Driver code
int main()
{
char input_str[] = "MENON";
int len_str;
// calculates length of string
len_str = sizeof(input_str) / sizeof(input_str[0]);
// to exclude '\0' character
len_str -= 1;
printf("Input string is : %s\n", input_str);
printf("Encoded string is : %s\n", base64Encoder(input_str, len_str));
return 0;
}
Java
public class Main {
// Takes string to be encoded as input
// and its length and returns encoded string
public static String base64Encoder(char[] input_str, int len_str) {
// Character set of base64 encoding scheme
char[] char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
// Resultant string
StringBuilder res_str = new StringBuilder();
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
// Loop takes 3 characters at a time from
// input_str and stores it in val
for (int i = 0; i < len_str; i += 3) {
val = 0;
count = 0;
no_of_bits = 0;
for (int j = i; j < len_str && j <= i + 2; j++) {
// binary data of input_str is stored in val
val = val << 8;
// (A + 0 = A) stores character in val
val = val | input_str[j];
// calculates how many times loop ran
// if "MEN" -> 3 otherwise "ON" -> 2
count++;
}
no_of_bits = count * 8;
// calculates how many "=" to append after res_str.
padding = no_of_bits % 3;
// extracts all bits from val (6 at a time)
// and find the value of each block
while (no_of_bits != 0) {
// retrieve the value of each block
if (no_of_bits >= 6) {
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
} else {
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str.append(char_set[index]);
}
}
// padding is done here
for (int i = 1; i <= padding; i++) {
res_str.append('=');
}
return res_str.toString();
}
// Driver code
public static void main(String[] args) {
char[] input_str = "MENON".toCharArray();
int len_str;
// calculates length of string
len_str = input_str.length;
// Input string is : MENON
System.out.println("Input string is : " + new String(input_str));
// Encoded string is : TUVO T04=
System.out.println("Encoded string is : " + base64Encoder(input_str, len_str));
}
}
//tHIS CODE IS CONTRIBUTED BY kishan.
Python3
import base64
# Function to encode an ASCII string into Base64 format
def base64Encoder(input_str):
# Character set of base64 encoding scheme
char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
# Resultant string
res_str = ""
# Loop over input string taking 3 characters at a time
for i in range(0, len(input_str), 3):
val = 0
count = 0
# Loop over characters within the 3-character block
for j in range(i, min(i + 3, len(input_str))):
# Store binary data of input_str in val
val = val << 8
# Store the character in val
val = val | ord(input_str[j])
count += 1
# Calculate number of bits
no_of_bits = count * 8
# Calculate padding
padding = no_of_bits % 3
# Extract all bits from val (6 at a time) and find the value of each block
while no_of_bits != 0:
if no_of_bits >= 6:
temp = no_of_bits - 6
index = (val >> temp) & 63
no_of_bits -= 6
else:
temp = 6 - no_of_bits
index = (val << temp) & 63
no_of_bits = 0
res_str += char_set[index]
# Add padding if necessary
for i in range(padding):
res_str += '='
return res_str
# Driver code
if __name__ == "__main__":
input_str = "MENON"
print("Input string is:", input_str)
print("Encoded string is:", base64Encoder(input_str))
#this code is contributed by Adarsh
C#
using System;
using System.Text;
public class MainClass {
// Function to encode an ASCII string into Base64 format
public static string Base64Encoder(string inputStr) {
// Character set of base64 encoding scheme
string charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Resultant string
string resStr = "";
// Loop over input string taking 3 characters at a time
for (int i = 0; i < inputStr.Length; i += 3) {
int val = 0;
int count = 0;
// Loop over characters within the 3-character block
for (int j = i; j < Math.Min(i + 3, inputStr.Length); j++) {
// Store binary data of inputStr in val
val = val << 8;
// Store the character in val
val = val | (int)inputStr[j];
count++;
}
// Calculate number of bits
int noOfBits = count * 8;
// Calculate padding
int padding = noOfBits % 3;
// Extract all bits from val (6 at a time) and find the value of each block
while (noOfBits != 0) {
int index;
if (noOfBits >= 6) {
int temp = noOfBits - 6;
index = (val >> temp) & 63;
noOfBits -= 6;
} else {
int temp = 6 - noOfBits;
index = (val << temp) & 63;
noOfBits = 0;
}
resStr += charSet[index];
}
// Add padding if necessary
for (int k = 0; k < padding; k++) {
resStr += '=';
}
}
return resStr;
}
// Driver code
public static void Main (string[] args) {
string inputStr = "MENON";
Console.WriteLine("Input string is: " + inputStr);
Console.WriteLine("Encoded string is: " + Base64Encoder(inputStr));
}
}
//this code is contributed by Utkarsh
JavaScript
// JavaScript program to encode an ASCII string in Base64 format
// Takes string to be encoded as input and its length and returns encoded string
function base64Encoder(input_str) {
// Character set of base64 encoding scheme
const char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Resultant string
let res_str = "";
let index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
let i, j, k = 0;
// Loop takes 3 characters at a time from input_str and stores it in val
for (i = 0; i < input_str.length; i += 3) {
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < input_str.length && j <= i + 2; j++) {
// binary data of input_str is stored in val
val = val << 8;
// (A + 0 = A) stores character in val
val = val | input_str.charCodeAt(j);
// calculates how many time loop ran if "MEN" -> 3 otherwise "ON" -> 2
count++;
}
no_of_bits = count * 8;
// calculates how many "=" to append after res_str.
padding = no_of_bits % 3;
// extracts all bits from val (6 at a time) and find the value of each block
while (no_of_bits != 0) {
// retrieve the value of each block
if (no_of_bits >= 6) {
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
} else {
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str += char_set[index];
}
}
// padding is done here
for (i = 1; i <= padding; i++) {
res_str += '=';
}
return res_str;
}
// Driver code
function main() {
const input_str = "MENON";
console.log("Input string is : " + input_str);
console.log("Encoded string is : " + base64Encoder(input_str));
}
// Call the main function
main();
OutputInput string is : MENON
Encoded string is : TUVOT04=
Time Complexity: O(2 * N) inserting bits into val + retrieving bits form val
Space Complexity: O(N) where N is the size of the input string
Python Solution:
C++
#include <cstring>
#include <iostream>
using namespace std;
#define SIZE 1000
// Function to encode an ASCII string into Base64 format
char* base64Encoder(char input_str[], int len_str)
{
// Define the character set for Base64 encoding
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"
"klmnopqrstuvwxyz0123456789+/";
// Initialize the result string
char* res_str = new char[SIZE];
int index, no_of_bits = 0, padding = 0, val = 0,
count = 0, temp;
int k = 0;
// Loop to process input string in chunks of 3
// characters
for (int i = 0; i < len_str; i += 3) {
val = 0, count = 0, no_of_bits = 0;
// Process 3 characters at a time
for (int j = i; j < len_str && j <= i + 2; j++) {
// Convert characters to their binary
// representation and store in val
val = val << 8;
val = val | input_str[j];
count++;
}
// Calculate the total number of bits and padding
// required
no_of_bits = count * 8;
padding = no_of_bits % 3;
// Process each 6-bit chunk and map it to its
// corresponding Base64 character
while (no_of_bits != 0) {
if (no_of_bits >= 6) {
temp = no_of_bits - 6;
index = (val >> temp) & 63;
no_of_bits -= 6;
}
else {
temp = 6 - no_of_bits;
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
// Add padding characters ('=') if necessary
for (int i = 1; i <= padding; i++) {
res_str[k++] = '=';
}
// Null-terminate the result string
res_str[k] = '\0';
// Return the encoded string
return res_str;
}
// Main function
int main()
{
// Input string
char input_str[] = "MENON";
int len_str = strlen(input_str);
// Display the input string
cout << "Input string is: " << input_str << endl;
// Encode the input string into Base64 format
char* encoded_str = base64Encoder(input_str, len_str);
// Display the encoded string
cout << "Encoded string is: " << encoded_str << endl;
// Free the dynamically allocated memory
delete[] encoded_str;
return 0;
}
// this code is contributed by Utkarsh
Java
import java.util.*;
public class Main {
static final int SIZE = 1000;
// Function to encode an ASCII string into Base64 format
static char[] base64Encoder(char[] input_str,
int len_str)
{
// Define the character set for Base64 encoding
char[] char_set
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
// Initialize the result string
char[] res_str = new char[SIZE];
int index, no_of_bits = 0, padding = 0, val = 0,
count = 0, temp;
int k = 0;
// Loop to process input string in chunks of 3
// characters
for (int i = 0; i < len_str; i += 3) {
val = 0;
count = 0;
no_of_bits = 0;
// Process 3 characters at a time
for (int j = i; j < len_str && j <= i + 2;
j++) {
// Convert characters to their binary
// representation and store in val
val = val << 8;
val = val | input_str[j];
count++;
}
// Calculate the total number of bits and
// padding required
no_of_bits = count * 8;
padding = no_of_bits % 3;
// Process each 6-bit chunk and map it to its
// corresponding Base64 character
while (no_of_bits != 0) {
if (no_of_bits >= 6) {
temp = no_of_bits - 6;
index = (val >> temp) & 63;
no_of_bits -= 6;
}
else {
temp = 6 - no_of_bits;
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
// Add padding characters ('=') if necessary
for (int i = 1; i <= padding; i++) {
res_str[k++] = '=';
}
// Null-terminate the result string
res_str[k] = '\0';
// Return the encoded string
return res_str;
}
// Main function
public static void main(String[] args)
{
// Input string
char[] input_str = "MENON".toCharArray();
int len_str = input_str.length;
// Display the input string
System.out.println("Input string is: "
+ String.valueOf(input_str));
// Encode the input string into Base64 format
char[] encoded_str
= base64Encoder(input_str, len_str);
// Display the encoded string
System.out.println("Encoded string is: "
+ String.valueOf(encoded_str));
// No need to free memory in Java (Garbage
// Collection takes care of it)
}
}
// this code is contributed by Adarsh
Python3
import base64
def base64_encoder(input_str):
# Encode the input string using base64 encoding
encoded_bytes = base64.b64encode(input_str.encode())
# Decode the bytes and convert to string
encoded_str = encoded_bytes.decode()
return encoded_str
def main():
input_str = "MENON"
print("Input string is:", input_str)
encoded_str = base64_encoder(input_str)
print("Encoded string is:", encoded_str)
if __name__ == "__main__":
main()
JavaScript
// Function to encode an ASCII string into Base64 format
function base64Encoder(input_str) {
// Define the character set for Base64 encoding
const char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Initialize variables
let res_str = ""; // Result string
let index, no_of_bits = 0, padding = 0, val = 0, count = 0;
// Loop to process input string in chunks of 3 characters
for (let i = 0; i < input_str.length; i += 3) {
val = 0, count = 0, no_of_bits = 0;
// Process 3 characters at a time
for (let j = i; j < input_str.length && j <= i + 2; j++) {
// Convert characters to their binary representation and store in val
val = val << 8;
val = val | input_str.charCodeAt(j);
count++;
}
// Calculate the total number of bits and padding required
no_of_bits = count * 8;
padding = no_of_bits % 3;
// Process each 6-bit chunk and map it to its corresponding Base64 character
while (no_of_bits !== 0) {
if (no_of_bits >= 6) {
const temp = no_of_bits - 6;
index = (val >> temp) & 63;
no_of_bits -= 6;
} else {
const temp = 6 - no_of_bits;
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str += char_set[index];
}
}
// Add padding characters ('=') if necessary
for (let i = 1; i <= padding; i++) {
res_str += '=';
}
// Return the encoded string
return res_str;
}
// Main function
function main() {
// Input string
const input_str = "MENON";
// Display the input string
console.log("Input string is: " + input_str);
// Encode the input string into Base64 format
const encoded_str = base64Encoder(input_str);
// Display the encoded string
console.log("Encoded string is: " + encoded_str);
}
// Call the main function to execute the program
main();
//this code is contributed by Prachi.
OutputInput string is: MENON
Encoded string is: TUVOT04=
Exercise : Implement a base 64 decoder
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