Prerequisite: Dictionaries in Python
A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse sorting by values are discussed.
Using lambda function along with items() and sorted(): The lambda function returns the key(0th element) for a specific item tuple, When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary. keys() method returns a view object that displays a list of all the keys in the dictionary. sorted() is used to sort the keys of the dictionary.
Examples:
Input: my_dict = {2: 'three', 1: 'two'}
Output: [(2, 'three'), (1, 'two')]
Below is the implementation using lambda function:
C++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
// Initialize a map (equivalent to HashMap in Java)
std::map<int, std::string> myMap;
myMap[2] = "three";
myMap[1] = "two";
// Sort the map by value
std::vector<std::pair<int, std::string>> sortedVector(myMap.begin(), myMap.end());
// Use a lambda function for sorting based on the string values
std::sort(sortedVector.begin(), sortedVector.end(),
[](const std::pair<int, std::string>& kv1, const std::pair<int, std::string>& kv2) {
return kv1.second < kv2.second;
});
// Print the sorted dictionary (map)
std::cout << "Sorted dictionary is: [";
for (size_t i = 0; i < sortedVector.size(); i++) {
std::cout << "(" << sortedVector[i].first << ", '" << sortedVector[i].second << "')";
if (i < sortedVector.size() - 1) {
std::cout << ", ";
}
}
std::cout << "]" << std::endl;
return 0;
}
Java
// Java program to sort dictionary by value using lambda function
import java.util.*;
class Main {
public static void main(String[] args) {
// Initialize a HashMap
HashMap<Integer, String> myMap = new HashMap<Integer, String>();
myMap.put(2, "three");
myMap.put(1, "two");
// Sort the HashMap by value
List<Map.Entry<Integer, String>> sortedList = new ArrayList<Map.Entry<Integer, String>>(myMap.entrySet());
Collections.sort(sortedList, (kv1, kv2) -> kv1.getValue().compareTo(kv2.getValue()));
// Print sorted dictionary
System.out.print("Sorted dictionary is : ");
for (Map.Entry<Integer, String> entry : sortedList) {
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
}
}
Python
# Python program to sort dictionary
# by value using lambda function
# Initialize a dictionary
my_dict = {2: 'three',
1: 'two'}
# Sort the dictionary
sorted_dict = sorted(
my_dict.items(),
key = lambda kv: kv[1])
# Print sorted dictionary
print("Sorted dictionary is :",
sorted_dict)
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// Initialize a Dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
myDictionary.Add(2, "three");
myDictionary.Add(1, "two");
// Sort the Dictionary by value
var sortedList = myDictionary.OrderBy(kv => kv.Value).ToList();
// Print sorted dictionary in the requested format
Console.Write("Sorted dictionary is : [");
for (int i = 0; i < sortedList.Count; i++)
{
var entry = sortedList[i];
Console.Write($"({entry.Key}, '{entry.Value}')");
if (i < sortedList.Count - 1)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
JavaScript
// Javascript program for the above approach
// Initialize a dictionary
let my_dict = {2: 'three', 1: 'two'};
// Sort the dictionary by value using lambda function
let sorted_dict = Object.entries(my_dict).sort((a, b) => a[1].localeCompare(b[1]));
// Print sorted dictionary
console.log("Sorted dictionary is :", sorted_dict);
// This code is contributed by rishab
OutputSorted dictionary is: [(2, 'three'), (1, 'two')]
The time complexity of this program is O(n log n), where n is the size of the dictionary.
The space complexity is O(n), where n is the size of the dictionary.
Using items() alone: The method items() is used alone with two variables i.e., key and value to sort the dictionary by value.
Examples:
Input: my_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}
Output: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
Below is the implementation using method items():
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
int main() {
// Initialize a dictionary
std::map<char, int> my_dict = {
{'c', 3},
{'a', 1},
{'d', 4},
{'b', 2}
};
// Sorting dictionary
std::vector<std::pair<int, char>> sorted_dict;
for (const auto& pair : my_dict) {
sorted_dict.emplace_back(pair.second, pair.first);
}
std::sort(sorted_dict.begin(), sorted_dict.end());
// Print sorted dictionary
std::cout << "Sorted dictionary is :" << std::endl;
for (const auto& pair : sorted_dict) {
std::cout << '(' << pair.first << ", " << pair.second << ") ";
}
std::cout << std::endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Initialize a dictionary
TreeMap<Character, Integer> my_dict
= new TreeMap<>();
my_dict.put('c', 3);
my_dict.put('a', 1);
my_dict.put('d', 4);
my_dict.put('b', 2);
// Sorting dictionary
List<Map.Entry<Character, Integer> > sorted_dict
= new ArrayList<>(my_dict.entrySet());
Collections.sort(
sorted_dict,
Comparator.comparing(Map.Entry::getValue));
// Print sorted dictionary
System.out.println("Sorted dictionary is :");
for (Map.Entry<Character, Integer> entry :
sorted_dict) {
System.out.print("(" + entry.getValue() + ", "
+ entry.getKey() + ") ");
}
System.out.println();
}
}
// This code is contributed by Susobhan Akhuli
Python
# Python program to sort dictionary
# by value using item function
# Initialize a dictionary
my_dict = {'c': 3,
'a': 1,
'd': 4,
'b': 2}
# Sorting dictionary
sorted_dict = sorted([(value, key)
for (key, value) in my_dict.items()])
# Print sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Initialize a dictionary
Dictionary<char, int> myDict = new Dictionary<char, int>
{
{'c', 3},
{'a', 1},
{'d', 4},
{'b', 2}
};
// Sorting dictionary
List<KeyValuePair<int, char>> sortedDict = myDict
.Select(pair => new KeyValuePair<int, char>(pair.Value, pair.Key))
.OrderBy(pair => pair.Key)
.ToList();
// Print sorted dictionary
Console.WriteLine("Sorted dictionary is :");
foreach (var pair in sortedDict)
{
Console.Write("(" + pair.Key + ", " + pair.Value + ") ");
}
Console.WriteLine();
}
}
JavaScript
// Initialize a dictionary
const my_dict = {
'c': 3,
'a': 1,
'd': 4,
'b': 2
};
// Sorting dictionary
const sorted_dict = Object.entries(my_dict)
.sort((a, b) => a[1] - b[1])
.map(entry => [entry[1], entry[0]]);
// Print sorted dictionary
console.log("Sorted dictionary is :");
console.log(sorted_dict);
// This code is contributed by Prince Kumar
OutputSorted dictionary is :
(1, a) (2, b) (3, c) (4, d)
Time Complexity: O(n log n)
Space Complexity: O(n)
Using sorted() and get(): The method get() returns the value for the given key, if present in the dictionary. If not, then it will return None.
Examples:
Input: my_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'}
Output:
black #000000
green #008000
red #FF0000
white #FFFFFF
Below is the implementation using sorted() and get() method:
C++
// CPP program for the above approach
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
// Initialize a dictionary
map<string, string> my_dict
= { { "red", "#FF0000" },
{ "green", "#008000" },
{ "black", "#000000" },
{ "white", "#FFFFFF" } };
// Sort dictionary by value
vector<pair<string, string> > sorted_dict;
for (const auto& pair : my_dict) {
sorted_dict.push_back(pair);
}
sort(sorted_dict.begin(), sorted_dict.end(),
[](const auto& a, const auto& b) {
return a.second < b.second;
});
// Print sorted dictionary
cout << "Sorted dictionary is :\n";
for (const auto& pair : sorted_dict) {
cout << pair.first << " " << pair.second << "\n";
}
return 0;
}
// This code is contributed by Susobhan Akhuli
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initialize a TreeMap to store key-value pairs
TreeMap<String, String> myMap = new TreeMap<>();
// Add key-value pairs to the TreeMap
myMap.put("red", "#FF0000");
myMap.put("green", "#008000");
myMap.put("black", "#000000");
myMap.put("white", "#FFFFFF");
// Sort and print the TreeMap
System.out.println("Sorted dictionary is:");
for (Map.Entry<String, String> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Python
# Python program to sort dictionary
# by value using sorted() and get()
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
'black': '# 000000', 'white': '# FFFFFF'}
# Sort and print dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get):
print(w, my_dict[w])
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// Initialize a dictionary
Dictionary<string, string> myDict = new Dictionary<string, string>()
{
{ "red", "#FF0000" },
{ "green", "#008000" },
{ "black", "#000000" },
{ "white", "#FFFFFF" }
};
// Sort dictionary by value
var sortedDict = myDict.OrderBy(pair => pair.Value);
// Print sorted dictionary
Console.WriteLine("Sorted dictionary is :");
foreach (var pair in sortedDict)
{
Console.WriteLine($"{pair.Key} {pair.Value}");
}
// This code is contributed by Susobhan Akhuli
}
}
JavaScript
// Initialize an object (dictionary)
const myDict = {
'red': '#FF0000',
'green': '#008000',
'black': '#000000',
'white': '#FFFFFF'
};
// Sort and print the dictionary
console.log('Sorted dictionary is:');
Object.keys(myDict)
.sort((a, b) => myDict[a].localeCompare(myDict[b]))
.forEach(key => {
console.log(key, myDict[key]);
});
OutputSorted dictionary is :
black #000000
green #008000
red #FF0000
white #FFFFFF
Time complexity: O(nlogn) - sorting the dictionary using the sorted() function takes nlogn time,
Auxiliary space: O(n) - creating a new list of keys in sorted order takes O(n) space.
Using itemgetter from operator
The method itemgetter(n) constructs a callable that assumes an iterable object as input, and fetches the n-th element out of it.
Examples
Input:
my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}
Output:
[('e', 12), ('a', 23), ('g', 67), (45, 90)]
Below is the python program to sort the dictionary using itemgetter():
C++
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
// Comparator function to sort map by value
bool sortByValue(const pair<string, int>& a,
const pair<string, int>& b)
{
return (a.second < b.second);
}
int main()
{
// Initialize a map
map<string, int> my_dict = {
{ "a", 23 }, { "g", 67 }, { "e", 12 }, { "45", 90 }
};
// Sorting dictionary
vector<pair<string, int> > sorted_dict(my_dict.begin(),
my_dict.end());
sort(sorted_dict.begin(), sorted_dict.end(),
sortByValue);
// Printing sorted dictionary
cout << "Sorted dictionary is:" << endl;
for (const auto& pair : sorted_dict) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
// This code is contibuted by Utkarsh.
Java
import java.util.*;
public class SortMapByValue {
// Comparator function to sort map by value
static class SortByValue
implements Comparator<Map.Entry<String, Integer> > {
public int compare(Map.Entry<String, Integer> a,
Map.Entry<String, Integer> b)
{
return a.getValue().compareTo(b.getValue());
}
}
public static void main(String[] args)
{
// Initialize a map
Map<String, Integer> myDict = new HashMap<>();
myDict.put("a", 23);
myDict.put("g", 67);
myDict.put("e", 12);
myDict.put("45", 90);
// Sorting dictionary
List<Map.Entry<String, Integer> > sortedDict
= new ArrayList<>(myDict.entrySet());
Collections.sort(sortedDict, new SortByValue());
// Printing sorted dictionary
System.out.println("Sorted dictionary is:");
System.out.print("[");
for (int i = 0; i < sortedDict.size(); i++) {
System.out.print(
"(" + sortedDict.get(i).getKey() + ", "
+ sortedDict.get(i).getValue() + ")");
if (i != sortedDict.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
// This code is contributed by Monu.
Python
# Python program to sort dictionary
# by value using itemgetter() function
# Importing OrderedDict
import operator
# Initialize a dictionary
my_dict = {'a': 23,
'g': 67,
'e': 12,
45: 90}
# Sorting dictionary
sorted_dict = sorted(my_dict.items(),
key=operator.itemgetter(1))
# Printing sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)
JavaScript
// Comparator function to sort array of objects by value
function sortByValue(a, b) {
return a[1] - b[1];
}
// Initialize a map
let my_dict = new Map([
["a", 23],
["g", 67],
["e", 12],
["45", 90]
]);
// Sorting dictionary
let sorted_dict = Array.from(my_dict.entries()).sort(sortByValue);
// Printing sorted dictionary
console.log("Sorted dictionary is:");
sorted_dict.forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
OutputSorted dictionary is :
[('e', 12), ('a', 23), ('g', 67), (45, 90)]
Time complexity: O(n log n)
The time complexity of sorting a dictionary using the itemgetter() function is O(n log n). This is because the itemgetter() function must traverse through the dictionary and compare each element to determine the sorting order. Since comparing each element is an O(n) operation, and sorting is an O(log n) operation, the overall time complexity is O(n log n).
Space complexity: O(n)
The space complexity of sorting a dictionary using the itemgetter() function is O(n). This is because the itemgetter() function must create a new list containing all of the elements of the dictionary, which requires O(n) space.
Using OrderedDict from collections: The OrderedDict is a standard library class, which is located in the collections module. OrderedDict maintains the orders of keys as inserted.
Examples:
Input: my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
Below is the implementation using Ordered Dict:
C++
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main() {
// Initialize a map
map<int, int> myDict = {{1, 2}, {3, 4}, {4, 3}, {2, 1}, {0, 0}};
// Convert the map into a vector of key-value pairs
vector<pair<int, int>> items(myDict.begin(), myDict.end());
// Sort the vector based on the values
sort(items.begin(), items.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second;
});
// Initialize an empty vector of pairs to store the sorted dictionary
vector<pair<int, int>> sortedDict;
// Populate the sorted dictionary vector
for (const auto& item : items) {
sortedDict.push_back(item);
}
// Print the sorted dictionary
cout << "Sorted dictionary is:" << endl;
for (const auto& kv : sortedDict) {
cout << kv.first << ": " << kv.second << endl;
}
return 0;
}
// This code is contributed by shivamgupta0987654321
Java
import java.util.*;
public class SortDictionaryByValue {
public static LinkedHashMap<Integer, Integer>
sortDictionaryByValue(Map<Integer, Integer> myMap)
{
// Create a list of entries from the map
List<Map.Entry<Integer, Integer> > entryList
= new LinkedList<>(myMap.entrySet());
// Sort the list based on the values
entryList.sort(Map.Entry.comparingByValue());
// Create a new LinkedHashMap to maintain the
// insertion order
LinkedHashMap<Integer, Integer> sortedMap
= new LinkedHashMap<>();
// Copy sorted entries to the LinkedHashMap
for (Map.Entry<Integer, Integer> entry :
entryList) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void main(String[] args)
{
// Initialize a dictionary
Map<Integer, Integer> myMap = new HashMap<>();
myMap.put(1, 2);
myMap.put(3, 4);
myMap.put(4, 3);
myMap.put(2, 1);
myMap.put(0, 0);
// Sort the dictionary by value
LinkedHashMap<Integer, Integer> sortedMap
= sortDictionaryByValue(myMap);
// Print the sorted dictionary
System.out.println("Sorted dictionary is :");
for (Map.Entry<Integer, Integer> entry :
sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": "
+ entry.getValue());
}
}
}
Python
# Python program to sort dictionary
# by value using OrderedDict
# Import OrderedDict
from collections import OrderedDict
# Initialize a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# Sort dictionary
sorted_dict = OrderedDict(sorted(
my_dict.items(), key=lambda x: x[1]))
# Print the sorted dictionary in the specified format
print("Sorted dictionary is:")
for key, value in sorted_dict.items():
print(f"{key}: {value}")
JavaScript
// Initialize a dictionary
const myDict = { 1: 2, 3: 4, 4: 3, 2: 1, 0: 0 };
// Convert the dictionary into an array of key-value pairs
const items = Object.keys(myDict).map(key => [parseInt(key), myDict[key]]);
// Sort the array based on the values
items.sort((a, b) => a[1] - b[1]);
// Initialize an empty string to store the sorted dictionary representation
let sortedDictString = "Sorted dictionary is:\n";
// Populate the sorted dictionary string
items.forEach(item => {
sortedDictString += `${item[0]}: ${item[1]}\n`;
});
// Print the sorted dictionary
console.log(sortedDictString);
OutputSorted dictionary is :
OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])
Time complexity: The time complexity of this program is O(n log n), where n is the size of the dictionary.
Space complexity: The space complexity of this program is O(n), where n is the size of the dictionary.
Using Counter from collections: The counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers.
Examples:
Input: my_dict = {'hello': 1, 'python': 5, 'world': 3}
Output: [('hello', 1), ('world', 3), ('python', 5)]
Below is the implementation using Counter from collections:
C++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
// Initialize a map
std::map<std::string, int> myMap;
myMap["hello"] = 1;
myMap["python"] = 5;
myMap["world"] = 3;
// Sort the map by value
std::vector<std::pair<std::string, int>> sortedEntries(myMap.begin(), myMap.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), [](const auto& a, const auto& b) {
return a.second < b.second;
});
// Print the sorted map
std::cout << "Sorted dictionary is:" << std::endl;
for (const auto& entry : sortedEntries) {
std::cout << entry.first << ": " << entry.second << std::endl;
}
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
// Initialize a dictionary
Map<String, Integer> myMap = new HashMap<>();
myMap.put("hello", 1);
myMap.put("python", 5);
myMap.put("world", 3);
// Sort the dictionary by value
List<Map.Entry<String, Integer> > sortedEntries
= new ArrayList<>(myMap.entrySet());
Collections.sort(
sortedEntries,
Comparator.comparing(Map.Entry::getValue));
// Print the sorted dictionary
System.out.println("Sorted dictionary is:");
for (Map.Entry<String, Integer> entry :
sortedEntries) {
System.out.println(entry.getKey() + ": "
+ entry.getValue());
}
}
}
Python
# Define a dictionary
my_dict = {"hello": 1, "python": 5, "world": 3}
# Sort the dictionary by value
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])
# Print the sorted dictionary
print("Sorted dictionary is:")
for key, value in sorted_dict:
print(key + ": " + str(value))
JavaScript
// Define a dictionary
let myMap = new Map();
myMap.set("hello", 1);
myMap.set("python", 5);
myMap.set("world", 3);
// Convert the Map to an array of entries and sort it by value
let sortedEntries = Array.from(myMap.entries()).sort((a, b) => a[1] - b[1]);
// Print the sorted dictionary
console.log("Sorted dictionary is:");
sortedEntries.forEach(([key, value]) => {
console.log(key + ": " + value);
});
OutputSorted dictionary is :
[('hello', 1), ('world', 3), ('python', 5)]
Reverse Sorting Dictionary by values: The same syntax for both ascending and descending ordered sorting. For reverse sorting, the idea is to use reverse = true. with the function sorted().
Examples:
Input:
my_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
Output:
black #000000
green #008000
red #FF0000
white #FFFFFF
Below is the implementation using Reverse Sorting Dictionary by values:
C++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Initialize a dictionary
map<string, string> my_dict = {{"red", "# FF0000"}, {"green", "# 008000"},
{"black", "# 000000"}, {"white", "# FFFFFF"}};
// Create a vector of pairs to store key-value pairs
vector<pair<string, string>> dict_vec;
// Copy key-value pairs from dictionary to vector
for (auto const& pair : my_dict) {
dict_vec.push_back(pair);
}
// Sort the vector by value in reverse order
sort(dict_vec.begin(), dict_vec.end(),
[](const pair<string, string>& a, const pair<string, string>& b) {
return a.second > b.second;
});
// Print the sorted dictionary
cout << "Sorted dictionary is:" << endl;
for (const auto& pair : dict_vec) {
cout << pair.first << " " << pair.second << endl;
}
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initialize a HashMap
HashMap<String, String> myMap = new HashMap<>();
myMap.put("red", "#FF0000");
myMap.put("green", "#008000");
myMap.put("black", "#000000");
myMap.put("white", "#FFFFFF");
// Convert HashMap to a List of Map.Entry objects
List<Map.Entry<String, String>> mapList = new ArrayList<>(myMap.entrySet());
// Sort the list by value in reverse order
Collections.sort(mapList, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> a, Map.Entry<String, String> b) {
return b.getValue().compareTo(a.getValue());
}
});
// Print the sorted dictionary
System.out.println("Sorted dictionary is:");
for (Map.Entry<String, String> entry : mapList) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Python
# Python program to sort dictionary
# by value using sorted setting
# reverse parameter to true
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
'black': '# 000000', 'white': '# FFFFFF'}
# Sort and print the dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get, \
reverse = True):
print(w, my_dict[w])
JavaScript
// Initialize a dictionary (object in JavaScript)
let myDict = {
"red": "#FF0000",
"green": "#008000",
"black": "#000000",
"white": "#FFFFFF"
};
// Convert dictionary to an array of key-value pairs
let dictArray = Object.entries(myDict);
// Sort the array by value in reverse order
dictArray.sort((a, b) => {
return b[1].localeCompare(a[1]);
});
// Print the sorted dictionary
console.log("Sorted dictionary is:");
dictArray.forEach(pair => {
console.log(pair[0] + " " + pair[1]);
});
OutputSorted dictionary is :
white # FFFFFF
red # FF0000
green # 008000
black # 000000
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read