diff --git a/README.md b/README.md index d6fd89ffb..6821297b6 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Pavitraa G + + + yashksaini-coder +
+ Yash Kumar Saini +
+ KapuluruBhuvaneswariVspdbct @@ -199,13 +206,6 @@ Thanks to these amazing people who have contributed to the **Algo** project:
Priya
- - - - yashksaini-coder -
- Yash Kumar Saini -
@@ -268,10 +268,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Gopal0Gupta + + nishant4500
- Gopal Gupta + Nishant Dwivedi
@@ -282,10 +282,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - nishant4500 + + Gopal0Gupta
- Nishant Dwivedi + Gopal Gupta
@@ -297,6 +297,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: + + + shuvojitss +
+ Shuvojit Samanta +
+ riyaa060 @@ -318,13 +325,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Vivek Prakash - - - shuvojitss -
- Shuvojit Samanta -
- PradeepFSTdhane123 @@ -333,19 +333,19 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Shariq2003 + + AE-Hertz
- Shariq + Abhinandan
- - MithanshuHedau + + PrAyAg9
- Mithanshu Hedau + Prayag Thakur
@@ -356,17 +356,17 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - AE-Hertz + + MithanshuHedau
- Abhinandan + Mithanshu Hedau
- - PrAyAg9 + + Shariq2003
- Prayag Thakur + Shariq
@@ -400,40 +400,40 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Subashree-selvaraj + + aditiverma-21
- subashree + Aditi Verma
- - Abhishek2634 + + KashishJuneja101003
- Abhishek Farshwal + Kashish Juneja
- - KashishJuneja101003 + + Rashigera
- Kashish Juneja + Rashigera
- - aditiverma-21 + + Abhishek2634
- Aditi Verma + Abhishek Farshwal
- - Rashigera + + Subashree-selvaraj
- Rashigera + subashree
@@ -451,33 +451,33 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - tanishqkolhatkar93 + + PavanTeja2005
- Tanishq Kolhatkar + PavanTeja2005
- - Riddhi12349 + + mehul-m-prajapati
- riddhi + Mehul Prajapati
- - PavanTeja2005 + + tanishqkolhatkar93
- PavanTeja2005 + Tanishq Kolhatkar
- - mehul-m-prajapati + + Riddhi12349
- Mehul Prajapati + riddhi
@@ -502,10 +502,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - shimmer12 + + khurshed07
- Srishti Soni + khurshed Ansari
@@ -517,6 +517,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: + + + shimmer12 +
+ Srishti Soni +
+ LitZeus @@ -546,12 +553,14 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - khurshed07 + + jvkousthub
- khurshed Ansari + Kousthub J V
+ + sriraghavi22 @@ -559,8 +568,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: sriraghavi22 - - govindumeesala @@ -569,10 +576,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - jvkousthub + + AADESHak007
- Kousthub J V + Aadesh_Kumar
@@ -590,12 +597,14 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - AADESHak007 + + Saaarthak0102
- Aadesh_Kumar + Sarthak
+ + akash70629 @@ -603,57 +612,55 @@ Thanks to these amazing people who have contributed to the **Algo** project: Akash Das - - - - Saaarthak0102 + + AdityaJani616
- Sarthak + Aditya Jani
- - Bhumika-00 + + AswaniBolisetti
- Bhumika Sharma + Aswani Bolisetti
- - Lighting-pixel + + 4F24L
- Ayan + Md Afzal Mir
- - AdityaJani616 + + Bhumika-00
- Aditya Jani + Bhumika Sharma
- - samar12-rad + + Jivanjamadar
- Samarth Vaidya + Jivan
+ + - - AswaniBolisetti + + Lighting-pixel
- Aswani Bolisetti + Ayan
- - - - 4F24L + + samar12-rad
- Md Afzal Mir + Samarth Vaidya
@@ -671,17 +678,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Shantnu-singh -
- shantnu -
- - - - KunikaMakker + + alo7lika
- Kunika Makker + alolika bhowmik
@@ -694,17 +694,17 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - alo7lika + + KunikaMakker
- alolika bhowmik + Kunika Makker
- - shashmitha46 + + Shantnu-singh
- Shashmitha V + shantnu
@@ -714,6 +714,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Disha T + + + shashmitha46 +
+ Shashmitha V +
+ purnima2904 @@ -728,6 +735,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: shamvrueth + + IRFANSARI @@ -735,8 +744,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Irfan Ansari - - karthikyandrapu @@ -772,6 +779,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Vishant Rathi + + tanushrigoel @@ -779,8 +788,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: tanushrigoel - - Bhum-ika @@ -816,6 +823,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Souvik Kumar Pramanik + + Soumya03007 @@ -823,8 +832,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Soumyadeep Paul - - KGupta2601 @@ -846,13 +853,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: smog-root - - - yogeswari05 -
- Chekka Yogeswari -
- ADITHYA-NS @@ -876,13 +876,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Grandhi-Harshitha - - - Jivanjamadar -
- Jivan -
- meghanakn473 @@ -911,8 +904,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Sanat Kumar Gupta - - Shreya7tripathy @@ -920,6 +911,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Shreya Tripathy + + vedhcet-07 @@ -927,6 +920,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Vishwas M D + + + yogeswari05 +
+ Chekka Yogeswari +
+ 1-SubhamSingh @@ -1316,6 +1316,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Adwitya Chakraborty + + + pa1narendra +
+ PAVAN NARENDRA PEELA +
+ sujal-GITHUB @@ -1344,6 +1351,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Lokesh_Bijarniya_ + + LNischala @@ -1351,8 +1360,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: LNischala - - krishpathak @@ -1388,6 +1395,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Harsh + + arzoosingh147 @@ -1395,8 +1404,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Arzoo Singh - - ArchanRD diff --git a/docs/Fenwick Tree /FenwickTree.md b/docs/Fenwick Tree /FenwickTree.md deleted file mode 100644 index ba6bfd85b..000000000 --- a/docs/Fenwick Tree /FenwickTree.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -id: fenwick-tree -title: "Introduction to Fenwick Tree (Binary Indexed Tree)" -sidebar_label: "Fenwick Tree" -sidebar_position: 1 -description: "Information on Fenwick Tree (Binary Indexed Tree) Algorithm" -tags: [Algorithm, Fenwick Tree, Binary Indexed Tree] ---- - -# Fenwick Tree (Binary Indexed Tree) -## Overview -The Fenwick Tree, also known as a Binary Indexed Tree (BIT), is a data structure used for efficiently calculating prefix sums and updating elements. It offers a significant performance boost when dealing with cumulative frequency tables, making it ideal for scenarios where frequent updates and prefix sum queries are required. - -## Use Cases -- **Efficient Range Queries**: Commonly used in situations where range sums and point updates are frequent. -- **Inversion Counting in Arrays**: Used in competitive programming to count inversions in arrays. -- **Data Compression**: Supports cumulative frequency counting, which helps in data compression algorithms. -- **2D Queries**: Fenwick Trees can also be extended to 2D data structures, allowing applications in grid-based problems. - -## Algorithm Details -### Key Concepts -1. **Binary Indexed Representation**: Fenwick Trees leverage binary representation for efficient sum and update operations. -2. **Operations**: - - **Update**: Modify the value of a specific element. - - **Query**: Compute the cumulative sum up to a specific index. - -### Time Complexity -- Both update and query operations are `O(log N)` where `N` is the number of elements, due to the logarithmic depth of the tree. - -## Pseudocode - -```cpp -// Function to add 'val' to index 'i' (1-based index) -function update(i, val): - while i <= n: - BITree[i] += val - i += (i & -i) - -// Function to get sum from index 1 to i (1-based index) -function getSum(i): - sum = 0 - while i > 0: - sum += BITree[i] - i -= (i & -i) - return sum -``` - -## Example Code in C++ -Here’s a C++ implementation of the Fenwick Tree: - -```cpp -#include -#include -using namespace std; - -class FenwickTree { -private: - vector BITree; - int n; - -public: - // Initialize Fenwick Tree with n elements - FenwickTree(int size) { - n = size; - BITree.resize(n + 1, 0); - } - - // Update index 'i' with value 'val' - void update(int i, int val) { - while (i <= n) { - BITree[i] += val; - i += (i & -i); - } - } - - // Get cumulative sum from index 1 to 'i' - int getSum(int i) { - int sum = 0; - while (i > 0) { - sum += BITree[i]; - i -= (i & -i); - } - return sum; - } - - // Get sum from index 'l' to 'r' - int rangeSum(int l, int r) { - return getSum(r) - getSum(l - 1); - } -}; - -int main() { - FenwickTree ft(10); - ft.update(3, 5); // Update index 3 with +5 - ft.update(5, 2); // Update index 5 with +2 - cout << "Sum from 1 to 5: " << ft.getSum(5) << endl; - cout << "Range Sum from 3 to 5: " << ft.rangeSum(3, 5) << endl; - return 0; -} -``` - -## Explanation of the Code -- Update Operation: Updates the tree from a specific index by propagating the change to subsequent indices using i += (i & -i). -- Query Operation: Accumulates the sum of elements up to a specific index by traversing backward using i -= (i & -i). -- Range Sum Query: To compute the sum between two indices l and r, the difference of sums up to r and l-1 is used. - -## Example Walkthrough -Suppose we have an array of integers and initialize the Fenwick Tree with zeroes. For each update and query operation, the tree adjusts only the necessary indices, significantly improving efficiency. - -## Real-World Example -In competitive programming and applications dealing with real-time data processing, such as live leaderboard rankings or real-time transaction data, Fenwick Trees provide a fast and memory-efficient way to maintain cumulative values. diff --git a/docs/Recursion/Knight's_Tour_Problem.md b/docs/Recursion/Knight's_Tour_Problem.md index 095105f36..59d3bff80 100644 --- a/docs/Recursion/Knight's_Tour_Problem.md +++ b/docs/Recursion/Knight's_Tour_Problem.md @@ -1,192 +1,192 @@ ---- -id: Knights-Tour-problem-dsa -title: Knight's Tour Recursion -sidebar_label: Knight's Tour -sidebar_position: 3 -description: "The Knight's Tour problem is a classic backtracking problem where the goal is to move a knight across an n×n chessboard such that it visits every square exactly once. The problem is often solved using backtracking and recursion." -tags: [knights-tour, backtracking, recursion, dsa] ---- - -## Knight's Tour Problem | Find a Path for the Knight to Visit All Squares - -- Problem Statement: The Knight's Tour problem involves moving a knight on an n × n chessboard such that the knight visits every square exactly once. Given an integer `n`, find one possible solution to the problem. - - -```cpp -#include -#include - -using namespace std; - -class KnightTour { - const vector> moves = { - {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, - {-2, -1}, {-1, -2}, {1, -2}, {2, -1} - }; - -public: - void findKnightTour(int n) { - vector> board(n, vector(n, -1)); - board[0][0] = 0; // Starting position - if (exploreTour(0, 0, 1, board, n)) { - displayBoard(board); - } else { - cout << "No solution exists." << endl; - } - } - -private: - bool exploreTour(int x, int y, int moveCount, vector>& board, int n) { - if (moveCount == n * n) { - return true; // All squares visited - } - - for (const auto& move : moves) { - int nextX = x + move.first; - int nextY = y + move.second; - - if (isValidMove(nextX, nextY, board, n)) { - board[nextX][nextY] = moveCount; - if (exploreTour(nextX, nextY, moveCount + 1, board, n)) { - return true; - } - board[nextX][nextY] = -1; // Backtrack - } - } - return false; // No valid move found - } - - bool isValidMove(int x, int y, const vector>& board, int n) { - return (x >= 0 && x < n && y >= 0 && y < n && board[x][y] == -1); - } - - void displayBoard(const vector>& board) { - for (const auto& row : board) { - for (const auto& cell : row) { - cout << cell << "\t"; - } - cout << endl; - } - } -}; - -int main() { - int n = 5; // Size of the chessboard - KnightTour kt; - kt.findKnightTour(n); - return 0; -} - -``` - -```python - -class KnightsTour: - def __init__(self, n): - self.n = n - self.moves = [(2, 1), (1, 2), (-1, 2), (-2, 1), - (-2, -1), (-1, -2), (1, -2), (2, -1)] - self.board = [[-1 for _ in range(n)] for _ in range(n)] - self.board[0][0] = 0 # Starting position - - def is_valid_move(self, x, y): - return 0 <= x < self.n and 0 <= y < self.n and self.board[x][y] == -1 - - def explore_tour(self, x, y, move_count): - if move_count == self.n * self.n: - return True # All squares visited - - for move in self.moves: - next_x = x + move[0] - next_y = y + move[1] - - if self.is_valid_move(next_x, next_y): - self.board[next_x][next_y] = move_count - if self.explore_tour(next_x, next_y, move_count + 1): - return True - self.board[next_x][next_y] = -1 # Backtrack - - return False # No valid move found - - def display_board(self): - for row in self.board: - print("\t".join(map(str, row))) - print() - - def find_knight_tour(self): - if self.explore_tour(0, 0, 1): - self.display_board() - else: - print("No solution exists.") - - -if __name__ == "__main__": - n = 5 # Size of the chessboard - kt = KnightsTour(n) - kt.find_knight_tour() - -``` - -```java - -public class KnightsTour { - private static final int[][] moves = { - {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, - {-2, -1}, {-1, -2}, {1, -2}, {2, -1} - }; - - public void findKnightTour(int n) { - int[][] board = new int[n][n]; - for (int[] row : board) { - Arrays.fill(row, -1); // Initialize the board with -1 - } - board[0][0] = 0; // Starting position - if (exploreTour(0, 0, 1, board, n)) { - displayBoard(board); - } else { - System.out.println("No solution exists."); - } - } - - private boolean exploreTour(int x, int y, int moveCount, int[][] board, int n) { - if (moveCount == n * n) { - return true; // All squares visited - } - - for (int[] move : moves) { - int nextX = x + move[0]; - int nextY = y + move[1]; - - if (isValidMove(nextX, nextY, board, n)) { - board[nextX][nextY] = moveCount; - if (exploreTour(nextX, nextY, moveCount + 1, board, n)) { - return true; - } - board[nextX][nextY] = -1; // Backtrack - } - } - return false; // No valid move found - } - - private boolean isValidMove(int x, int y, int[][] board, int n) { - return (x >= 0 && x < n && y >= 0 && y < n && board[x][y] == -1); - } - - private void displayBoard(int[][] board) { - for (int[] row : board) { - for (int cell : row) { - System.out.print(cell + "\t"); - } - System.out.println(); - } - } - - public static void main(String[] args) { - int n = 5; // Size of the chessboard - KnightsTour kt = new KnightsTour(); - kt.findKnightTour(n); - } -} - -``` - +--- +id: Knights-Tour-problem-dsa +title: Knight's Tour Recursion +sidebar_label: Knight's Tour +sidebar_position: 3 +description: "The Knight's Tour problem is a classic backtracking problem where the goal is to move a knight across an n×n chessboard such that it visits every square exactly once. The problem is often solved using backtracking and recursion." +tags: [knights-tour, backtracking, recursion, dsa] +--- + +## Knight's Tour Problem | Find a Path for the Knight to Visit All Squares + +- Problem Statement: The Knight's Tour problem involves moving a knight on an n × n chessboard such that the knight visits every square exactly once. Given an integer `n`, find one possible solution to the problem. + + +```cpp +#include +#include + +using namespace std; + +class KnightTour { + const vector> moves = { + {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, + {-2, -1}, {-1, -2}, {1, -2}, {2, -1} + }; + +public: + void findKnightTour(int n) { + vector> board(n, vector(n, -1)); + board[0][0] = 0; // Starting position + if (exploreTour(0, 0, 1, board, n)) { + displayBoard(board); + } else { + cout << "No solution exists." << endl; + } + } + +private: + bool exploreTour(int x, int y, int moveCount, vector>& board, int n) { + if (moveCount == n * n) { + return true; // All squares visited + } + + for (const auto& move : moves) { + int nextX = x + move.first; + int nextY = y + move.second; + + if (isValidMove(nextX, nextY, board, n)) { + board[nextX][nextY] = moveCount; + if (exploreTour(nextX, nextY, moveCount + 1, board, n)) { + return true; + } + board[nextX][nextY] = -1; // Backtrack + } + } + return false; // No valid move found + } + + bool isValidMove(int x, int y, const vector>& board, int n) { + return (x >= 0 && x < n && y >= 0 && y < n && board[x][y] == -1); + } + + void displayBoard(const vector>& board) { + for (const auto& row : board) { + for (const auto& cell : row) { + cout << cell << "\t"; + } + cout << endl; + } + } +}; + +int main() { + int n = 5; // Size of the chessboard + KnightTour kt; + kt.findKnightTour(n); + return 0; +} + +``` + +```python + +class KnightsTour: + def __init__(self, n): + self.n = n + self.moves = [(2, 1), (1, 2), (-1, 2), (-2, 1), + (-2, -1), (-1, -2), (1, -2), (2, -1)] + self.board = [[-1 for _ in range(n)] for _ in range(n)] + self.board[0][0] = 0 # Starting position + + def is_valid_move(self, x, y): + return 0 <= x < self.n and 0 <= y < self.n and self.board[x][y] == -1 + + def explore_tour(self, x, y, move_count): + if move_count == self.n * self.n: + return True # All squares visited + + for move in self.moves: + next_x = x + move[0] + next_y = y + move[1] + + if self.is_valid_move(next_x, next_y): + self.board[next_x][next_y] = move_count + if self.explore_tour(next_x, next_y, move_count + 1): + return True + self.board[next_x][next_y] = -1 # Backtrack + + return False # No valid move found + + def display_board(self): + for row in self.board: + print("\t".join(map(str, row))) + print() + + def find_knight_tour(self): + if self.explore_tour(0, 0, 1): + self.display_board() + else: + print("No solution exists.") + + +if __name__ == "__main__": + n = 5 # Size of the chessboard + kt = KnightsTour(n) + kt.find_knight_tour() + +``` + +```java + +public class KnightsTour { + private static final int[][] moves = { + {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, + {-2, -1}, {-1, -2}, {1, -2}, {2, -1} + }; + + public void findKnightTour(int n) { + int[][] board = new int[n][n]; + for (int[] row : board) { + Arrays.fill(row, -1); // Initialize the board with -1 + } + board[0][0] = 0; // Starting position + if (exploreTour(0, 0, 1, board, n)) { + displayBoard(board); + } else { + System.out.println("No solution exists."); + } + } + + private boolean exploreTour(int x, int y, int moveCount, int[][] board, int n) { + if (moveCount == n * n) { + return true; // All squares visited + } + + for (int[] move : moves) { + int nextX = x + move[0]; + int nextY = y + move[1]; + + if (isValidMove(nextX, nextY, board, n)) { + board[nextX][nextY] = moveCount; + if (exploreTour(nextX, nextY, moveCount + 1, board, n)) { + return true; + } + board[nextX][nextY] = -1; // Backtrack + } + } + return false; // No valid move found + } + + private boolean isValidMove(int x, int y, int[][] board, int n) { + return (x >= 0 && x < n && y >= 0 && y < n && board[x][y] == -1); + } + + private void displayBoard(int[][] board) { + for (int[] row : board) { + for (int cell : row) { + System.out.print(cell + "\t"); + } + System.out.println(); + } + } + + public static void main(String[] args) { + int n = 5; // Size of the chessboard + KnightsTour kt = new KnightsTour(); + kt.findKnightTour(n); + } +} + +``` + diff --git a/docs/algorithms/Searching Algorithms/A*-Search.md b/docs/algorithms/Searching Algorithms/A*-Search.md deleted file mode 100644 index 8fe5bcf96..000000000 --- a/docs/algorithms/Searching Algorithms/A*-Search.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -id: a-*-search -sidebar_position: 1 -title: A* Search -sidebar_label: A* ---- - -### Definition: - -**A* Search** is a pathfinding and graph traversal algorithm used to find the shortest path from a starting point to a goal. It combines the actual cost from the starting point and a heuristic estimate of the cost to reach the goal, making it both efficient and effective in scenarios where an optimal path is needed. - -### Characteristics: - -- **Heuristic-Based**: Utilizes heuristics to prioritize nodes. -- **Optimal**: Finds the shortest path if the heuristic is admissible. -- **Complete**: Ensures a solution is found if one exists. - -### How A* Works: - -1. **Initialize**: Start with the initial node in the open list. -2. **Expand**: Select the node with the lowest estimated total cost. -3. **Explore Neighbors**: For each unvisited neighbor, calculate the cost, update if lower. -4. **Repeat**: Continue until reaching the goal node or the open list is empty. - -### Time Complexity: - -- **Time Complexity**: \(O(b^d)\), where `b` is the branching factor and `d` is the depth of the solution. - -### Space Complexity: - -- **Space Complexity**: \(O(b^d)\) - -### Advantages of A*: - -- **Optimal Path**: Finds the shortest path in a graph. -- **Efficient Exploration**: Heuristic allows focusing on promising paths. - -### Disadvantages of A*: - -- **Memory Usage**: Can require high memory for large graphs. -- **Dependence on Heuristic**: Performance relies on the quality of the heuristic. - -### A* Algorithm (Java Implementation): - -```java -import java.util.*; - -class Node implements Comparable { - int x, y, cost, heuristic; - - Node(int x, int y, int cost, int heuristic) { - this.x = x; - this.y = y; - this.cost = cost; - this.heuristic = heuristic; - } - - @Override - public int compareTo(Node other) { - return Integer.compare(this.cost + this.heuristic, other.cost + other.heuristic); - } -} - -class AStarAlgorithm { - public static List aStarSearch(Node start, Node goal) { - PriorityQueue openList = new PriorityQueue<>(); - Set closedList = new HashSet<>(); - openList.add(start); - - while (!openList.isEmpty()) { - Node current = openList.poll(); - if (current.equals(goal)) { - return reconstructPath(goal); - } - closedList.add(current); - - for (Node neighbor : getNeighbors(current)) { - if (closedList.contains(neighbor)) continue; - int tentativeCost = current.cost + calculateCost(current, neighbor); - - if (!openList.contains(neighbor) || tentativeCost < neighbor.cost) { - neighbor.cost = tentativeCost; - neighbor.heuristic = calculateHeuristic(neighbor, goal); - openList.add(neighbor); - } - } - } - return null; // Goal not reached - } - - // Dummy implementations for path reconstruction, neighbors, and heuristics - private static List reconstructPath(Node goal) { return new ArrayList<>(); } - private static List getNeighbors(Node node) { return new ArrayList<>(); } - private static int calculateCost(Node current, Node neighbor) { return 1; } - private static int calculateHeuristic(Node current, Node goal) { return Math.abs(current.x - goal.x) + Math.abs(current.y - goal.y); } -} -``` -### Applications of A*: -Pathfinding: Used in games, robotics, and network routing. -AI for Games: Determines optimal paths in dynamic environments. -Robotics: Helps in navigating obstacles effectively. -### Summary: -A* Search is an optimal, heuristic-based search algorithm with broad applications in AI, robotics, and pathfinding. Its focus on efficient pathfinding while guaranteeing optimality makes it a key algorithm in many fields. diff --git a/docs/algorithms/Searching Algorithms/AO*-Search.md b/docs/algorithms/Searching Algorithms/AO*-Search.md deleted file mode 100644 index 1956a0fb5..000000000 --- a/docs/algorithms/Searching Algorithms/AO*-Search.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -id: ao-star-search -sidebar_position: 2 -title: AO* Search -sidebar_label: AO* ---- - -### Definition: - -**AO* Search** is an algorithm designed for AND-OR graphs, where nodes may have both AND and OR conditions. This is common in decision-making and problem-solving applications where subproblems must be solved together or independently to reach a solution. - -### Characteristics: - -- **AND-OR Structure**: Solves problems with combined conditions. -- **Heuristic-Based**: Uses heuristics for efficient traversal. -- **Backtracking**: Updates cost estimates and paths dynamically. - -### How AO* Works: - -1. **Initialize**: Start with the root node. -2. **Evaluate Nodes**: Expand nodes based on heuristic values. -3. **Select Optimal Paths**: Choose paths with minimum costs, backtracking if needed. -4. **Repeat**: Continue until reaching a terminal node or completing all AND-conditions. - -### Time Complexity: - -- **Time Complexity**: Variable, based on graph complexity and heuristic. - -### Space Complexity: - -- **Space Complexity**: \(O(n)\) - -### Advantages of AO*: - -- **Solves Complex Problems**: Ideal for problems with AND-OR structures. -- **Heuristic Efficiency**: Minimizes unnecessary expansions. - -### Disadvantages of AO*: - -- **Dependent on Heuristic**: Heuristic choice impacts performance. -- **Complexity in Large Graphs**: May become inefficient on large, complex graphs. - -### AO* Algorithm (Java Implementation): - -```java -// Placeholder for a general AO* graph node -class AONode { - List children; - int cost; - boolean isANDNode; - - AONode(int cost, boolean isANDNode) { - this.cost = cost; - this.isANDNode = isANDNode; - children = new ArrayList<>(); - } -} - -class AOStar { - public static int aoStarSearch(AONode startNode) { - return search(startNode); - } - - private static int search(AONode node) { - if (node.children.isEmpty()) return node.cost; - - int totalCost = node.isANDNode ? 0 : Integer.MAX_VALUE; - for (AONode child : node.children) { - int childCost = search(child); - if (node.isANDNode) totalCost += childCost; - else totalCost = Math.min(totalCost, childCost); - } - return totalCost; - } -} -``` -### Applications of AO*: -Decision-Making in Expert Systems: Uses AND-OR logic for complex decisions. -Game Theory: Assesses multiple paths in strategic games. -Knowledge Representation: Maps complex rule-based systems. -### Summary: -AO* is powerful in scenarios involving both mandatory and optional paths (AND-OR) for reaching goals, making it ideal for expert systems and decision-making applications. diff --git a/docs/binary-search/Problem-Practice.md b/docs/binary-search/Problem-Practice.md index 67beac754..b1bae27c7 100644 --- a/docs/binary-search/Problem-Practice.md +++ b/docs/binary-search/Problem-Practice.md @@ -1,43 +1,43 @@ ---- -id: Practice-Problems-on-binary-search -title: Practice Problems -sidebar_label: Practice Problems -sidebar_position: 2 -description: Here are some practice problems for Binary Search, divided into topic-wise and difficulty-wise categories. -tags: [DSA, algorithms, binary search] ---- - -### Basic Problems: - -- [Search insert Position](https://leetcode.com/problems/search-insert-position?envType=problem-list-v2&envId=binary-search&difficulty=EASY) -- [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes?envType=problem-list-v2&envId=binary-search&difficulty=EASY) -- [Missing Number](https://leetcode.com/problems/missing-number?envType=problem-list-v2&envId=binary-search&difficulty=EASY) -- [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value?envType=problem-list-v2&envId=binary-search&difficulty=EASY) -- [First Bad Version](https://leetcode.com/problems/first-bad-version?envType=problem-list-v2&envId=binary-search&difficulty=EASY) -- [Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/description/) - - -### Intermediate Problems: - -- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) -- [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) -- [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) -- [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) -- [Find Peak Element](https://leetcode.com/problems/find-peak-element?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) -- [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/) -- [Aggressive cows](https://www.spoj.com/problems/AGGRCOW/) -- [Ugly Number III](https://leetcode.com/problems/ugly-number-iii/description/?envType=problem-list-v2&envId=binary-search) - -### Advanced Problems: - -- [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays?envType=problem-list-v2&envId=binary-search&difficulty=HARD) -- [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii?envType=problem-list-v2&envId=binary-search&difficulty=HARD) -- [Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels?envType=problem-list-v2&envId=binary-search&difficulty=HARD) -- [Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self?envType=problem-list-v2&envId=binary-search&difficulty=HARD) -- [Super Egg Drop](https://leetcode.com/problems/super-egg-drop/description/) - -### Challenges: - -- [Escape the Spreading Fire](https://leetcode.com/problems/escape-the-spreading-fire?envType=problem-list-v2&envId=binary-search&difficulty=HARD) -- [Number of Flowers in Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom?envType=problem-list-v2&envId=binary-search&difficulty=HARD) -- [Maximum Number of Robots Within Budget](https://leetcode.com/problems/maximum-number-of-robots-within-budget?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +--- +id: Practice-Problems-on-binary-search +title: Practice Problems +sidebar_label: Practice Problems +sidebar_position: 2 +description: Here are some practice problems for Binary Search, divided into topic-wise and difficulty-wise categories. +tags: [DSA, algorithms, binary search] +--- + +### Basic Problems: + +- [Search insert Position](https://leetcode.com/problems/search-insert-position?envType=problem-list-v2&envId=binary-search&difficulty=EASY) +- [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes?envType=problem-list-v2&envId=binary-search&difficulty=EASY) +- [Missing Number](https://leetcode.com/problems/missing-number?envType=problem-list-v2&envId=binary-search&difficulty=EASY) +- [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value?envType=problem-list-v2&envId=binary-search&difficulty=EASY) +- [First Bad Version](https://leetcode.com/problems/first-bad-version?envType=problem-list-v2&envId=binary-search&difficulty=EASY) +- [Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/description/) + + +### Intermediate Problems: + +- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) +- [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) +- [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) +- [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) +- [Find Peak Element](https://leetcode.com/problems/find-peak-element?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM) +- [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/) +- [Aggressive cows](https://www.spoj.com/problems/AGGRCOW/) +- [Ugly Number III](https://leetcode.com/problems/ugly-number-iii/description/?envType=problem-list-v2&envId=binary-search) + +### Advanced Problems: + +- [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +- [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +- [Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +- [Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +- [Super Egg Drop](https://leetcode.com/problems/super-egg-drop/description/) + +### Challenges: + +- [Escape the Spreading Fire](https://leetcode.com/problems/escape-the-spreading-fire?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +- [Number of Flowers in Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom?envType=problem-list-v2&envId=binary-search&difficulty=HARD) +- [Maximum Number of Robots Within Budget](https://leetcode.com/problems/maximum-number-of-robots-within-budget?envType=problem-list-v2&envId=binary-search&difficulty=HARD) diff --git a/docs/combinatorics/Practice-problems.md b/docs/combinatorics/Practice-problems.md index 857073a1e..761746f5f 100644 --- a/docs/combinatorics/Practice-problems.md +++ b/docs/combinatorics/Practice-problems.md @@ -1,160 +1,160 @@ ---- -id: Practice-Problems-on-Combinatorics -title: Practice Problems in Combinatorics -sidebar_label: Combinatorics Practice Problems -sidebar_position: 4 -description: A comprehensive list of practice problems focused on combinatorics, covering various topics and concepts. -tags: [DSA, algorithms, combinatorics, practice problems] ---- - -## Practice Problems on Combinatorics - -This section provides a list of practice problems focused on combinatorics, covering various concepts and applications. Each problem includes a clear description, example inputs and outputs, and hints or solutions where applicable. - -### Easy Problems: - -1. **Sum of All Subset XOR Totals** - **Description:** Given an array of integers, calculate the sum of the XOR totals of all possible subsets. The XOR of a subset is calculated by taking the XOR of all its elements. For instance, for the array `[1, 2]`, the subsets are `[]`, `[1]`, `[2]`, and `[1, 2]`, with their XOR totals being `0`, `1`, `2`, and `3`, respectively. Your task is to find the total sum of these XOR values. - - - **Example:** - Input: `[1, 2, 3]` - Output: `6` (Subsets: `[] -> 0`, `[1] -> 1`, `[2] -> 2`, `[3] -> 3`, `[1,2] -> 3`, `[1,3] -> 2`, `[2,3] -> 1`, `[1,2,3] -> 0`) - - - **Hint:** Use recursion or bit manipulation to generate all subsets. - - **Link:** [Sum of All Subset XOR Totals - LeetCode](https://leetcode.com/problems/sum-of-all-subset-xor-totals?envType=problem-list-v2&envId=combinatorics&difficulty=EASY) - -2. **Distribute Candies Among Children I** - **Description:** You have a certain number of candies to distribute among `k` children in such a way that each child receives at least one candy. The challenge is to maximize the number of children that receive candies while ensuring that no child receives more than one candy. Given `n` candies and `k` children, determine how many children can receive candies. - - - **Example:** - Input: `n = 7, k = 4` - Output: `4` (Each child can get at least one candy) - - - **Hint:** Use the formula for distribution and check constraints. - - **Link:** [Distribute Candies Among Children I - LeetCode](https://leetcode.com/problems/distribute-candies-among-children-i?envType=problem-list-v2&envId=combinatorics&difficulty=EASY) - ---- - -### Medium Problems: - -1. **Unique Paths** - **Description:** Given an `m x n` grid, count the number of unique paths from the top-left corner to the bottom-right corner, moving only down or to the right. The challenge is to implement an algorithm that computes this efficiently. - - - **Example:** - Input: `m = 3, n = 7` - Output: `28` (There are 28 unique paths in a 3x7 grid) - - - **Hint:** Use dynamic programming to store intermediate results. - - **Link:** [Unique Paths - LeetCode](https://leetcode.com/problems/unique-paths?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) - -2. **Ugly Number III** - **Description:** An ugly number is a positive number whose prime factors only include `2`, `3`, and `5`. Given an integer `n`, your task is to find the `n-th` ugly number. - - - **Example:** - Input: `n = 10` - Output: `12` (The first 10 ugly numbers are `1, 2, 3, 4, 5, 6, 8, 9, 10, 12`) - - - **Hint:** Consider a min-heap or dynamic programming to generate ugly numbers efficiently. - - **Link:** [Ugly Number III - LeetCode](https://leetcode.com/problems/ugly-number-iii?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) - -3. **Number of Sets of K Non-Overlapping Line Segments** - **Description:** Given an array of segments defined by their endpoints, count the number of ways to select `k` non-overlapping segments. - - - **Example:** - Input: `segments = [[1, 2], [2, 3], [3, 4]], k = 2` - Output: `1` (Only one way to select two non-overlapping segments) - - - **Hint:** Use combinatorial counting and dynamic programming. - - **Link:** [Number of Sets of K Non-Overlapping Line Segments - LeetCode](https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) - -4. **Vowels of All Substrings** - **Description:** Count the number of vowels in all substrings of a given string. Each vowel contributes to each substring it appears in. - - - **Example:** - Input: `s = "abc"` - Output: `3` (Vowels: `a` contributes to 1 substring, `b` and `c` contribute to 0) - - - **Hint:** Use a two-pointer technique to count contributions of each vowel. - - **Link:** [Vowels of All Substrings - LeetCode](https://leetcode.com/problems/vowels-of-all-substrings?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) - -5. **The Number of Beautiful Subsets** - **Description:** Determine the number of beautiful subsets of a given array based on specific conditions that define a beautiful subset. - - - **Example:** - Input: `nums = [1, 2, 3], condition = even sum` - Output: `4` (The beautiful subsets could be `[]`, `[2]`, `[1, 3]`, and `[1, 2, 3]`) - - - **Hint:** Apply a combinatorial approach to generate subsets and filter based on the condition. - - **Link:** [The Number of Beautiful Subsets - LeetCode](https://leetcode.com/problems/the-number-of-beautiful-subsets?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) - ---- - -### Hard Problems: - -1. **Poor Pigs** - **Description:** You have a certain number of pigs and buckets. Each bucket may contain either water or poison, and you need to find out which buckets are poisoned using the least number of pigs within a given time limit. - - - **Example:** - Input: `pigs = 1, buckets = 1000, minutes = 15, minutesToDie = 15` - Output: `1` (One pig is enough to find the poisoned bucket) - - - **Hint:** Use a binary approach to represent the pigs' tests. - - **Link:** [Poor Pigs - LeetCode](https://leetcode.com/problems/poor-pigs?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) - -2. **Kth Smallest Instructions** - **Description:** Given a number of `k`, your task is to find the `k-th` smallest instruction in a certain set of instructions. - - - **Example:** - Input: `n = 3, k = 5` - Output: `5` (Find the 5th smallest instruction) - - - **Hint:** Use combinatorial techniques to generate the set of instructions. - - **Link:** [Kth Smallest Instructions - LeetCode](https://leetcode.com/problems/kth-smallest-instructions?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) - -3. **Number of Music Playlists** - **Description:** Calculate the number of playlists of a given length that can be created under specific conditions, such as the maximum number of unique songs allowed in the playlist. - - - **Example:** - Input: `n = 3, l = 3, k = 1` - Output: `6` (Six different playlists can be created) - - - **Hint:** Use dynamic programming to keep track of playlists. - - **Link:** [Number of Music Playlists - LeetCode](https://leetcode.com/problems/number-of-music-playlists?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) - -4. **Number of Ways to Reorder Array to Get Same BST** - **Description:** Given an array, find the number of ways to reorder it to obtain the same binary search tree (BST). - - - **Example:** - Input: `arr = [2, 1, 3]` - Output: `1` (Only one way to order the array for the same BST structure) - - - **Hint:** Use combinatorial counting based on the properties of BST. - - **Link:** [Number of Ways to Reorder Array to Get Same BST - LeetCode](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) - -5. **Count the Number of Ideal Arrays** - **Description:** Count the number of ideal arrays based on certain properties defined in the problem. - - - **Example:** - Input: `n = 5, maxValue = 2` - Output: `7` (Count ideal arrays of length 5 with values not exceeding 2) - - - **Hint:** Use combinatorial counting and generating functions. - - **Link:** [Count the Number of Ideal Arrays - LeetCode](https://leetcode.com/problems/count-the-number-of-ideal-arrays?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) - ---- - -## Conclusion - -These problems are designed to strengthen your understanding of combinatorial mathematics. Make sure to attempt each problem and utilize the hints provided to assist your learning. Solutions may be found online for additional support. +--- +id: Practice-Problems-on-Combinatorics +title: Practice Problems in Combinatorics +sidebar_label: Combinatorics Practice Problems +sidebar_position: 4 +description: A comprehensive list of practice problems focused on combinatorics, covering various topics and concepts. +tags: [DSA, algorithms, combinatorics, practice problems] +--- + +## Practice Problems on Combinatorics + +This section provides a list of practice problems focused on combinatorics, covering various concepts and applications. Each problem includes a clear description, example inputs and outputs, and hints or solutions where applicable. + +### Easy Problems: + +1. **Sum of All Subset XOR Totals** + **Description:** Given an array of integers, calculate the sum of the XOR totals of all possible subsets. The XOR of a subset is calculated by taking the XOR of all its elements. For instance, for the array `[1, 2]`, the subsets are `[]`, `[1]`, `[2]`, and `[1, 2]`, with their XOR totals being `0`, `1`, `2`, and `3`, respectively. Your task is to find the total sum of these XOR values. + + - **Example:** + Input: `[1, 2, 3]` + Output: `6` (Subsets: `[] -> 0`, `[1] -> 1`, `[2] -> 2`, `[3] -> 3`, `[1,2] -> 3`, `[1,3] -> 2`, `[2,3] -> 1`, `[1,2,3] -> 0`) + + - **Hint:** Use recursion or bit manipulation to generate all subsets. + + **Link:** [Sum of All Subset XOR Totals - LeetCode](https://leetcode.com/problems/sum-of-all-subset-xor-totals?envType=problem-list-v2&envId=combinatorics&difficulty=EASY) + +2. **Distribute Candies Among Children I** + **Description:** You have a certain number of candies to distribute among `k` children in such a way that each child receives at least one candy. The challenge is to maximize the number of children that receive candies while ensuring that no child receives more than one candy. Given `n` candies and `k` children, determine how many children can receive candies. + + - **Example:** + Input: `n = 7, k = 4` + Output: `4` (Each child can get at least one candy) + + - **Hint:** Use the formula for distribution and check constraints. + + **Link:** [Distribute Candies Among Children I - LeetCode](https://leetcode.com/problems/distribute-candies-among-children-i?envType=problem-list-v2&envId=combinatorics&difficulty=EASY) + +--- + +### Medium Problems: + +1. **Unique Paths** + **Description:** Given an `m x n` grid, count the number of unique paths from the top-left corner to the bottom-right corner, moving only down or to the right. The challenge is to implement an algorithm that computes this efficiently. + + - **Example:** + Input: `m = 3, n = 7` + Output: `28` (There are 28 unique paths in a 3x7 grid) + + - **Hint:** Use dynamic programming to store intermediate results. + + **Link:** [Unique Paths - LeetCode](https://leetcode.com/problems/unique-paths?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) + +2. **Ugly Number III** + **Description:** An ugly number is a positive number whose prime factors only include `2`, `3`, and `5`. Given an integer `n`, your task is to find the `n-th` ugly number. + + - **Example:** + Input: `n = 10` + Output: `12` (The first 10 ugly numbers are `1, 2, 3, 4, 5, 6, 8, 9, 10, 12`) + + - **Hint:** Consider a min-heap or dynamic programming to generate ugly numbers efficiently. + + **Link:** [Ugly Number III - LeetCode](https://leetcode.com/problems/ugly-number-iii?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) + +3. **Number of Sets of K Non-Overlapping Line Segments** + **Description:** Given an array of segments defined by their endpoints, count the number of ways to select `k` non-overlapping segments. + + - **Example:** + Input: `segments = [[1, 2], [2, 3], [3, 4]], k = 2` + Output: `1` (Only one way to select two non-overlapping segments) + + - **Hint:** Use combinatorial counting and dynamic programming. + + **Link:** [Number of Sets of K Non-Overlapping Line Segments - LeetCode](https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) + +4. **Vowels of All Substrings** + **Description:** Count the number of vowels in all substrings of a given string. Each vowel contributes to each substring it appears in. + + - **Example:** + Input: `s = "abc"` + Output: `3` (Vowels: `a` contributes to 1 substring, `b` and `c` contribute to 0) + + - **Hint:** Use a two-pointer technique to count contributions of each vowel. + + **Link:** [Vowels of All Substrings - LeetCode](https://leetcode.com/problems/vowels-of-all-substrings?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) + +5. **The Number of Beautiful Subsets** + **Description:** Determine the number of beautiful subsets of a given array based on specific conditions that define a beautiful subset. + + - **Example:** + Input: `nums = [1, 2, 3], condition = even sum` + Output: `4` (The beautiful subsets could be `[]`, `[2]`, `[1, 3]`, and `[1, 2, 3]`) + + - **Hint:** Apply a combinatorial approach to generate subsets and filter based on the condition. + + **Link:** [The Number of Beautiful Subsets - LeetCode](https://leetcode.com/problems/the-number-of-beautiful-subsets?envType=problem-list-v2&envId=combinatorics&difficulty=MEDIUM) + +--- + +### Hard Problems: + +1. **Poor Pigs** + **Description:** You have a certain number of pigs and buckets. Each bucket may contain either water or poison, and you need to find out which buckets are poisoned using the least number of pigs within a given time limit. + + - **Example:** + Input: `pigs = 1, buckets = 1000, minutes = 15, minutesToDie = 15` + Output: `1` (One pig is enough to find the poisoned bucket) + + - **Hint:** Use a binary approach to represent the pigs' tests. + + **Link:** [Poor Pigs - LeetCode](https://leetcode.com/problems/poor-pigs?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) + +2. **Kth Smallest Instructions** + **Description:** Given a number of `k`, your task is to find the `k-th` smallest instruction in a certain set of instructions. + + - **Example:** + Input: `n = 3, k = 5` + Output: `5` (Find the 5th smallest instruction) + + - **Hint:** Use combinatorial techniques to generate the set of instructions. + + **Link:** [Kth Smallest Instructions - LeetCode](https://leetcode.com/problems/kth-smallest-instructions?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) + +3. **Number of Music Playlists** + **Description:** Calculate the number of playlists of a given length that can be created under specific conditions, such as the maximum number of unique songs allowed in the playlist. + + - **Example:** + Input: `n = 3, l = 3, k = 1` + Output: `6` (Six different playlists can be created) + + - **Hint:** Use dynamic programming to keep track of playlists. + + **Link:** [Number of Music Playlists - LeetCode](https://leetcode.com/problems/number-of-music-playlists?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) + +4. **Number of Ways to Reorder Array to Get Same BST** + **Description:** Given an array, find the number of ways to reorder it to obtain the same binary search tree (BST). + + - **Example:** + Input: `arr = [2, 1, 3]` + Output: `1` (Only one way to order the array for the same BST structure) + + - **Hint:** Use combinatorial counting based on the properties of BST. + + **Link:** [Number of Ways to Reorder Array to Get Same BST - LeetCode](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) + +5. **Count the Number of Ideal Arrays** + **Description:** Count the number of ideal arrays based on certain properties defined in the problem. + + - **Example:** + Input: `n = 5, maxValue = 2` + Output: `7` (Count ideal arrays of length 5 with values not exceeding 2) + + - **Hint:** Use combinatorial counting and generating functions. + + **Link:** [Count the Number of Ideal Arrays - LeetCode](https://leetcode.com/problems/count-the-number-of-ideal-arrays?envType=problem-list-v2&envId=combinatorics&difficulty=HARD) + +--- + +## Conclusion + +These problems are designed to strengthen your understanding of combinatorial mathematics. Make sure to attempt each problem and utilize the hints provided to assist your learning. Solutions may be found online for additional support. diff --git a/docs/graphs/Disjoint Set Union.md b/docs/graphs/Disjoint Set Union.md index 78b46c448..7249048af 100644 --- a/docs/graphs/Disjoint Set Union.md +++ b/docs/graphs/Disjoint Set Union.md @@ -1,169 +1,169 @@ ---- -id: disjoint-set-union -title: Disjoint Set Union (DSU) -sidebar_label: Introduction to Disjoint Set Union -description: 'The Disjoint Set Union (DSU) algorithm efficiently manages dynamic connectivity and union-find operations.' -tags: [dsa, data-structures, DSU, C language] ---- - -### Solutions: - - -## C++ - -```c -#include -using namespace std; - -class DisjointSetUnion { -public: - vector parent, rank; - - // Constructor to initialize the DSU - DisjointSetUnion(int n) { - parent.resize(n); - rank.resize(n, 1); - for (int i = 0; i < n; i++) { - parent[i] = i; - } - } - - // Find function with path compression - int find(int u) { - if (parent[u] != u) { - parent[u] = find(parent[u]); // Path compression - } - return parent[u]; - } - - // Union function with union by rank - void unionSets(int u, int v) { - int rootU = find(u); - int rootV = find(v); - - if (rootU != rootV) { - if (rank[rootU] > rank[rootV]) { - parent[rootV] = rootU; - } else if (rank[rootU] < rank[rootV]) { - parent[rootU] = rootV; - } else { - parent[rootV] = rootU; - rank[rootU]++; - } - } - } -}; - -// Example Usage -int main() { - DisjointSetUnion dsu(5); // Create 5 disjoint sets - dsu.unionSets(0, 1); - dsu.unionSets(1, 2); - cout << dsu.find(0) << endl; // Output: 0 - cout << dsu.find(1) << endl; // Output: 0 (due to union) - return 0; -} -``` - -## Java - -```java -public class DisjointSetUnion { - private int[] parent; - private int[] rank; - - // Constructor to initialize the DSU - public DisjointSetUnion(int n) { - parent = new int[n]; - rank = new int[n]; - for (int i = 0; i < n; i++) { - parent[i] = i; - rank[i] = 1; - } - } - - // Find function with path compression - public int find(int u) { - if (parent[u] != u) { - parent[u] = find(parent[u]); // Path compression - } - return parent[u]; - } - - // Union function with union by rank - public void union(int u, int v) { - int rootU = find(u); - int rootV = find(v); - - if (rootU != rootV) { - if (rank[rootU] > rank[rootV]) { - parent[rootV] = rootU; - } else if (rank[rootU] < rank[rootV]) { - parent[rootU] = rootV; - } else { - parent[rootV] = rootU; - rank[rootU]++; - } - } - } - - // Example Usage - public static void main(String[] args) { - DisjointSetUnion dsu = new DisjointSetUnion(5); // Create 5 disjoint sets - dsu.union(0, 1); - dsu.union(1, 2); - System.out.println(dsu.find(0)); // Output: 0 - System.out.println(dsu.find(1)); // Output: 0 (due to union) - } -} -``` - -## Python - -```python -class DisjointSetUnion: - def __init__(self, n): - self.parent = list(range(n)) - self.rank = [1] * n - - # Find function with path compression - def find(self, u): - if self.parent[u] != u: - self.parent[u] = self.find(self.parent[u]) # Path compression - return self.parent[u] - - # Union function with union by rank - def union(self, u, v): - rootU = self.find(u) - rootV = self.find(v) - - if rootU != rootV: - if self.rank[rootU] > self.rank[rootV]: - self.parent[rootV] = rootU - elif self.rank[rootU] < self.rank[rootV]: - self.parent[rootU] = rootV - else: - self.parent[rootV] = rootU - self.rank[rootU] += 1 - -# Example Usage -dsu = DisjointSetUnion(5) # Create 5 disjoint sets -dsu.union(0, 1) -dsu.union(1, 2) -print(dsu.find(0)) # Output: 0 -print(dsu.find(1)) # Output: 0 (due to union) - -``` - - - -## Key Concepts: - -➢ Path Compression: When performing the find operation, we make all nodes - point directly to the root, flattening the structure and speeding up future operations. -➢ Union by Rank: The smaller tree is attached under the root of the larger - tree to keep the tree as flat as possible, improving the efficiency of find operations. - - - +--- +id: disjoint-set-union +title: Disjoint Set Union (DSU) +sidebar_label: Introduction to Disjoint Set Union +description: 'The Disjoint Set Union (DSU) algorithm efficiently manages dynamic connectivity and union-find operations.' +tags: [dsa, data-structures, DSU, C language] +--- + +### Solutions: + + +## C++ + +```c +#include +using namespace std; + +class DisjointSetUnion { +public: + vector parent, rank; + + // Constructor to initialize the DSU + DisjointSetUnion(int n) { + parent.resize(n); + rank.resize(n, 1); + for (int i = 0; i < n; i++) { + parent[i] = i; + } + } + + // Find function with path compression + int find(int u) { + if (parent[u] != u) { + parent[u] = find(parent[u]); // Path compression + } + return parent[u]; + } + + // Union function with union by rank + void unionSets(int u, int v) { + int rootU = find(u); + int rootV = find(v); + + if (rootU != rootV) { + if (rank[rootU] > rank[rootV]) { + parent[rootV] = rootU; + } else if (rank[rootU] < rank[rootV]) { + parent[rootU] = rootV; + } else { + parent[rootV] = rootU; + rank[rootU]++; + } + } + } +}; + +// Example Usage +int main() { + DisjointSetUnion dsu(5); // Create 5 disjoint sets + dsu.unionSets(0, 1); + dsu.unionSets(1, 2); + cout << dsu.find(0) << endl; // Output: 0 + cout << dsu.find(1) << endl; // Output: 0 (due to union) + return 0; +} +``` + +## Java + +```java +public class DisjointSetUnion { + private int[] parent; + private int[] rank; + + // Constructor to initialize the DSU + public DisjointSetUnion(int n) { + parent = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + rank[i] = 1; + } + } + + // Find function with path compression + public int find(int u) { + if (parent[u] != u) { + parent[u] = find(parent[u]); // Path compression + } + return parent[u]; + } + + // Union function with union by rank + public void union(int u, int v) { + int rootU = find(u); + int rootV = find(v); + + if (rootU != rootV) { + if (rank[rootU] > rank[rootV]) { + parent[rootV] = rootU; + } else if (rank[rootU] < rank[rootV]) { + parent[rootU] = rootV; + } else { + parent[rootV] = rootU; + rank[rootU]++; + } + } + } + + // Example Usage + public static void main(String[] args) { + DisjointSetUnion dsu = new DisjointSetUnion(5); // Create 5 disjoint sets + dsu.union(0, 1); + dsu.union(1, 2); + System.out.println(dsu.find(0)); // Output: 0 + System.out.println(dsu.find(1)); // Output: 0 (due to union) + } +} +``` + +## Python + +```python +class DisjointSetUnion: + def __init__(self, n): + self.parent = list(range(n)) + self.rank = [1] * n + + # Find function with path compression + def find(self, u): + if self.parent[u] != u: + self.parent[u] = self.find(self.parent[u]) # Path compression + return self.parent[u] + + # Union function with union by rank + def union(self, u, v): + rootU = self.find(u) + rootV = self.find(v) + + if rootU != rootV: + if self.rank[rootU] > self.rank[rootV]: + self.parent[rootV] = rootU + elif self.rank[rootU] < self.rank[rootV]: + self.parent[rootU] = rootV + else: + self.parent[rootV] = rootU + self.rank[rootU] += 1 + +# Example Usage +dsu = DisjointSetUnion(5) # Create 5 disjoint sets +dsu.union(0, 1) +dsu.union(1, 2) +print(dsu.find(0)) # Output: 0 +print(dsu.find(1)) # Output: 0 (due to union) + +``` + + + +## Key Concepts: + +➢ Path Compression: When performing the find operation, we make all nodes + point directly to the root, flattening the structure and speeding up future operations. +➢ Union by Rank: The smaller tree is attached under the root of the larger + tree to keep the tree as flat as possible, improving the efficiency of find operations. + + + All three implementations support efficient find and union operations with a time complexity of nearly O(1) due to path compression and union by rank. \ No newline at end of file diff --git a/docs/hash/_category_.json b/docs/hash/_category_.json index 4f6772765..4e5434df8 100644 --- a/docs/hash/_category_.json +++ b/docs/hash/_category_.json @@ -1,8 +1,8 @@ -{ - "label": "Hash tables", - "position": 14, - "link": { - "type": "generated-index", - "description": "A Hash Table is a data structure designed to be fast to work with." - } - } +{ + "label": "Hash tables", + "position": 14, + "link": { + "type": "generated-index", + "description": "A Hash Table is a data structure designed to be fast to work with." + } + } diff --git a/docs/hash/hash-tables.md b/docs/hash/hash-tables.md index 11f52291e..49c47503b 100644 --- a/docs/hash/hash-tables.md +++ b/docs/hash/hash-tables.md @@ -1,127 +1,127 @@ ---- -id: hash-tables-dsa -sidebar_position: 1 -title: Hash tables -sidebar_label: Hash tables -description: "In this blog post, we'll dive into the Hash tables and implementations of hash table, a fundamental topic in Data Structures" -tags: [dsa, Hashtables, Hashmaps] ---- - -## Introduction - -Hashing is a technique to convert a range of key values into a range of indexes of an array. To get the idea of what a Hash Table is, let's try to build one from scratch to store unique first names inside it. - -We will build the Hash Set in 5 steps: - -1. Starting with an array. -2. Storing names using a hash function. -3. Looking up an element using a hash function. -4. Handling collisions. -5. The basic Hash Set code example and simulation. - -## Implementation - -### Basic Operations - -Following are the basic primary operations of a hash table: - -- **Search** - Searches an element in a hash table. -- **Insert** - Inserts an element in a hash table. -- **Delete** - Deletes an element from a hash table. - -### 1. Search Operation - -Whenever an element is to be searched, compute the hash code of the key passed and locate the element using that hash code as index in the array. Use linear probing to get the element ahead if the element is not found at the computed hash code. - -```cpp -struct DataItem { - int data; - int key; -}; - -struct DataItem* search(int key) { - // get the hash - int hashIndex = hashCode(key); - - // move in array until an empty - while (hashArray[hashIndex] != NULL) { - if (hashArray[hashIndex]->key == key) - return hashArray[hashIndex]; - - // go to next cell - ++hashIndex; - - // wrap around the table - hashIndex %= SIZE; - } - - return NULL; -} -``` -### 2. Insert Operation - -Whenever an element is to be inserted, compute the hash code of the key passed and locate the index using that hash code as an index in the array. Use linear probing for an empty location if an element is found at the computed hash code. - -```cpp -void insert(int key, int data) { - struct DataItem* item = (struct DataItem*) malloc(sizeof(struct DataItem)); - item->data = data; - item->key = key; - - // get the hash - int hashIndex = hashCode(key); - - // move in array until an empty or deleted cell - while (hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { - // go to next cell - ++hashIndex; - - // wrap around the table - hashIndex %= SIZE; - } - - hashArray[hashIndex] = item; -} -``` -### 3. Delete Operation - -Whenever an element is to be deleted, compute the hash code of the key passed and locate the index using that hash code as an index in the array. Use linear probing to get the element ahead if an element is not found at the computed hash code. When found, store a dummy item there to keep the performance of the hash table intact. - -```cpp -struct DataItem* deleteItem(struct DataItem* item) { - int key = item->key; - - // get the hash - int hashIndex = hashCode(key); - - // move in array until an empty - while (hashArray[hashIndex] != NULL) { - if (hashArray[hashIndex]->key == key) { - struct DataItem* temp = hashArray[hashIndex]; - - // assign a dummy item at deleted position - hashArray[hashIndex] = dummyItem; - return temp; - } - - // go to next cell - ++hashIndex; - - // wrap around the table - hashIndex %= SIZE; - } - - return NULL; -} -``` -### Time Complexity -For lookup, insertion, and deletion operations, hash tables have an average-case time complexity of O(1). However, these operations may, in the worst case, require O(n) time, where n is the number of elements in the table. -### Space Complexity -The space complexity of a hash table is O(n), where n is the number of elements in the -table. This is because each element is stored in a separate cell in the array. - -### Applications of Hash Table -Hash tables are frequently used for indexing and searching massive volumes of data. A search engine might use a hash table to store the web pages that it has indexed. -Data is usually cached in memory via hash tables, enabling rapid access to frequently used information. -Hash functions are frequently used in cryptography to create digital signatures, validate data, and guarantee data integrity. -Hash tables can be used for implementing database indexes, enabling fast access to data based on key values. +--- +id: hash-tables-dsa +sidebar_position: 1 +title: Hash tables +sidebar_label: Hash tables +description: "In this blog post, we'll dive into the Hash tables and implementations of hash table, a fundamental topic in Data Structures" +tags: [dsa, Hashtables, Hashmaps] +--- + +## Introduction + +Hashing is a technique to convert a range of key values into a range of indexes of an array. To get the idea of what a Hash Table is, let's try to build one from scratch to store unique first names inside it. + +We will build the Hash Set in 5 steps: + +1. Starting with an array. +2. Storing names using a hash function. +3. Looking up an element using a hash function. +4. Handling collisions. +5. The basic Hash Set code example and simulation. + +## Implementation + +### Basic Operations + +Following are the basic primary operations of a hash table: + +- **Search** - Searches an element in a hash table. +- **Insert** - Inserts an element in a hash table. +- **Delete** - Deletes an element from a hash table. + +### 1. Search Operation + +Whenever an element is to be searched, compute the hash code of the key passed and locate the element using that hash code as index in the array. Use linear probing to get the element ahead if the element is not found at the computed hash code. + +```cpp +struct DataItem { + int data; + int key; +}; + +struct DataItem* search(int key) { + // get the hash + int hashIndex = hashCode(key); + + // move in array until an empty + while (hashArray[hashIndex] != NULL) { + if (hashArray[hashIndex]->key == key) + return hashArray[hashIndex]; + + // go to next cell + ++hashIndex; + + // wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} +``` +### 2. Insert Operation + +Whenever an element is to be inserted, compute the hash code of the key passed and locate the index using that hash code as an index in the array. Use linear probing for an empty location if an element is found at the computed hash code. + +```cpp +void insert(int key, int data) { + struct DataItem* item = (struct DataItem*) malloc(sizeof(struct DataItem)); + item->data = data; + item->key = key; + + // get the hash + int hashIndex = hashCode(key); + + // move in array until an empty or deleted cell + while (hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { + // go to next cell + ++hashIndex; + + // wrap around the table + hashIndex %= SIZE; + } + + hashArray[hashIndex] = item; +} +``` +### 3. Delete Operation + +Whenever an element is to be deleted, compute the hash code of the key passed and locate the index using that hash code as an index in the array. Use linear probing to get the element ahead if an element is not found at the computed hash code. When found, store a dummy item there to keep the performance of the hash table intact. + +```cpp +struct DataItem* deleteItem(struct DataItem* item) { + int key = item->key; + + // get the hash + int hashIndex = hashCode(key); + + // move in array until an empty + while (hashArray[hashIndex] != NULL) { + if (hashArray[hashIndex]->key == key) { + struct DataItem* temp = hashArray[hashIndex]; + + // assign a dummy item at deleted position + hashArray[hashIndex] = dummyItem; + return temp; + } + + // go to next cell + ++hashIndex; + + // wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} +``` +### Time Complexity +For lookup, insertion, and deletion operations, hash tables have an average-case time complexity of O(1). However, these operations may, in the worst case, require O(n) time, where n is the number of elements in the table. +### Space Complexity +The space complexity of a hash table is O(n), where n is the number of elements in the +table. This is because each element is stored in a separate cell in the array. + +### Applications of Hash Table +Hash tables are frequently used for indexing and searching massive volumes of data. A search engine might use a hash table to store the web pages that it has indexed. +Data is usually cached in memory via hash tables, enabling rapid access to frequently used information. +Hash functions are frequently used in cryptography to create digital signatures, validate data, and guarantee data integrity. +Hash tables can be used for implementing database indexes, enabling fast access to data based on key values. diff --git a/docs/heap/time-complexity.md b/docs/heap/time-complexity.md index 3e6a2c204..594d67e31 100644 --- a/docs/heap/time-complexity.md +++ b/docs/heap/time-complexity.md @@ -1,211 +1,211 @@ ---- -id: Heap-Operations-Time-Complexity -title: Detailed Time Complexity of Heap Operations -sidebar_label: Heap Time Complexity -sidebar_position: 3 -description: A comprehensive guide covering the time complexity of various operations associated with binary heaps, including rationale and examples. -tags: [DSA, algorithms, heaps, time complexity] ---- - -## Heap Operations and Their Time Complexities - -A **binary heap** is a complete binary tree often used to implement priority queues. It can be a **min-heap** (parent nodes are smaller than their children) or a **max-heap** (parent nodes are larger). Binary heaps support several key operations, such as insertion, deletion, and more. Below is a breakdown of these operations, their time complexities, and detailed explanations. - -### 1. Insertion (Insert a New Element) - -- **Time Complexity:** **O(log n)** -- **Explanation:** - Inserting an element into a heap involves two steps: - - 1. The new element is placed at the end of the heap. - 2. The element is then "bubbled up" to its correct position to restore the heap property. - - Since the heap is a complete binary tree, its height is proportional to `log n`. Thus, bubbling up the element takes at most `log n` comparisons and swaps. - -- **Example:** - Consider inserting the number `2` into a min-heap: - ``` - 3 - / \ - 5 7 - / \ - 8 9 - ``` - After insertion: - ``` - 3 - / \ - 5 7 - / \ \ - 8 9 2 - ``` - The element `2` is smaller than its parent `7`, so it bubbles up: - ``` - 3 - / \ - 5 2 - / \ \ - 8 9 7 - ``` - -### 2. Deletion (Extracting the Root) - -- **Time Complexity:** **O(log n)** -- **Explanation:** - Deleting the root (the smallest or largest element in a min-heap or max-heap) is one of the key operations. It involves: - - 1. Replacing the root with the last element in the heap. - 2. "Bubbling down" the new root to maintain the heap property. - - Bubbling down requires comparing and swapping the new root with its children to ensure the heap remains valid. This process can take up to `log n` steps due to the height of the heap. - -- **Example:** - Consider the following max-heap before and after extracting the root (value `9`): - ``` - 9 - / \ - 7 8 - / \ - 6 4 - ``` - After extracting the root and replacing it with the last element `4`: - ``` - 4 - / \ - 7 8 - / - 6 - ``` - The element `4` bubbles down to its correct position: - ``` - 8 - / \ - 7 4 - / - 6 - ``` - -### 3. Heapify (Building a Heap from an Array) - -- **Time Complexity:** **O(n)** -- **Explanation:** - Heapifying an unsorted array to form a valid heap is done in linear time, although it may seem like `O(n log n)`. This is because, during heap construction, the number of operations decreases significantly for elements at lower levels of the tree. Elements closer to the root require more comparisons, but there are fewer such elements. - -- **Example:** - For an array `[4, 10, 3, 5, 1]`, the heapify process builds the following min-heap: - ``` - 1 - / \ - 5 3 - / \ - 10 4 - ``` - -### 4. Peek (Getting the Root) - -- **Time Complexity:** **O(1)** -- **Explanation:** - The root of the heap (either the minimum or maximum element) can be accessed in constant time because it is always at the top of the heap. - -- **Example:** - In the min-heap: - ``` - 1 - / \ - 5 3 - / \ - 10 4 - ``` - Accessing the root (`1`) takes constant time. - -### 5. Decrease Key (For Priority Queues) - -- **Time Complexity:** **O(log n)** -- **Explanation:** - In priority queues, we may need to decrease the key value of a particular element. This involves: - - 1. Reducing the key value. - 2. "Bubbling up" the element to restore the heap property. - - Since bubbling up takes `O(log n)` time, decreasing a key takes logarithmic time as well. - -- **Example:** - If we decrease the key value of the node `10` in a min-heap to `2`, it may need to bubble up to maintain the heap property: - ``` - 1 - / \ - 5 3 - / \ - 2 4 - ``` - -### 6. Delete a Key (Removing an Arbitrary Element) - -- **Time Complexity:** **O(log n)** -- **Explanation:** - To delete a specific element from the heap: - - 1. Replace the element with the last node in the heap. - 2. Restore the heap property by either bubbling up or bubbling down. - - Both of these operations take `O(log n)` time because they depend on the height of the heap. - -- **Example:** - Consider deleting the element `5` from the min-heap: - - ``` - 1 - / \ - 5 3 - / \ - 10 4 - ``` - - After replacing `5` with the last element `4`: - - ``` - 1 - / \ - 4 3 - / - 10 - ``` - - The heap is already valid, so no further adjustments are needed. - ---- - -## Summary Table of Heap Operation Time Complexities - -| Operation | Time Complexity | -| ----------------------- | --------------- | -| Insertion | O(log n) | -| Deletion (Extract Root) | O(log n) | -| Heapify (Build a Heap) | O(n) | -| Peek (Get Root) | O(1) | -| Decrease Key | O(log n) | -| Delete a Key | O(log n) | - ---- - -## Explanation of Time Complexities - -### Why is Heapify O(n)? - -Heapify has a time complexity of `O(n)` because elements at the lowest levels of the tree require fewer comparisons. If you think about the number of operations needed for nodes at different levels of the tree: - -- For nodes at the bottom level, no swaps are needed. -- For nodes at the next level up, only one comparison and swap are needed. -- For nodes higher up, more swaps are required, but there are fewer of these nodes. - -The sum of these operations across the entire tree results in a linear time complexity of `O(n)`. - -### Why is Insertion and Deletion O(log n)? - -Both insertion and deletion involve restructuring the heap by bubbling elements up or down. Since the heap is a complete binary tree, its height is `log n`, meaning that in the worst case, you only need to perform `log n` swaps. - -This logarithmic behavior makes heaps extremely efficient for use cases like priority queues, where fast insertions and deletions are crucial. - ---- - -Understanding the time complexities of heap operations is fundamental when implementing or optimizing algorithms involving heaps, such as scheduling algorithms, Dijkstra's shortest path, or priority queues. The balance between constant-time root access and logarithmic-time inserts/deletes makes heaps ideal for many real-world applications. +--- +id: Heap-Operations-Time-Complexity +title: Detailed Time Complexity of Heap Operations +sidebar_label: Heap Time Complexity +sidebar_position: 3 +description: A comprehensive guide covering the time complexity of various operations associated with binary heaps, including rationale and examples. +tags: [DSA, algorithms, heaps, time complexity] +--- + +## Heap Operations and Their Time Complexities + +A **binary heap** is a complete binary tree often used to implement priority queues. It can be a **min-heap** (parent nodes are smaller than their children) or a **max-heap** (parent nodes are larger). Binary heaps support several key operations, such as insertion, deletion, and more. Below is a breakdown of these operations, their time complexities, and detailed explanations. + +### 1. Insertion (Insert a New Element) + +- **Time Complexity:** **O(log n)** +- **Explanation:** + Inserting an element into a heap involves two steps: + + 1. The new element is placed at the end of the heap. + 2. The element is then "bubbled up" to its correct position to restore the heap property. + + Since the heap is a complete binary tree, its height is proportional to `log n`. Thus, bubbling up the element takes at most `log n` comparisons and swaps. + +- **Example:** + Consider inserting the number `2` into a min-heap: + ``` + 3 + / \ + 5 7 + / \ + 8 9 + ``` + After insertion: + ``` + 3 + / \ + 5 7 + / \ \ + 8 9 2 + ``` + The element `2` is smaller than its parent `7`, so it bubbles up: + ``` + 3 + / \ + 5 2 + / \ \ + 8 9 7 + ``` + +### 2. Deletion (Extracting the Root) + +- **Time Complexity:** **O(log n)** +- **Explanation:** + Deleting the root (the smallest or largest element in a min-heap or max-heap) is one of the key operations. It involves: + + 1. Replacing the root with the last element in the heap. + 2. "Bubbling down" the new root to maintain the heap property. + + Bubbling down requires comparing and swapping the new root with its children to ensure the heap remains valid. This process can take up to `log n` steps due to the height of the heap. + +- **Example:** + Consider the following max-heap before and after extracting the root (value `9`): + ``` + 9 + / \ + 7 8 + / \ + 6 4 + ``` + After extracting the root and replacing it with the last element `4`: + ``` + 4 + / \ + 7 8 + / + 6 + ``` + The element `4` bubbles down to its correct position: + ``` + 8 + / \ + 7 4 + / + 6 + ``` + +### 3. Heapify (Building a Heap from an Array) + +- **Time Complexity:** **O(n)** +- **Explanation:** + Heapifying an unsorted array to form a valid heap is done in linear time, although it may seem like `O(n log n)`. This is because, during heap construction, the number of operations decreases significantly for elements at lower levels of the tree. Elements closer to the root require more comparisons, but there are fewer such elements. + +- **Example:** + For an array `[4, 10, 3, 5, 1]`, the heapify process builds the following min-heap: + ``` + 1 + / \ + 5 3 + / \ + 10 4 + ``` + +### 4. Peek (Getting the Root) + +- **Time Complexity:** **O(1)** +- **Explanation:** + The root of the heap (either the minimum or maximum element) can be accessed in constant time because it is always at the top of the heap. + +- **Example:** + In the min-heap: + ``` + 1 + / \ + 5 3 + / \ + 10 4 + ``` + Accessing the root (`1`) takes constant time. + +### 5. Decrease Key (For Priority Queues) + +- **Time Complexity:** **O(log n)** +- **Explanation:** + In priority queues, we may need to decrease the key value of a particular element. This involves: + + 1. Reducing the key value. + 2. "Bubbling up" the element to restore the heap property. + + Since bubbling up takes `O(log n)` time, decreasing a key takes logarithmic time as well. + +- **Example:** + If we decrease the key value of the node `10` in a min-heap to `2`, it may need to bubble up to maintain the heap property: + ``` + 1 + / \ + 5 3 + / \ + 2 4 + ``` + +### 6. Delete a Key (Removing an Arbitrary Element) + +- **Time Complexity:** **O(log n)** +- **Explanation:** + To delete a specific element from the heap: + + 1. Replace the element with the last node in the heap. + 2. Restore the heap property by either bubbling up or bubbling down. + + Both of these operations take `O(log n)` time because they depend on the height of the heap. + +- **Example:** + Consider deleting the element `5` from the min-heap: + + ``` + 1 + / \ + 5 3 + / \ + 10 4 + ``` + + After replacing `5` with the last element `4`: + + ``` + 1 + / \ + 4 3 + / + 10 + ``` + + The heap is already valid, so no further adjustments are needed. + +--- + +## Summary Table of Heap Operation Time Complexities + +| Operation | Time Complexity | +| ----------------------- | --------------- | +| Insertion | O(log n) | +| Deletion (Extract Root) | O(log n) | +| Heapify (Build a Heap) | O(n) | +| Peek (Get Root) | O(1) | +| Decrease Key | O(log n) | +| Delete a Key | O(log n) | + +--- + +## Explanation of Time Complexities + +### Why is Heapify O(n)? + +Heapify has a time complexity of `O(n)` because elements at the lowest levels of the tree require fewer comparisons. If you think about the number of operations needed for nodes at different levels of the tree: + +- For nodes at the bottom level, no swaps are needed. +- For nodes at the next level up, only one comparison and swap are needed. +- For nodes higher up, more swaps are required, but there are fewer of these nodes. + +The sum of these operations across the entire tree results in a linear time complexity of `O(n)`. + +### Why is Insertion and Deletion O(log n)? + +Both insertion and deletion involve restructuring the heap by bubbling elements up or down. Since the heap is a complete binary tree, its height is `log n`, meaning that in the worst case, you only need to perform `log n` swaps. + +This logarithmic behavior makes heaps extremely efficient for use cases like priority queues, where fast insertions and deletions are crucial. + +--- + +Understanding the time complexities of heap operations is fundamental when implementing or optimizing algorithms involving heaps, such as scheduling algorithms, Dijkstra's shortest path, or priority queues. The balance between constant-time root access and logarithmic-time inserts/deletes makes heaps ideal for many real-world applications. diff --git a/docs/machine-learning/XGBoost.md b/docs/machine-learning/XGBoost.md index 284c8f07e..4836aebd7 100644 --- a/docs/machine-learning/XGBoost.md +++ b/docs/machine-learning/XGBoost.md @@ -1,102 +1,102 @@ ---- - -id: xgboost -title: XGBoost Algorithm -sidebar_label: XGBoost -description: "XGBoost is a highly efficient and scalable machine learning algorithm known for its accuracy and speed in solving both classification and regression problems." -tags: [machine learning, algorithms, xgboost, classification, regression] - ---- - -### Definition: -**XGBoost (eXtreme Gradient Boosting)** is a supervised learning algorithm that implements gradient boosting for classification and regression tasks. It builds an ensemble of decision trees in a sequential manner, where each subsequent tree aims to reduce the errors of the previous trees, improving accuracy through boosting techniques. - -### Characteristics: -- **Boosting Technique**: - XGBoost uses a boosting method where weak learners (shallow trees) are combined iteratively to create a strong predictive model. Each tree tries to correct the errors made by the previous one, focusing on harder-to-predict instances. - -- **Highly Efficient**: - XGBoost is known for its speed and performance optimizations, utilizing techniques such as parallel tree boosting and hardware optimization to handle large-scale datasets efficiently. - -- **Regularization**: - Unlike traditional boosting, XGBoost includes regularization parameters to prevent overfitting, making it a robust choice even for noisy data. - - -### Steps Involved: -1. **Initialize the Model**: - XGBoost starts by initializing predictions with a base value (such as the average of the target values in regression). - -2. **Fit Gradient-Boosted Trees**: - Sequentially add decision trees, each one trained to reduce the residual errors of the model’s predictions from the previous iteration. - -3. **Update Weights**: - At each step, the algorithm updates the weights of misclassified instances, assigning higher weights to the harder-to-predict instances in classification or high-error instances in regression. - -4. **Predict and Aggregate**: - The final model aggregates the predictions of all trees, weighted by their learning rates, to output the final classification or regression prediction. - -### Problem Statement: -Given a dataset, the goal of XGBoost is to iteratively build a model that minimizes the prediction error by adding trees that improve upon the mistakes of previous ones, effectively handling both classification and regression tasks. - -### Key Concepts: -- **Boosting**: - A technique that combines multiple weak learners (e.g., shallow decision trees) into a strong predictive model. - -- **Learning Rate**: - A parameter that scales the contribution of each new tree added to the model, balancing the trade-off between the speed of learning and generalization. - -- **Max Depth**: - Limits the depth of the trees to prevent overfitting, controlling model complexity. - -### Objective Function: -The objective function minimized by XGBoost is defined as: - -$Obj(\Theta) = \sum_{i=1}^{n} L(y_i, \hat{y}) + \sum_{k=1}^{K} \Omega(f_k)$ - - - -Where: -- $L(y_i, \hat{y}_i)$ is the loss function measuring the difference between true values ($y_i$) and predicted values \($\hat{y}_i$). -- $\Omega(f_k)$ is the regularization term penalizing the complexity of the model. - -### Time Complexity: -- **Best, Average, and Worst Case: $O(n \log n)$** - XGBoost optimizes tree construction with a greedy algorithm, achieving logarithmic time complexity for each tree based on the number of training instances `n`. - -### Space Complexity: -- **Space Complexity: $O(n)$** - The memory footprint grows with the number of data points, as XGBoost needs to store gradient and Hessian information for each instance during training. - -### Python Implementation: -Here is a basic implementation of XGBoost in Python using the **XGBoost** library: - -```python -import xgboost as xgb -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_boston -from sklearn.metrics import mean_squared_error - -# Load dataset -data = load_boston() -X, y = data.data, data.target - -# Split into training and testing sets -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) - -# Create XGBoost model -model = xgb.XGBRegressor(objective='reg:squarederror', n_estimators=100, learning_rate=0.1) - -# Train model -model.fit(X_train, y_train) - -# Make predictions -predictions = model.predict(X_test) - -# Calculate mean squared error -mse = mean_squared_error(y_test, predictions) -print(f'Mean Squared Error: {mse}') -``` - -### Summary: -**XGBoost** is a powerful, efficient, and scalable machine learning algorithm. Its regularization capabilities, combined with its use of gradient boosting, make it a popular choice for a wide range of tasks. - +--- + +id: xgboost +title: XGBoost Algorithm +sidebar_label: XGBoost +description: "XGBoost is a highly efficient and scalable machine learning algorithm known for its accuracy and speed in solving both classification and regression problems." +tags: [machine learning, algorithms, xgboost, classification, regression] + +--- + +### Definition: +**XGBoost (eXtreme Gradient Boosting)** is a supervised learning algorithm that implements gradient boosting for classification and regression tasks. It builds an ensemble of decision trees in a sequential manner, where each subsequent tree aims to reduce the errors of the previous trees, improving accuracy through boosting techniques. + +### Characteristics: +- **Boosting Technique**: + XGBoost uses a boosting method where weak learners (shallow trees) are combined iteratively to create a strong predictive model. Each tree tries to correct the errors made by the previous one, focusing on harder-to-predict instances. + +- **Highly Efficient**: + XGBoost is known for its speed and performance optimizations, utilizing techniques such as parallel tree boosting and hardware optimization to handle large-scale datasets efficiently. + +- **Regularization**: + Unlike traditional boosting, XGBoost includes regularization parameters to prevent overfitting, making it a robust choice even for noisy data. + + +### Steps Involved: +1. **Initialize the Model**: + XGBoost starts by initializing predictions with a base value (such as the average of the target values in regression). + +2. **Fit Gradient-Boosted Trees**: + Sequentially add decision trees, each one trained to reduce the residual errors of the model’s predictions from the previous iteration. + +3. **Update Weights**: + At each step, the algorithm updates the weights of misclassified instances, assigning higher weights to the harder-to-predict instances in classification or high-error instances in regression. + +4. **Predict and Aggregate**: + The final model aggregates the predictions of all trees, weighted by their learning rates, to output the final classification or regression prediction. + +### Problem Statement: +Given a dataset, the goal of XGBoost is to iteratively build a model that minimizes the prediction error by adding trees that improve upon the mistakes of previous ones, effectively handling both classification and regression tasks. + +### Key Concepts: +- **Boosting**: + A technique that combines multiple weak learners (e.g., shallow decision trees) into a strong predictive model. + +- **Learning Rate**: + A parameter that scales the contribution of each new tree added to the model, balancing the trade-off between the speed of learning and generalization. + +- **Max Depth**: + Limits the depth of the trees to prevent overfitting, controlling model complexity. + +### Objective Function: +The objective function minimized by XGBoost is defined as: + +$Obj(\Theta) = \sum_{i=1}^{n} L(y_i, \hat{y}) + \sum_{k=1}^{K} \Omega(f_k)$ + + + +Where: +- $L(y_i, \hat{y}_i)$ is the loss function measuring the difference between true values ($y_i$) and predicted values \($\hat{y}_i$). +- $\Omega(f_k)$ is the regularization term penalizing the complexity of the model. + +### Time Complexity: +- **Best, Average, and Worst Case: $O(n \log n)$** + XGBoost optimizes tree construction with a greedy algorithm, achieving logarithmic time complexity for each tree based on the number of training instances `n`. + +### Space Complexity: +- **Space Complexity: $O(n)$** + The memory footprint grows with the number of data points, as XGBoost needs to store gradient and Hessian information for each instance during training. + +### Python Implementation: +Here is a basic implementation of XGBoost in Python using the **XGBoost** library: + +```python +import xgboost as xgb +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_boston +from sklearn.metrics import mean_squared_error + +# Load dataset +data = load_boston() +X, y = data.data, data.target + +# Split into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Create XGBoost model +model = xgb.XGBRegressor(objective='reg:squarederror', n_estimators=100, learning_rate=0.1) + +# Train model +model.fit(X_train, y_train) + +# Make predictions +predictions = model.predict(X_test) + +# Calculate mean squared error +mse = mean_squared_error(y_test, predictions) +print(f'Mean Squared Error: {mse}') +``` + +### Summary: +**XGBoost** is a powerful, efficient, and scalable machine learning algorithm. Its regularization capabilities, combined with its use of gradient boosting, make it a popular choice for a wide range of tasks. + diff --git a/docs/machine-learning/principal_component_analysis.md b/docs/machine-learning/principal_component_analysis.md new file mode 100644 index 000000000..c56a3c677 --- /dev/null +++ b/docs/machine-learning/principal_component_analysis.md @@ -0,0 +1,132 @@ + +--- +id: principal-component-analysis +title: "Principal Component Analysis (PCA)" +sidebar_label: PCA +description: "In this post, we’ll explore Principal Component Analysis (PCA), a fundamental technique in unsupervised learning used for dimensionality reduction and data visualization." +tags: [machine learning, algorithms, unsupervised learning, PCA] +--- + +### Definition: +**Principal Component Analysis (PCA)** is an unsupervised learning algorithm used for dimensionality reduction. It transforms data into a new coordinate system where the greatest variance by any projection lies on the first coordinate (called the first principal component), the second greatest variance on the second coordinate, and so on. + + + +### Characteristics: +- **Dimensionality Reduction**: + PCA reduces the number of features in a dataset while retaining as much variability as possible. + +- **Variance Maximization**: + The principal components are chosen such that they maximize the variance of the projected data. + +- **Linear Transformation**: + PCA is a linear transformation technique that projects data onto a lower-dimensional space. + +### Steps Involved: +1. **Standardize the Data**: + Center the data by subtracting the mean and scaling to unit variance if necessary. + +2. **Compute the Covariance Matrix**: + Calculate the covariance matrix to understand how variables relate to one another. + +3. **Calculate Eigenvalues and Eigenvectors**: + Determine the eigenvalues and eigenvectors of the covariance matrix to identify principal components. + +4. **Sort Eigenvalues and Eigenvectors**: + Sort the eigenvalues in descending order and select the top k eigenvectors corresponding to the largest eigenvalues. + +5. **Transform the Data**: + Project the original data onto the new feature space defined by the selected eigenvectors. + + + +### Problem Statement: +Given a high-dimensional dataset, PCA aims to reduce its dimensionality while preserving as much information (variance) as possible. This is particularly useful for visualization and reducing computational costs in subsequent analyses. + +### Key Concepts: +- **Eigenvalue**: + A scalar that indicates how much variance is captured by each principal component. + +- **Eigenvector**: + A direction in which a particular transformation acts; in PCA, it represents a principal component. + +- **Explained Variance Ratio**: + The proportion of variance explained by each principal component, useful for determining how many components to retain. + + + +### Split Criteria: +PCA does not involve splitting data like supervised learning; instead, it focuses on transforming all available data into a lower-dimensional space based on variance maximization. + +### Time Complexity: +- **Training Complexity**: + Computing PCA typically involves matrix operations that can have a time complexity of \( O(n^2 \cdot p) \), where \( n \) is the number of samples and \( p \) is the number of features. + +- **Prediction Complexity**: + The complexity for projecting new data points is \( O(k \cdot p) \), where \( k \) is the number of principal components retained. + +### Space Complexity: +- **Space Complexity**: + The space complexity primarily depends on storing covariance matrices and eigenvectors, which can be \( O(p^2) \). + +### Example: +Consider a scenario where we want to reduce features from a dataset containing measurements of different attributes of flowers (e.g., sepal length, sepal width, petal length, petal width). + +**Dataset Example:** + +| Sepal Length | Sepal Width | Petal Length | Petal Width | +|---------------|-------------|--------------|-------------| +| 5.1 | 3.5 | 1.4 | 0.2 | +| 4.9 | 3.0 | 1.4 | 0.2 | +| 4.7 | 3.2 | 1.3 | 0.2 | +| 4.6 | 3.1 | 1.5 | 0.2 | + +Step-by-Step Execution: + +1. **Input Data**: + The model receives training data with multiple features (sepal length, width, etc.). + +2. **Standardize Data**: + Center and scale each feature to have zero mean and unit variance. + +3. **Compute Covariance Matrix**: + Calculate how features vary together. + +4. **Calculate Eigenvalues/Eigenvectors**: + Find eigenvalues and eigenvectors from the covariance matrix. + +5. **Select Principal Components**: + Choose top k components based on explained variance. + +6. **Transform Data**: + Project original data onto selected principal components for reduced representation. + + + +### Python Implementation: +Here’s a basic implementation of PCA using **scikit-learn**: + +```python +from sklearn.decomposition import PCA +from sklearn.datasets import load_iris +import matplotlib.pyplot as plt + +# Load dataset +iris = load_iris() +X = iris.data + +# Create PCA model +pca = PCA(n_components=2) + +# Fit model and transform data +X_reduced = pca.fit_transform(X) + +# Visualize results +plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=iris.target) +plt.title('PCA of Iris Dataset') +plt.xlabel('Principal Component 1') +plt.ylabel('Principal Component 2') +plt.colorbar() +plt.show() +``` + diff --git a/src/components/Visualizing/index.tsx b/src/components/Visualizing/index.tsx index 9c0c30231..4410a9ab5 100644 --- a/src/components/Visualizing/index.tsx +++ b/src/components/Visualizing/index.tsx @@ -1,387 +1,387 @@ -import React, { useEffect } from "react"; -import Layout from "@theme/Layout"; -import "../../css/visualiezer.css"; - -const DSARoadmap: React.FC = () => { - useEffect(() => { - function swap(e: HTMLElement, r: HTMLElement) { - let t = e.style.height; - e.style.height = r.style.height; - r.style.height = t; - } - - function disableSortingBtn() { - document.querySelector(".bubbleSort")!.disabled = true; - document.querySelector(".insertionSort")!.disabled = true; - document.querySelector(".mergeSort")!.disabled = true; - document.querySelector(".quickSort")!.disabled = true; - document.querySelector(".selectionSort")!.disabled = true; - } - - function disableSizeSlider() { - document.querySelector("#arr_sz")!.disabled = true; - } - - function enableSizeSlider() { - document.querySelector("#arr_sz").disabled = !1; - } - function disableNewArrayBtn() { - document.querySelector(".newArray").disabled = !1; - } - function enableNewArrayBtn() { - document.querySelector(".newArray").disabled = !1; - } - - function enableSortingBtn() { - document.querySelector(".bubbleSort")!.disabled = false; - document.querySelector(".insertionSort")!.disabled = false; - document.querySelector(".mergeSort")!.disabled = false; - document.querySelector(".quickSort")!.disabled = false; - document.querySelector(".selectionSort")!.disabled = false; - } - - function waitforme(e: number) { - return new Promise((r) => { - setTimeout(() => { - r(""); - }, e); - }); - } - - let arraySize = document.querySelector("#arr_sz") as HTMLInputElement; - let delayElement = document.querySelector("#speed_input") as HTMLInputElement; - - let delay = 260; - - arraySize.addEventListener("input", function () { - createNewArray(parseInt(arraySize.value)); - }); - - delayElement.addEventListener("input", function () { - delay = 320 - parseInt(delayElement.value); - }); - - let array: number[] = []; - - function createNewArray(e: number = 60) { - deleteChild(); - array = []; - for (let r = 0; r < e; r++) array.push(Math.floor(250 * Math.random()) + 1); - - const barsContainer = document.querySelector("#bars") as HTMLElement; - - for (let t = 0; t < e; t++) { - const bar = document.createElement("div"); - bar.style.height = 1.5 * array[t] + "px"; - bar.classList.add("bar", "flex-item", `barNo${t}`); - barsContainer.appendChild(bar); - } - } - - function deleteChild() { - const barsContainer = document.querySelector("#bars") as HTMLElement; - barsContainer.innerHTML = ""; - } - - createNewArray(); - - const newArrayBtn = document.querySelector(".newArray")!; - - newArrayBtn.addEventListener("click", function () { - enableSortingBtn(); - createNewArray(arraySize.value); - }); - - // bubble sort -async function bubble() { - const ele = document.querySelectorAll(".bar"); - for (let i = 0; i < ele.length - 1; i++) { - for (let j = 0; j < ele.length - i - 1; j++) { - console.log("In jth loop"); - ele[j].style.background = "blue"; - ele[j + 1].style.background = "blue"; - if (parseInt(ele[j].style.height) > parseInt(ele[j + 1].style.height)) { - await waitforme(delay); - swap(ele[j], ele[j + 1]); - } - ele[j].style.background = "cyan"; - ele[j + 1].style.background = "cyan"; - } - ele[ele.length - 1 - i].style.background = "green"; - } - ele[0].style.background = "green"; - } - const bubSortbtn = document.querySelector(".bubbleSort"); - bubSortbtn.addEventListener("click", async function () { - disableSortingBtn(); - disableSizeSlider(); - disableNewArrayBtn(); - await bubble(); - enableSortingBtn(); - enableSizeSlider(); - enableNewArrayBtn(); - }); - - -// insertion sort -async function insertion() { - const ele = document.querySelectorAll(".bar"); - ele[0].style.background = "green"; - for (let i = 1; i < ele.length; i++) { - let j = i - 1; - let key = ele[i].style.height; - ele[i].style.background = "blue"; - await waitforme(delay); - while (j >= 0 && parseInt(ele[j].style.height) > parseInt(key)) { - ele[j].style.background = "blue"; - ele[j + 1].style.height = ele[j].style.height; - j--; - await waitforme(delay); - for (let k = i; k >= 0; k--) { - ele[k].style.background = "green"; - } - } - ele[j + 1].style.height = key; - ele[i].style.background = "green"; - } - } - const inSortbtn = document.querySelector(".insertionSort"); - inSortbtn.addEventListener("click", async function () { - disableSortingBtn(); - disableSizeSlider(); - disableNewArrayBtn(); - await insertion(); - enableSortingBtn(); - enableSizeSlider(); - enableNewArrayBtn(); - }); - // Merge Sort - async function merge(arr: NodeListOf, left: number, mid: number, right: number) { - const n1 = mid - left + 1; // Length of left subarray - const n2 = right - mid; // Length of right subarray - - let leftArr: string[] = []; - let rightArr: string[] = []; - - for (let i = 0; i < n1; i++) { - await waitforme(delay); - (arr[left + i] as HTMLElement).style.backgroundColor = "orange"; - leftArr[i] = (arr[left + i] as HTMLElement).style.height; - } - - for (let j = 0; j < n2; j++) { - await waitforme(delay); - (arr[mid + 1 + j] as HTMLElement).style.backgroundColor = "yellow"; - rightArr[j] = (arr[mid + 1 + j] as HTMLElement).style.height; - } - - await waitforme(delay); - - let i = 0, j = 0, k = left; - - while (i < n1 && j < n2) { - await waitforme(delay); - - if (parseInt(leftArr[i]) <= parseInt(rightArr[j])) { - (arr[k] as HTMLElement).style.height = leftArr[i]; - (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; - i++; - } else { - (arr[k] as HTMLElement).style.height = rightArr[j]; - (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; - j++; - } - k++; - } - - while (i < n1) { - await waitforme(delay); - (arr[k] as HTMLElement).style.height = leftArr[i]; - (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; - i++; - k++; - } - - while (j < n2) { - await waitforme(delay); - (arr[k] as HTMLElement).style.height = rightArr[j]; - (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; - j++; - k++; - } - } - - async function mergeSort(arr: NodeListOf, left: number, right: number) { - if (left >= right) return; - - const mid = Math.floor((left + right) / 2); - - await mergeSort(arr, left, mid); - await mergeSort(arr, mid + 1, right); - - await merge(arr, left, mid, right); - } - - const mergeSortBtn = document.querySelector(".mergeSort"); - - mergeSortBtn.addEventListener("click", async function () { - let barsElements = document.querySelectorAll(".bar"); - - disableSortingBtn(); - - await mergeSort(barsElements, 0, barsElements.length - 1); - - enableSortingBtn(); - }); - - - // quick sort -async function partitionLomuto(e, t, a) { - let n = t - 1; - e[a].style.background = "red"; - for (let r = t; r <= a - 1; r++) - (e[r].style.background = "yellow"), - await waitforme(delay), - parseInt(e[r].style.height) < parseInt(e[a].style.height) - ? (console.log("In partitionLomuto for j if"), - n++, - swap(e[n], e[r]), - (e[n].style.background = "orange"), - n != r && (e[r].style.background = "orange"), - await waitforme(delay)) - : (e[r].style.background = "pink"); - n++, - await waitforme(delay), - swap(e[n], e[a]), - (e[a].style.background = "pink"), - (e[n].style.background = "green"), - await waitforme(delay); - for (let t = 0; t < e.length; t++) - "green" != e[t].style.background && (e[t].style.background = "cyan"); - return n; - } - async function quickSort(e, t, a) { - if (t < a) { - let n = await partitionLomuto(e, t, a); - await quickSort(e, t, n - 1), await quickSort(e, n + 1, a); - } else - t >= 0 && - a >= 0 && - t < e.length && - a < e.length && - ((e[a].style.background = "green"), (e[t].style.background = "green")); - } - const quickSortbtn = document.querySelector(".quickSort"); - quickSortbtn.addEventListener("click", async function () { - let e = document.querySelectorAll(".bar"), - t = e.length - 1; - disableSortingBtn(), - disableSizeSlider(), - disableNewArrayBtn(), - await quickSort(e, 0, t), - enableSortingBtn(), - enableSizeSlider(), - enableNewArrayBtn(); - }); - -// selection sort -async function selection() { - const e = document.querySelectorAll(".bar"); - for (let t = 0; t < e.length; t++) { - let n = t; - e[t].style.background = "blue"; - for (let a = t + 1; a < e.length; a++) - (e[a].style.background = "red"), - await waitforme(delay), - parseInt(e[a].style.height) < parseInt(e[n].style.height) - ? (n !== t && (e[n].style.background = "cyan"), (n = a)) - : (e[a].style.background = "cyan"); - await waitforme(delay), - swap(e[n], e[t]), - (e[n].style.background = "cyan"), - (e[t].style.background = "green"); - } - } - const selectionSortbtn = document.querySelector(".selectionSort"); - selectionSortbtn.addEventListener("click", async function () { - disableSortingBtn(), - disableSizeSlider(), - disableNewArrayBtn(), - await selection(), - enableSortingBtn(), - enableSizeSlider(), - enableNewArrayBtn(); - }); - - - }, []); - - return ( - -
-
-

Sorting Visualizer

- -
-
-
-
- ); -}; - +import React, { useEffect } from "react"; +import Layout from "@theme/Layout"; +import "../../css/visualiezer.css"; + +const DSARoadmap: React.FC = () => { + useEffect(() => { + function swap(e: HTMLElement, r: HTMLElement) { + let t = e.style.height; + e.style.height = r.style.height; + r.style.height = t; + } + + function disableSortingBtn() { + document.querySelector(".bubbleSort")!.disabled = true; + document.querySelector(".insertionSort")!.disabled = true; + document.querySelector(".mergeSort")!.disabled = true; + document.querySelector(".quickSort")!.disabled = true; + document.querySelector(".selectionSort")!.disabled = true; + } + + function disableSizeSlider() { + document.querySelector("#arr_sz")!.disabled = true; + } + + function enableSizeSlider() { + document.querySelector("#arr_sz").disabled = !1; + } + function disableNewArrayBtn() { + document.querySelector(".newArray").disabled = !1; + } + function enableNewArrayBtn() { + document.querySelector(".newArray").disabled = !1; + } + + function enableSortingBtn() { + document.querySelector(".bubbleSort")!.disabled = false; + document.querySelector(".insertionSort")!.disabled = false; + document.querySelector(".mergeSort")!.disabled = false; + document.querySelector(".quickSort")!.disabled = false; + document.querySelector(".selectionSort")!.disabled = false; + } + + function waitforme(e: number) { + return new Promise((r) => { + setTimeout(() => { + r(""); + }, e); + }); + } + + let arraySize = document.querySelector("#arr_sz") as HTMLInputElement; + let delayElement = document.querySelector("#speed_input") as HTMLInputElement; + + let delay = 260; + + arraySize.addEventListener("input", function () { + createNewArray(parseInt(arraySize.value)); + }); + + delayElement.addEventListener("input", function () { + delay = 320 - parseInt(delayElement.value); + }); + + let array: number[] = []; + + function createNewArray(e: number = 60) { + deleteChild(); + array = []; + for (let r = 0; r < e; r++) array.push(Math.floor(250 * Math.random()) + 1); + + const barsContainer = document.querySelector("#bars") as HTMLElement; + + for (let t = 0; t < e; t++) { + const bar = document.createElement("div"); + bar.style.height = 1.5 * array[t] + "px"; + bar.classList.add("bar", "flex-item", `barNo${t}`); + barsContainer.appendChild(bar); + } + } + + function deleteChild() { + const barsContainer = document.querySelector("#bars") as HTMLElement; + barsContainer.innerHTML = ""; + } + + createNewArray(); + + const newArrayBtn = document.querySelector(".newArray")!; + + newArrayBtn.addEventListener("click", function () { + enableSortingBtn(); + createNewArray(arraySize.value); + }); + + // bubble sort +async function bubble() { + const ele = document.querySelectorAll(".bar"); + for (let i = 0; i < ele.length - 1; i++) { + for (let j = 0; j < ele.length - i - 1; j++) { + console.log("In jth loop"); + ele[j].style.background = "blue"; + ele[j + 1].style.background = "blue"; + if (parseInt(ele[j].style.height) > parseInt(ele[j + 1].style.height)) { + await waitforme(delay); + swap(ele[j], ele[j + 1]); + } + ele[j].style.background = "cyan"; + ele[j + 1].style.background = "cyan"; + } + ele[ele.length - 1 - i].style.background = "green"; + } + ele[0].style.background = "green"; + } + const bubSortbtn = document.querySelector(".bubbleSort"); + bubSortbtn.addEventListener("click", async function () { + disableSortingBtn(); + disableSizeSlider(); + disableNewArrayBtn(); + await bubble(); + enableSortingBtn(); + enableSizeSlider(); + enableNewArrayBtn(); + }); + + +// insertion sort +async function insertion() { + const ele = document.querySelectorAll(".bar"); + ele[0].style.background = "green"; + for (let i = 1; i < ele.length; i++) { + let j = i - 1; + let key = ele[i].style.height; + ele[i].style.background = "blue"; + await waitforme(delay); + while (j >= 0 && parseInt(ele[j].style.height) > parseInt(key)) { + ele[j].style.background = "blue"; + ele[j + 1].style.height = ele[j].style.height; + j--; + await waitforme(delay); + for (let k = i; k >= 0; k--) { + ele[k].style.background = "green"; + } + } + ele[j + 1].style.height = key; + ele[i].style.background = "green"; + } + } + const inSortbtn = document.querySelector(".insertionSort"); + inSortbtn.addEventListener("click", async function () { + disableSortingBtn(); + disableSizeSlider(); + disableNewArrayBtn(); + await insertion(); + enableSortingBtn(); + enableSizeSlider(); + enableNewArrayBtn(); + }); + // Merge Sort + async function merge(arr: NodeListOf, left: number, mid: number, right: number) { + const n1 = mid - left + 1; // Length of left subarray + const n2 = right - mid; // Length of right subarray + + let leftArr: string[] = []; + let rightArr: string[] = []; + + for (let i = 0; i < n1; i++) { + await waitforme(delay); + (arr[left + i] as HTMLElement).style.backgroundColor = "orange"; + leftArr[i] = (arr[left + i] as HTMLElement).style.height; + } + + for (let j = 0; j < n2; j++) { + await waitforme(delay); + (arr[mid + 1 + j] as HTMLElement).style.backgroundColor = "yellow"; + rightArr[j] = (arr[mid + 1 + j] as HTMLElement).style.height; + } + + await waitforme(delay); + + let i = 0, j = 0, k = left; + + while (i < n1 && j < n2) { + await waitforme(delay); + + if (parseInt(leftArr[i]) <= parseInt(rightArr[j])) { + (arr[k] as HTMLElement).style.height = leftArr[i]; + (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; + i++; + } else { + (arr[k] as HTMLElement).style.height = rightArr[j]; + (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; + j++; + } + k++; + } + + while (i < n1) { + await waitforme(delay); + (arr[k] as HTMLElement).style.height = leftArr[i]; + (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; + i++; + k++; + } + + while (j < n2) { + await waitforme(delay); + (arr[k] as HTMLElement).style.height = rightArr[j]; + (arr[k] as HTMLElement).style.backgroundColor = "lightgreen"; + j++; + k++; + } + } + + async function mergeSort(arr: NodeListOf, left: number, right: number) { + if (left >= right) return; + + const mid = Math.floor((left + right) / 2); + + await mergeSort(arr, left, mid); + await mergeSort(arr, mid + 1, right); + + await merge(arr, left, mid, right); + } + + const mergeSortBtn = document.querySelector(".mergeSort"); + + mergeSortBtn.addEventListener("click", async function () { + let barsElements = document.querySelectorAll(".bar"); + + disableSortingBtn(); + + await mergeSort(barsElements, 0, barsElements.length - 1); + + enableSortingBtn(); + }); + + + // quick sort +async function partitionLomuto(e, t, a) { + let n = t - 1; + e[a].style.background = "red"; + for (let r = t; r <= a - 1; r++) + (e[r].style.background = "yellow"), + await waitforme(delay), + parseInt(e[r].style.height) < parseInt(e[a].style.height) + ? (console.log("In partitionLomuto for j if"), + n++, + swap(e[n], e[r]), + (e[n].style.background = "orange"), + n != r && (e[r].style.background = "orange"), + await waitforme(delay)) + : (e[r].style.background = "pink"); + n++, + await waitforme(delay), + swap(e[n], e[a]), + (e[a].style.background = "pink"), + (e[n].style.background = "green"), + await waitforme(delay); + for (let t = 0; t < e.length; t++) + "green" != e[t].style.background && (e[t].style.background = "cyan"); + return n; + } + async function quickSort(e, t, a) { + if (t < a) { + let n = await partitionLomuto(e, t, a); + await quickSort(e, t, n - 1), await quickSort(e, n + 1, a); + } else + t >= 0 && + a >= 0 && + t < e.length && + a < e.length && + ((e[a].style.background = "green"), (e[t].style.background = "green")); + } + const quickSortbtn = document.querySelector(".quickSort"); + quickSortbtn.addEventListener("click", async function () { + let e = document.querySelectorAll(".bar"), + t = e.length - 1; + disableSortingBtn(), + disableSizeSlider(), + disableNewArrayBtn(), + await quickSort(e, 0, t), + enableSortingBtn(), + enableSizeSlider(), + enableNewArrayBtn(); + }); + +// selection sort +async function selection() { + const e = document.querySelectorAll(".bar"); + for (let t = 0; t < e.length; t++) { + let n = t; + e[t].style.background = "blue"; + for (let a = t + 1; a < e.length; a++) + (e[a].style.background = "red"), + await waitforme(delay), + parseInt(e[a].style.height) < parseInt(e[n].style.height) + ? (n !== t && (e[n].style.background = "cyan"), (n = a)) + : (e[a].style.background = "cyan"); + await waitforme(delay), + swap(e[n], e[t]), + (e[n].style.background = "cyan"), + (e[t].style.background = "green"); + } + } + const selectionSortbtn = document.querySelector(".selectionSort"); + selectionSortbtn.addEventListener("click", async function () { + disableSortingBtn(), + disableSizeSlider(), + disableNewArrayBtn(), + await selection(), + enableSortingBtn(), + enableSizeSlider(), + enableNewArrayBtn(); + }); + + + }, []); + + return ( + +
+
+

Sorting Visualizer

+ +
+
+
+
+ ); +}; + export default DSARoadmap; \ No newline at end of file diff --git a/src/css/visualiezer.css b/src/css/visualiezer.css index 6aafaa9b1..7e70fa566 100644 --- a/src/css/visualiezer.css +++ b/src/css/visualiezer.css @@ -1,93 +1,93 @@ -body { - font-family: Arial, Helvetica, sans-serif; - font-size: 20px; - padding: 0 20px 30px 0; - line-height: 1.4; -} - -.flex-container { - display: flex; - flex-wrap: nowrap; - width: 100%; - height: 400px; - justify-content: center; - align-items: flex-end; /* Aligns bars from the bottom */ - transition: 2s all ease; -} - -.flex-item { - background: cyan; - border: 1pt solid #000; - width: 10px; - transition: 0.1s all ease; -} - -#input { - display: flex; - padding: 10px; - justify-content: space-around; -} - -.h1, -h1 { - margin-bottom: 20px; -} - -/* Button Styles */ -.btn { - background-color: #007bff; /* Bootstrap primary color */ - color: white; /* Text color */ - border: none; /* Remove border */ - padding: 10px 15px; /* Padding */ - font-size: 16px; /* Font size */ - border-radius: 5px; /* Rounded corners */ - cursor: pointer; /* Pointer cursor on hover */ - transition: background-color 0.3s ease; /* Transition for hover effect */ -} - -.btn:hover { - background-color: #0056b3; /* Darker shade on hover */ -} - -.btn:disabled { - background-color: #ccc; /* Light gray for disabled buttons */ - cursor: not-allowed; /* Not allowed cursor for disabled buttons */ -} - -@media screen and (max-width: 600px) { - .col #input { - display: flex; - justify-content: center; - align-items: center; - } - - .col span { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - padding: 10px; - } - - .row { - display: inline; - text-align: center; - } - - .flex-container { - margin-top: 0; - } - - #input { - display: inline; - text-align: center; - } - - .justify-content-end { - margin-top: 0; - } - - .btn { - margin-bottom: 10px; - } +body { + font-family: Arial, Helvetica, sans-serif; + font-size: 20px; + padding: 0 20px 30px 0; + line-height: 1.4; +} + +.flex-container { + display: flex; + flex-wrap: nowrap; + width: 100%; + height: 400px; + justify-content: center; + align-items: flex-end; /* Aligns bars from the bottom */ + transition: 2s all ease; +} + +.flex-item { + background: cyan; + border: 1pt solid #000; + width: 10px; + transition: 0.1s all ease; +} + +#input { + display: flex; + padding: 10px; + justify-content: space-around; +} + +.h1, +h1 { + margin-bottom: 20px; +} + +/* Button Styles */ +.btn { + background-color: #007bff; /* Bootstrap primary color */ + color: white; /* Text color */ + border: none; /* Remove border */ + padding: 10px 15px; /* Padding */ + font-size: 16px; /* Font size */ + border-radius: 5px; /* Rounded corners */ + cursor: pointer; /* Pointer cursor on hover */ + transition: background-color 0.3s ease; /* Transition for hover effect */ +} + +.btn:hover { + background-color: #0056b3; /* Darker shade on hover */ +} + +.btn:disabled { + background-color: #ccc; /* Light gray for disabled buttons */ + cursor: not-allowed; /* Not allowed cursor for disabled buttons */ +} + +@media screen and (max-width: 600px) { + .col #input { + display: flex; + justify-content: center; + align-items: center; + } + + .col span { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + padding: 10px; + } + + .row { + display: inline; + text-align: center; + } + + .flex-container { + margin-top: 0; + } + + #input { + display: inline; + text-align: center; + } + + .justify-content-end { + margin-top: 0; + } + + .btn { + margin-bottom: 10px; + } } \ No newline at end of file diff --git a/src/data/problemData.ts b/src/data/problemData.ts index cbbe746ca..6c8214683 100644 --- a/src/data/problemData.ts +++ b/src/data/problemData.ts @@ -1,3600 +1,3600 @@ -const problemsData = { - twoSum: { - title: "1. Two Sum", - description: - "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.", - examples: [ - { input: "[2,7,11,15], target = 9", output: "[0,1]" }, - { input: "[3,2,4], target = 6", output: "[1,2]" }, - { input: "[3,3], target = 6", output: "[0,1]" }, - ], - solution: { - cpp: ` - class Solution { - public: - vector twoSum(vector& nums, int target) { - unordered_map res; - vector result; - - for(int i = 0; i < nums.size(); i++) { - if(res.find(target - nums[i]) != res.end()) { - result.push_back(i); - result.push_back(res[target - nums[i]]); - break; - } else { - res[nums[i]] = i; - } - } - return result; - } - };`, - java: ` - import java.util.HashMap; - - public class Solution { - public int[] twoSum(int[] nums, int target) { - HashMap map = new HashMap<>(); - - for (int i = 0; i < nums.length; i++) { - int complement = target - nums[i]; - - if (map.containsKey(complement)) { - return new int[] { map.get(complement), i }; - } - - map.put(nums[i], i); - } - return new int[] {}; - } - }`, - python: ` - class Solution: - def twoSum(self, nums: List[int], target: int) -> List[int]: - res = {} - - for i, num in enumerate(nums): - complement = target - num - - if complement in res: - return [res[complement], i] - - res[num] = i`, - }, - }, - containerWithMostWater: { - title: "2. Container With Most Water", - description: - "Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). Find two lines that form a container with the maximum area of water.", - examples: [ - { input: "[1,8,6,2,5,4,8,3,7]", output: "49" }, - { input: "[1,1]", output: "1" }, - { input: "[4,3,2,1,4]", output: "16" }, - { input: "[1,2,1]", output: "2" }, - ], - solution: { - cpp: ` - class Solution { - public: - int maxArea(vector& height) { - int current_area = INT_MIN; - int area = 0; - int left = 0, right = height.size() - 1; - while (left < right) { - current_area = min(height[left], height[right]) * (right - left); - if (height[left] < height[right]) left++; - else right--; - area = max(area, current_area); - } - return area; - } - };`, - java: ` - public class Solution { - public int maxArea(int[] height) { - int left = 0, right = height.length - 1; - int maxArea = 0; - - while (left < right) { - int currentArea = Math.min(height[left], height[right]) * (right - left); - maxArea = Math.max(maxArea, currentArea); - - if (height[left] < height[right]) { - left++; - } else { - right--; - } - } - - return maxArea; - } - }`, - python: ` -class Solution: - def maxArea(self, height: List[int]) -> int: - left, right = 0, len(height) - 1 - max_area = 0 - - while left < right: - current_area = min(height[left], height[right]) * (right - left) - max_area = max(max_area, current_area) - - if height[left] < height[right]: - left += 1 - else: - right -= 1 - - return max_area`, - }, - }, - threeSum: { - title: "3. 3Sum", - description: - "Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.", - examples: [ - { input: "[-1,0,1,2,-1,-4]", output: "[[-1,-1,2],[-1,0,1]]" }, - { input: "[]", output: "[]" }, - { input: "[0]", output: "[]" }, - ], - solution: { - cpp: ` - vector> threeSum(vector& nums) { - vector> res; - if(nums.size() < 3) return res; - sort(nums.begin(), nums.end()); - int n = nums.size(); - for(int i = 0; i < n - 2; i++) { - if(i > 0 && nums[i] == nums[i - 1]) continue; - int j = i + 1, k = n - 1; - while(j < k) { - int s = nums[i] + nums[j] + nums[k]; - if(s < 0) j++; - else if(s > 0) k--; - else { - res.push_back({nums[i], nums[j], nums[k]}); - while(j < k && nums[j] == nums[j + 1]) j++; - while(j < k && nums[k] == nums[k - 1]) k--; - j++, k--; - } - } - } - return res; - } -};`, - java: ` -import java.util.*; -public class Solution { - public List> threeSum(int[] nums) { - List> res = new ArrayList<>(); - if(nums.length < 3) return res; - Arrays.sort(nums); - for(int i = 0; i < nums.length - 2; i++) { - if(i > 0 && nums[i] == nums[i - 1]) continue; - int j = i + 1, k = nums.length - 1; - while(j < k) { - int sum = nums[i] + nums[j] + nums[k]; - if(sum < 0) j++; - else if(sum > 0) k--; - else { - res.add(Arrays.asList(nums[i], nums[j], nums[k])); - while(j < k && nums[j] == nums[j + 1]) j++; - while(j < k && nums[k] == nums[k - 1]) k--; - j++; k--; - } - } - } - return res; - } -};`, - python: ` -class Solution: - def threeSum(self, nums: List[int]) -> List[List[int]]: - res = [] - nums.sort() - for i in range(len(nums) - 2): - if i > 0 and nums[i] == nums[i - 1]: - continue - j, k = i + 1, len(nums) - 1 - while j < k: - s = nums[i] + nums[j] + nums[k] - if s < 0: - j += 1 - elif s > 0: - k -= 1 - else: - res.append([nums[i], nums[j], nums[k]]) - while j < k and nums[j] == nums[j + 1]: - j += 1 - while j < k and nums[k] == nums[k - 1]: - k -= 1 - j += 1 - k -= 1 - return res`, - }, - }, - - isValidParentheses: { - title: "4. Valid Parentheses", - description: - "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.", - examples: [ - { input: "(){}", output: "true" }, - { input: "()[]{}", output: "true" }, - { input: "(]", output: "false" }, - { input: "([)]", output: "false" }, - { input: "{[]}", output: "true" }, - ], - solution: { - cpp: ` -class Solution { -public: - bool isValid(string s) { - stack stk; - for(char c : s) { - if(c == '{') stk.push('}'); - else if(c == '[') stk.push(']'); - else if(c == '(') stk.push(')'); - else if(stk.empty() || stk.top() != c) return false; - else stk.pop(); - } - return stk.empty(); - } -};`, - java: ` -import java.util.Stack; - -public class Solution { - public boolean isValid(String s) { - Stack stack = new Stack<>(); - for (char c : s.toCharArray()) { - if (c == '(') stack.push(')'); - else if (c == '{') stack.push('}'); - else if (c == '[') stack.push(']'); - else if (stack.isEmpty() || stack.pop() != c) return false; - } - return stack.isEmpty(); - } -};`, - python: ` -class Solution: - def isValid(self, s: str) -> bool: - stack = [] - mapping = {')': '(', '}': '{', ']': '['} - for char in s: - if char in mapping: - top_element = stack.pop() if stack else '#' - if mapping[char] != top_element: - return False - else: - stack.append(char) - return not stack`, - }, - }, - - mergeTwoLists: { - title: "5. Merge Two Sorted Lists", - description: - "Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.", - examples: [ - { input: "[1,2,4], [1,3,4]", output: "[1,1,2,3,4,4]" }, - { input: "[], []", output: "[]" }, - { input: "[], [0]", output: "[0]" }, - ], - solution: { - cpp: ` -class Solution { -public: - ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { - if (!l1) return l2; - if (!l2) return l1; - if (l1->val < l2->val) { - l1->next = mergeTwoLists(l1->next, l2); - return l1; - } else { - l2->next = mergeTwoLists(l1, l2->next); - return l2; - } - } -};`, - java: ` -public class Solution { - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - if (l1 == null) return l2; - if (l2 == null) return l1; - if (l1.val < l2.val) { - l1.next = mergeTwoLists(l1.next, l2); - return l1; - } else { - l2.next = mergeTwoLists(l1, l2.next); - return l2; - } - } -};`, - python: ` -class Solution: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: - if not l1: - return l2 - if not l2: - return l1 - if l1.val < l2.val: - l1.next = self.mergeTwoLists(l1.next, l2) - return l1 - else: - l2.next = self.mergeTwoLists(l1, l2.next) - return l2`, - }, - }, - - nextPermutation: { - title: "6. Next Permutation", - description: - "Implement next permutation which rearranges numbers into the lexicographically next greater permutation of numbers.", - examples: [ - { input: "[1,2,3]", output: "[1,3,2]" }, - { input: "[3,2,1]", output: "[1,2,3]" }, - { input: "[1,5]", output: "[5,1]" }, - { input: "[5]", output: "[5]" }, - ], - solution: { - cpp: ` -class Solution { -public: - void nextPermutation(vector& nums) { - next_permutation(nums.begin(), nums.end()); - } -};`, - java: ` -import java.util.Arrays; -public class Solution { - public void nextPermutation(int[] nums) { - int i = nums.length - 2; - while (i >= 0 && nums[i] >= nums[i + 1]) i--; - if (i >= 0) { - int j = nums.length - 1; - while (nums[j] <= nums[i]) j--; - swap(nums, i, j); - } - reverse(nums, i + 1); - } - - private void swap(int[] nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } - - private void reverse(int[] nums, int start) { - int i = start, j = nums.length - 1; - while (i < j) { - swap(nums, i++, j--); - } - } -};`, - python: ` -class Solution: - def nextPermutation(self, nums: List[int]) -> None: - i = len(nums) - 2 - while i >= 0 and nums[i] >= nums[i + 1]: - i -= 1 - if i >= 0: - j = len(nums) - 1 - while nums[j] <= nums[i]: - j -= 1 - nums[i], nums[j] = nums[j], nums[i] - nums[i + 1:] = nums[i + 1:][::-1]`, - }, - }, - searchInsert: { - title: "7. Search Insert Position", - description: - "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.", - examples: [ - { input: "[1,3,5,6], target=5", output: "2" }, - { input: "[1,3], target=0", output: "0" }, - { input: "[3], target=4", output: "1" }, - ], - solution: { - cpp: ` -class Solution { -public: - int searchInsert(vector& nums, int target) { - int low = 0, high = nums.size() - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (nums[mid] == target) return mid; - else if (nums[mid] > target) high = mid - 1; - else low = mid + 1; - } - return low; - } -};`, - java: ` -class Solution { - public int searchInsert(int[] nums, int target) { - int low = 0, high = nums.length - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (nums[mid] == target) return mid; - else if (nums[mid] > target) high = mid - 1; - else low = mid + 1; - } - return low; - } -};`, - python: ` -class Solution: - def searchInsert(self, nums: List[int], target: int) -> int: - low, high = 0, len(nums) - 1 - while low <= high: - mid = (low + high) // 2 - if nums[mid] == target: - return mid - elif nums[mid] > target: - high = mid - 1 - else: - low = mid + 1 - return low`, - }, - }, - - isValidSudoku: { - title: "8. Valid Sudoku", - description: - "Determine if a 9 x 9 Sudoku board is valid by checking that each row, column, and 3 x 3 sub-box contains the digits 1-9 without repetition. The board may be partially filled, with empty cells represented by the character '.'. A board is considered valid if it adheres to these rules.", - examples: [ - { - input: `[['5','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','.'],['.','9','8','.','.','.','.','6','.'],['8','.','.','.','6','.','.','.','3'],['4','.','.','8','.','3','.','.','1'],['7','.','.','.','2','.','.','.','6'],['.','6','.','.','.','.','2','8','.'],['.','.' ,'.' ,'4' ,'1' ,'9' ,'.' ,'.' ,'5'],['.' ,'.' ,'.' ,'.' ,'8' ,'.' ,'.' ,'7' ,'9']]`, - output: "true", - }, - { - input: `[['8','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','.'],['.','9','8','.','.','.','.','6', '.'],['8', '.', '.', '.', '6', '.', '.', '.', '3'],['4', '.', '.', '8', '.', '3', '.', '.', '1'],['7', '.', '.', '.', '2', '.', '.', '.', '6'],['.', '6', '.', '.', '.', '.', '2', '8', '.'],['.', '.', '.', '4', '1', '9', '.', '.', '5'],['.', '.', '.', '.', '8', '.', '.', '7', '9']]`, - output: "false", - }, - ], - solution: { - cpp: ` - class Solution { - public: - bool isValidSudoku(vector>& board) { - vector> rows(9), cols(9), blocks(9); - for(int i=0; i<9; i++) { - for(int j=0; j<9; j++) { - if(board[i][j]=='.') continue; - int curr = board[i][j]-'0'; - if(rows[i].count(curr) || cols[j].count(curr) || blocks[(i/3)*3+j/3].count(curr)) return false; - rows[i].insert(curr); - cols[j].insert(curr); - blocks[(i/3)*3+j/3].insert(curr); - } - } - return true; - } - };`, - java: ` - class Solution { - public boolean isValidSudoku(char[][] board) { - HashSet seen = new HashSet<>(); - for (int r = 0; r < 9; r++) { - for (int c = 0; c < 9; c++) { - if (board[r][c] != '.') { - String num = String.valueOf(board[r][c]); - if (!seen.add(num + " in row " + r) || !seen.add(num + " in column " + c) || - !seen.add(num + " in block " + r / 3 + "-" + c / 3)) return false; - } - } - } - return true; - } - };`, - python: ` - class Solution: - def isValidSudoku(self, board: List[List[str]]) -> bool: - rows, cols, blocks = [set() for _ in range(9)], [set() for _ in range(9)], [set() for _ in range(9)] - for i in range(9): - for j in range(9): - if board[i][j] == '.': continue - curr = board[i][j] - if (curr in rows[i] or curr in cols[j] or curr in blocks[(i//3)*3+j//3]): - return False - rows[i].add(curr) - cols[j].add(curr) - blocks[(i//3)*3+j//3].add(curr) - return True`, - }, - }, - - firstMissingPositive: { - title: "9. First Missing Positive", - description: - "Given an unsorted integer array nums, return the smallest missing positive integer.", - examples: [ - { input: "[1,2,0]", output: "3" }, - { input: "[3,4,-1,1]", output: "2" }, - { input: "[7,8,9,11,12]", output: "1" }, - ], - solution: { - cpp: ` - class Solution { - public: - int firstMissingPositive(vector& nums) { - int n = nums.size(); - vector present(n + 1, false); - for (int num : nums) { - if (num > 0 && num <= n) present[num] = true; - } - for (int i = 1; i <= n; i++) { - if (!present[i]) return i; - } - return n + 1; - } - };`, - java: ` - class Solution { - public int firstMissingPositive(int[] nums) { - int n = nums.length; - boolean[] present = new boolean[n + 1]; - for (int num : nums) { - if (num > 0 && num <= n) present[num] = true; - } - for (int i = 1; i <= n; i++) { - if (!present[i]) return i; - } - return n + 1; - } - };`, - python: ` - class Solution: - def firstMissingPositive(self, nums: List[int]) -> int: - n = len(nums) - present = [False] * (n + 1) - for num in nums: - if 1 <= num <= n: - present[num] = True - for i in range(1, n + 1): - if not present[i]: return i - return n + 1`, - }, - }, - - maxSubArray: { - title: "10. Maximum Subarray", - description: - "Given an integer array nums, find the contiguous subarray which has the largest sum and return its sum.", - examples: [ - { input: "[-2,1,-3,4,-1,2,1,-5,4]", output: "6" }, - { input: "[1]", output: "1" }, - { input: "[5,4,-1,7,8]", output: "23" }, - ], - solution: { - cpp: ` - class Solution { - public: - int maxSubArray(vector& nums) { - int sum = nums[0], max_sum = nums[0]; - for (int i = 1; i < nums.size(); i++) { - sum = max(nums[i], sum + nums[i]); - max_sum = max(sum, max_sum); - } - return max_sum; - } - };`, - java: ` - class Solution { - public int maxSubArray(int[] nums) { - int maxSum = nums[0], currSum = nums[0]; - for (int i = 1; i < nums.length; i++) { - currSum = Math.max(nums[i], currSum + nums[i]); - maxSum = Math.max(maxSum, currSum); - } - return maxSum; - } - };`, - python: ` - class Solution: - def maxSubArray(self, nums: List[int]) -> int: - max_sum = nums[0] - curr_sum = nums[0] - for num in nums[1:]: - curr_sum = max(num, curr_sum + num) - max_sum = max(max_sum, curr_sum) - return max_sum`, - }, - }, - mySqrt: { - title: "11. Sqrt(x)", - description: - "Given a non-negative integer x, compute and return the square root of x.", - examples: [ - { input: "4", output: "2" }, - { input: "8", output: "2" }, - { input: "16", output: "4" }, - ], - solution: { - cpp: ` -class Solution { -public: - int mySqrt(int x) { - if (x < 2) return x; - long long int res; - long long int start = 1, end = x / 2; - while (start <= end) { - long long int mid = start + (end - start) / 2; - if (mid * mid == x) return mid; - else if (mid * mid < x) { - start = mid + 1; res = mid; - } else end = mid - 1; - } - return res; - } -};`, - java: ` -class Solution { - public int mySqrt(int x) { - if (x < 2) return x; - long res = 0; - long start = 1, end = x / 2; - while (start <= end) { - long mid = start + (end - start) / 2; - if (mid * mid == x) return (int) mid; - else if (mid * mid < x) { - start = mid + 1; res = mid; - } else end = mid - 1; - } - return (int) res; - } -};`, - python: ` -class Solution: - def mySqrt(self, x: int) -> int: - if x < 2: return x - start, end, res = 1, x // 2, 0 - while start <= end: - mid = start + (end - start) // 2 - if mid * mid == x: return mid - elif mid * mid < x: - start = mid + 1; res = mid - else: end = mid - 1 - return res - `, - }, - }, - - searchMatrix: { - title: "12. Search a 2D Matrix", - description: - "Write an efficient algorithm that searches for a value in an m x n matrix.", - examples: [ - { - input: "[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3", - output: "true", - }, - { input: "[[1,3,5],[10],[23]], target = 13", output: "false" }, - ], - solution: { - cpp: ` -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - if (!matrix.size()) return false; - int n = matrix.size(), m = matrix[0].size(), low = 0, high = (n * m) - 1; - while (low <= high) { - int mid = (low + (high - low) / 2); - if (matrix[mid / m][mid % m] == target) return true; - if (matrix[mid / m][mid % m] < target) low = mid + 1; - else high = mid - 1; - } - return false; - } -};`, - java: ` -class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - if (matrix.length == 0) return false; - int n = matrix.length, m = matrix[0].length, low = 0, high = (n * m) - 1; - while (low <= high) { - int mid = (low + (high - low) / 2); - if (matrix[mid / m][mid % m] == target) return true; - if (matrix[mid / m][mid % m] < target) low = mid + 1; - else high = mid - 1; - } - return false; - } -};`, - python: ` -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - if not matrix: return False - n, m = len(matrix), len(matrix[0]) - low, high = 0, (n * m) - 1 - while low <= high: - mid = (low + (high - low) // 2) - if matrix[mid // m][mid % m] == target: return True - if matrix[mid // m][mid % m] < target: low = mid + 1 - else: high = mid - 1 - return False - `, - }, - }, - - deleteDuplicates: { - title: "13. Remove Duplicates from Sorted List", - description: - "Given the head of a sorted linked list, delete all duplicates such that each element appears only once.", - examples: [ - { input: "[1,1,2]", output: "[1,2]" }, - { input: "[1,1,2,3,3]", output: "[1,2,3]" }, - ], - solution: { - cpp: ` -class Solution { -public: - ListNode* deleteDuplicates(ListNode* head) { - if(head == NULL) return NULL; - ListNode* curr = head; - while(curr->next) { - if(curr->val == curr->next->val) - curr->next = curr->next->next; - else curr = curr->next; - } - return head; - } -};`, - java: ` -class Solution { - public ListNode deleteDuplicates(ListNode head) { - if (head == null) return null; - ListNode curr = head; - while (curr.next != null) { - if (curr.val == curr.next.val) - curr.next = curr.next.next; - else curr = curr.next; - } - return head; - } -};`, - python: ` -class Solution: - def deleteDuplicates(self, head: ListNode) -> ListNode: - if head is None: return None - curr = head - while curr.next: - if curr.val == curr.next.val: - curr.next = curr.next.next - else: curr = curr.next - return head - `, - }, - }, - - mergeTwoSortedLists: { - title: "14. Merge Two Sorted Lists", - description: - "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order.", - examples: [ - { - input: "[1,2,4,0,0,0], m = 3, nums2 = [2,5,6], n = 3", - output: "[1,2,2,3,5,6]", - }, - { input: "[1], m = 1, nums2 = [], n = 0", output: "[1]" }, - ], - solution: { - cpp: ` -class Solution { -public: - void merge(vector& nums1, int m, vector& nums2, int n) { - int i = 0; - while (i < n) { - nums1[m++] = nums2[i]; - i++; - } - sort(nums1.begin(), nums1.end()); - } -};`, - java: ` -class Solution { - public void merge(int[] nums1, int m, int[] nums2, int n) { - int i = 0; - while (i < n) { - nums1[m++] = nums2[i]; - i++; - } - Arrays.sort(nums1); - } -};`, - python: ` -class Solution: - def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: - i = 0 - while i < n: - nums1[m] = nums2[i] - m += 1 - i += 1 - nums1.sort() - `, - }, - }, - inorderTraversal: { - title: "15. Binary Tree Inorder Traversal", - description: - "Given the root of a binary tree, return the inorder traversal of its nodes' values.", - examples: [ - { input: "[1,null,2,3]", output: "[1,3,2]" }, - { input: "[]", output: "[]" }, - { input: "[1]", output: "[1]" }, - ], - solution: { - cpp: ` -class Solution { -public: - vector ans; - vector inorderTraversal(TreeNode* root) { - if (root == NULL) return ans; - inorderTraversal(root->left); - ans.push_back(root->val); - inorderTraversal(root->right); - return ans; - } -};`, - java: ` -class Solution { - public List inorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - inorderTraversalHelper(root, ans); - return ans; - } - private void inorderTraversalHelper(TreeNode root, List ans) { - if (root == null) return; - inorderTraversalHelper(root.left, ans); - ans.add(root.val); - inorderTraversalHelper(root.right, ans); - } -};`, - python: ` -class Solution: - def inorderTraversal(self, root: TreeNode) -> List[int]: - ans = [] - def inorder(node): - if not node: return - inorder(node.left) - ans.append(node.val) - inorder(node.right) - inorder(root) - return ans - `, - }, - }, - - isSymmetric: { - title: "16. Symmetric Tree", - description: - "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).", - examples: [ - { input: "[1,2,2,3,4,4,3]", output: "true" }, - { input: "[1,2,2,null,3,null,3]", output: "false" }, - ], - solution: { - cpp: ` -class Solution { -public: - bool isSymmetric(TreeNode* root) { - if (root == NULL) return true; - return isSymmetricTest(root->left, root->right); - } - bool isSymmetricTest(TreeNode* p, TreeNode* q) { - if (p == NULL && q == NULL) return true; - else if (p == NULL || q == NULL) return false; - else if (p->val != q->val) return false; - return isSymmetricTest(p->left, q->right) && isSymmetricTest(p->right, q->left); - } -};`, - java: ` -class Solution { - public boolean isSymmetric(TreeNode root) { - if (root == null) return true; - return isSymmetricTest(root.left, root.right); - } - private boolean isSymmetricTest(TreeNode p, TreeNode q) { - if (p == null && q == null) return true; - else if (p == null || q == null) return false; - else if (p.val != q.val) return false; - return isSymmetricTest(p.left, q.right) && isSymmetricTest(p.right, q.left); - } -};`, - python: ` -class Solution: - def isSymmetric(self, root: TreeNode) -> bool: - if not root: return True - return self.isSymmetricTest(root.left, root.right) - def isSymmetricTest(self, p: TreeNode, q: TreeNode) -> bool: - if not p and not q: return True - if not p or not q: return False - if p.val != q.val: return False - return self.isSymmetricTest(p.left, q.right) and self.isSymmetricTest(p.right, q.left) - `, - }, - }, - - levelOrderTraversal: { - title: "17. Binary Tree Level Order Traversal", - description: - "Given the root of a binary tree, return the level order traversal of its nodes' values.", - examples: [ - { input: "[3,9,20,null,null,15,7]", output: "[[3],[9,20],[15,7]]" }, - { input: "[1]", output: "[[1]]" }, - { input: "[]", output: "[]" }, - ], - solution: { - cpp: ` -class Solution { -public: - vector> levelOrder(TreeNode* root) { - vector> ans; - if (root == NULL) return ans; - - queue q; - q.push(root); - while (!q.empty()) { - int size = q.size(); - vector level; - for (int i = 0; i < size; i++) { - TreeNode* node = q.front(); - q.pop(); - if (node->left != NULL) q.push(node->left); - if (node->right != NULL) q.push(node->right); - level.push_back(node->val); - } - ans.push_back(level); - } - return ans; - } -};`, - java: ` -class Solution { - public List> levelOrder(TreeNode root) { - List> ans = new ArrayList<>(); - if (root == null) return ans; - - Queue q = new LinkedList<>(); - q.offer(root); - while (!q.isEmpty()) { - int size = q.size(); - List level = new ArrayList<>(); - for (int i = 0; i < size; i++) { - TreeNode node = q.poll(); - if (node.left != null) q.offer(node.left); - if (node.right != null) q.offer(node.right); - level.add(node.val); - } - ans.add(level); - } - return ans; - } -};`, - python: ` -class Solution: - def levelOrder(self, root: TreeNode) -> List[List[int]]: - ans = [] - if not root: return ans - q = collections.deque([root]) - while q: - size = len(q) - level = [] - for _ in range(size): - node = q.popleft() - if node.left: q.append(node.left) - if node.right: q.append(node.right) - level.append(node.val) - ans.append(level) - return ans - `, - }, - }, - - maxDepthBinaryTree: { - title: "18. Maximum Depth of Binary Tree", - description: "Given the root of a binary tree, return its maximum depth.", - examples: [ - { input: "[3,9,20,null,null,15,7]", output: "3" }, - { input: "[1,null,2]", output: "2" }, - { input: "[]", output: "0" }, - ], - solution: { - cpp: ` -class Solution { -public: - int maxDepth(TreeNode* root) { - if (root == NULL) return 0; - int leftDepth = maxDepth(root->left); - int rightDepth = maxDepth(root->right); - return max(leftDepth, rightDepth) + 1; - } -};`, - java: ` -class Solution { - public int maxDepth(TreeNode root) { - if (root == null) return 0; - int leftDepth = maxDepth(root.left); - int rightDepth = maxDepth(root.right); - return Math.max(leftDepth, rightDepth) + 1; - } -};`, - python: ` -class Solution: - def maxDepth(self, root: TreeNode) -> int: - if not root: return 0 - leftDepth = self.maxDepth(root.left) - rightDepth = self.maxDepth(root.right) - return max(leftDepth, rightDepth) + 1 - `, - }, - }, - hasPathSum: { - title: "19. Path Sum", - description: - "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.", - examples: [ - { input: "[5,4,8,11,null,13,4], targetSum = 22", output: "true" }, - { input: "[1], targetSum = 5", output: "false" }, - ], - solution: { - cpp: ` -class Solution { -public: - bool hasPathSum(TreeNode* root, int sum) { - if (root == NULL) - return false; - - if (root->left == NULL && root->right == NULL) - return sum == root->val; - - return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); - } -};`, - java: ` -class Solution { - public boolean hasPathSum(TreeNode root, int sum) { - if (root == null) - return false; - - if (root.left == null && root.right == null) - return sum == root.val; - - return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); - } -};`, - python: ` -class Solution: - def hasPathSum(self, root: TreeNode, sum: int) -> bool: - if not root: - return False - - if not root.left and not root.right: - return sum == root.val - - return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) - `, - }, - }, - - generatePascalTriangle: { - title: "20. Pascal's Triangle", - description: - "Given an integer numRows, return a string that concatenates the elements of the first numRows of Pascal's triangle in a single line.", - examples: [ - { input: "5", output: [[1], [1, 1], [1, 2, 1], [1, 3, 3], [1, 4, 6]] }, - { input: "1", output: [[1]] }, - ], - solution: { - cpp: ` -class Solution { -public: - vector> generate(int numRows) { - vector> res(numRows); - - for (int i = 0; i < numRows; i++) { - res[i].resize(i + 1); // number of rows - res[i][0] = res[i][i] = 1; - - for (int j = 1; j < i; j++) { - res[i][j] = res[i - 1][j - 1] + res[i - 1][j]; - } - } - return res; - } -};`, - java: ` -class Solution { - public List> generate(int numRows) { - List> res = new ArrayList<>(); - - for (int i = 0; i < numRows; i++) { - List row = new ArrayList<>(Collections.nCopies(i + 1, 0)); - row.set(0, 1); - row.set(i, 1); - - for (int j = 1; j < i; j++) { - row.set(j, res.get(i - 1).get(j - 1) + res.get(i - 1).get(j)); - } - res.add(row); - } - return res; - } -};`, - python: ` -class Solution: - def generate(self, numRows: int) -> List[List[int]]: - res = [] - - for i in range(numRows): - row = [1] * (i + 1) - for j in range(1, i): - row[j] = res[i - 1][j - 1] + res[i - 1][j] - res.append(row) - - return res - `, - }, - }, - - maxProfit: { - title: "21. Best Time to Buy and Sell Stock", - description: - "You are given an array prices where prices[i] represents the price of a given stock on the i-th day.You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.Return the maximum profit you can achieve from this transaction. If no profit can be made, return 0.", - examples: [ - { input: "[7,1,5,3,6,4]", output: "5" }, - { input: "[7,6,4,3,1]", output: "0" }, - ], - solution: { - cpp: ` -class Solution { -public: - int maxProfit(vector& prices) { - int minm = INT_MAX; - int result = 0; - - for (int i = 0; i < prices.size(); i++) { - minm = min(minm , prices[i]); - result = max(prices[i] - minm , result); - } - return result; - } -};`, - java: ` -class Solution { - public int maxProfit(int[] prices) { - int minm = Integer.MAX_VALUE; - int result = 0; - - for (int price : prices) { - minm = Math.min(minm, price); - result = Math.max(result, price - minm); - } - return result; - } -};`, - python: ` -class Solution: - def maxProfit(self, prices: List[int]) -> int: - minm = float('inf') - result = 0 - - for price in prices: - minm = min(minm, price) - result = max(result, price - minm) - - return result - `, - }, - }, - - hasCycle: { - title: "22. Linked List Cycle", - description: - "Given the head of a linked list, determine if the linked list has a cycle in it.", - examples: [ - { input: "[3,2,0,-4], pos=1", output: "true" }, - { input: "[1,2], pos=0", output: "true" }, - { input: "[1], pos=-1", output: "false" }, - ], - solution: { - cpp: ` -class Solution { -public: - bool hasCycle(ListNode *head) { - if (head == NULL || head->next == NULL) - return false; - - ListNode *slow = head; - ListNode *fast = head; - - while (fast->next != NULL && fast->next->next != NULL) { - fast = fast->next->next; - slow = slow->next; - - if (fast == slow) - return true; - } - - return false; - } -};`, - java: ` -class Solution { - public boolean hasCycle(ListNode head) { - if (head == null || head.next == null) - return false; - - ListNode slow = head; - ListNode fast = head; - - while (fast.next != null && fast.next.next != null) { - slow = slow.next; - fast = fast.next.next; - - if (slow == fast) - return true; - } - - return false; - } -};`, - python: ` -class Solution: - def hasCycle(self, head: ListNode) -> bool: - if not head or not head.next: - return False - - slow = head - fast = head - - while fast and fast.next: - slow = slow.next - fast = fast.next.next - - if slow == fast: - return True - - return False - `, - }, - }, - preorderTraversal: { - title: "23. Binary Tree Preorder Traversal", - description: - "Given the root of a binary tree, return the preorder traversal of its nodes' values.", - examples: [ - { input: "[1,null,2,3]", output: "[1,2,3]" }, - { input: "[]", output: "[]" }, - { input: "[1]", output: "[1]" }, - { input: "[1,2]", output: "[1,2]" }, - { input: "[1,null,2]", output: "[1,2]" }, - ], - solution: { - cpp: ` - class Solution { - public: - vector ans; - vector preorderTraversal(TreeNode* root) { - if (root == NULL) - return ans; - - ans.push_back(root->val); - preorderTraversal(root->left); - preorderTraversal(root->right); - - return ans; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public List preorderTraversal(TreeNode root) { - List result = new ArrayList<>(); - preorder(root, result); - return result; - } - - private void preorder(TreeNode node, List result) { - if (node == null) return; - result.add(node.val); - preorder(node.left, result); - preorder(node.right, result); - } - };`, - - python: ` - class Solution: - def preorderTraversal(self, root: TreeNode) -> List[int]: - result = [] - self.preorder(root, result) - return result - - def preorder(self, node: TreeNode, result: List[int]) -> None: - if not node: - return - result.append(node.val) - self.preorder(node.left, result) - self.preorder(node.right, result) - `, - }, - }, - - postorderTraversal: { - title: "24. Binary Tree Postorder Traversal", - description: - "Given the root of a binary tree, return the postorder traversal of its nodes' values.", - examples: [ - { input: "[1,null,2,3]", output: "[3,2,1]" }, - { input: "[]", output: "[]" }, - { input: "[1]", output: "[1]" }, - { input: "[1,2]", output: "[2,1]" }, - { input: "[1,null,2]", output: "[2,1]" }, - ], - solution: { - cpp: ` - class Solution { - public: - vector ans; - vector postorderTraversal(TreeNode* root) { - if (root == NULL) - return ans; - - postorderTraversal(root->left); - postorderTraversal(root->right); - ans.push_back(root->val); - - return ans; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public List postorderTraversal(TreeNode root) { - List result = new ArrayList<>(); - postorder(root, result); - return result; - } - - private void postorder(TreeNode node, List result) { - if (node == null) return; - postorder(node.left, result); - postorder(node.right, result); - result.add(node.val); - } - };`, - - python: ` - class Solution: - def postorderTraversal(self, root: TreeNode) -> List[int]: - result = [] - self.postorder(root, result) - return result - - def postorder(self, node: TreeNode, result: List[int]) -> None: - if not node: - return - self.postorder(node.left, result) - self.postorder(node.right, result) - result.append(node.val) - `, - }, - }, - - removeElements: { - title: "25. Remove Linked List Elements", - description: - "Given the head of a linked list and an integer val, remove all the nodes of the linked list that have Node.val equal to val, and return the new head.", - examples: [ - { input: "[1,2,6,3,4,5,6], val=6", output: "[1,2,3,4,5]" }, - { input: "[], val=1", output: "[]" }, - { input: "[7,7,7,7], val=7", output: "[]" }, - ], - solution: { - cpp: ` - class Solution { - public: - ListNode* removeElements(ListNode* head, int val) { - if (head == NULL) - return head; - if (head->val == val) - return removeElements(head->next, val); - head->next = removeElements(head->next, val); - return head; - } - };`, - - java: ` - class Solution { - public ListNode removeElements(ListNode head, int val) { - if (head == null) return null; - if (head.val == val) return removeElements(head.next, val); - head.next = removeElements(head.next, val); - return head; - } - };`, - - python: ` - class Solution: - def removeElements(self, head: ListNode, val: int) -> ListNode: - if not head: - return None - if head.val == val: - return self.removeElements(head.next, val) - head.next = self.removeElements(head.next, val) - return head - `, - }, - }, - - reverseList: { - title: "26. Reverse Linked List", - description: - "Given the head of a singly linked list, reverse the list, and return the reversed list.", - examples: [ - { input: "[1,2,3,4,5]", output: "[5,4,3,2,1]" }, - { input: "[1,2]", output: "[2,1]" }, - { input: "[]", output: "[]" }, - ], - solution: { - cpp: ` - class Solution { - public: - ListNode* reverseList(ListNode* head) { - vector res; - ListNode* temp = head; - while (temp) { - res.push_back(temp->val); - temp = temp->next; - } - - temp = head; - for (int i = res.size() - 1; i >= 0; i--) { - temp->val = res[i]; - temp = temp->next; - } - return head; - } - };`, - - java: ` - class Solution { - public ListNode reverseList(ListNode head) { - List values = new ArrayList<>(); - ListNode temp = head; - while (temp != null) { - values.add(temp.val); - temp = temp.next; - } - - temp = head; - for (int i = values.size() - 1; i >= 0; i--) { - temp.val = values.get(i); - temp = temp.next; - } - - return head; - } - };`, - - python: ` - class Solution: - def reverseList(self, head: ListNode) -> ListNode: - values = [] - current = head - while current: - values.append(current.val) - current = current.next - - current = head - for val in reversed(values): - current.val = val - current = current.next - - return head - `, - }, - }, - - findKthLargest: { - title: "27. Kth Largest Element in an Array", - description: - "Given an integer array nums and an integer k, return the kth largest element in the array.", - examples: [ - { input: "[3,2,1,5,6,4], k = 2", output: "5" }, - { input: "[3,2,3,1,2,4,5,5,6], k = 4", output: "4" }, - ], - solution: { - cpp: ` - class Solution { - public: - int findKthLargest(vector& nums, int k) { - sort(nums.begin(), nums.end()); - return nums[nums.size() - k]; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public int findKthLargest(int[] nums, int k) { - Arrays.sort(nums); - return nums[nums.length - k]; - } - };`, - - python: ` - class Solution: - def findKthLargest(self, nums: List[int], k: int) -> int: - nums.sort() - return nums[-k] - `, - }, - }, - - containsDuplicate: { - title: "28. Contains Duplicate", - description: - "Given an integer array nums, return true if any value appears at least twice in the array.", - examples: [ - { input: "[1,2,3,1]", output: "true" }, - { input: "[1,2,3,4]", output: "false" }, - { input: "[1,1,1,3,3,4,3,2,4,2]", output: "true" }, - ], - solution: { - cpp: ` - class Solution { - public: - bool containsDuplicate(vector& nums) { - return (nums.size() > unordered_set(nums.begin(), nums.end()).size()); - } - };`, - - java: ` - import java.util.*; - - class Solution { - public boolean containsDuplicate(int[] nums) { - Set numSet = new HashSet<>(); - for (int num : nums) { - if (!numSet.add(num)) return true; - } - return false; - } - };`, - - python: ` - class Solution: - def containsDuplicate(self, nums: List[int]) -> bool: - return len(nums) > len(set(nums)) - `, - }, - }, - - invertBinaryTree: { - title: "29. Invert Binary Tree", - description: - "Given the root of a binary tree, invert the tree and return its root.", - examples: [ - { input: "[4,2,7,1,3,6,9]", output: "[4,7,2,9,6,3,1]" }, - { input: "[2,1,3]", output: "[2,3,1]" }, - { input: "[]", output: "[]" }, - ], - solution: { - cpp: ` - class Solution { - public: - TreeNode* invertTree(TreeNode* root) { - if (root) { - invertTree(root->left); - invertTree(root->right); - swap(root->left, root->right); - } - return root; - } - };`, - - java: ` - class Solution { - public TreeNode invertTree(TreeNode root) { - if (root == null) return null; - TreeNode left = invertTree(root.left); - TreeNode right = invertTree(root.right); - root.left = right; - root.right = left; - return root; - } - };`, - - python: ` - class Solution: - def invertTree(self, root: TreeNode) -> TreeNode: - if root is None: - return None - root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) - return root - `, - }, - }, - - MyQueue: { - title: "30. Implement Queue using Stacks", - description: - "Implement a first-in-first-out (FIFO) queue using only two stacks.", - examples: [ - { - input: `["MyQueue", "push", "push", "peek", "pop", "empty"]`, - output: `[null,null,null,1,1,false]`, - }, - ], - solution: { - cpp: ` - class MyQueue { - public: - stack s1, s2; - - MyQueue() {} - - void push(int x) { - while (!s1.empty()) { - s2.push(s1.top()); - s1.pop(); - } - s2.push(x); - while (!s2.empty()) { - s1.push(s2.top()); - s2.pop(); - } - } - - int pop() { - int curr = s1.top(); - s1.pop(); - return curr; - } - - int peek() { - return s1.top(); - } - - bool empty() { - return s1.empty(); - } - };`, - - java: ` - import java.util.Stack; - - class MyQueue { - private Stack s1; - private Stack s2; - - public MyQueue() { - s1 = new Stack<>(); - s2 = new Stack<>(); - } - - public void push(int x) { - while (!s1.isEmpty()) { - s2.push(s1.pop()); - } - s2.push(x); - while (!s2.isEmpty()) { - s1.push(s2.pop()); - } - } - - public int pop() { - return s1.pop(); - } - - public int peek() { - return s1.peek(); - } - - public boolean empty() { - return s1.isEmpty(); - } - };`, - - python: ` - class MyQueue: - - def __init__(self): - self.s1 = [] - self.s2 = [] - - def push(self, x: int) -> None: - while self.s1: - self.s2.append(self.s1.pop()) - self.s2.append(x) - while self.s2: - self.s1.append(self.s2.pop()) - - def pop(self) -> int: - return self.s1.pop() - - def peek(self) -> int: - return self.s1[-1] - - def empty(self) -> bool: - return not self.s1 - `, - }, - }, - - isAnagram: { - title: "31. Valid Anagram", - description: - "Given two strings s and t, return true if t is an anagram of s, and false otherwise.", - examples: [ - { input: "anagram, nagaram", output: "true" }, - { input: "rat, car", output: "false" }, - ], - solution: { - cpp: ` - class Solution { - public: - bool isAnagram(string s, string t) { - if (s.length() != t.length()) - return false; - - int count[26] = {0}; - for (char ch : s) - count[ch - 'a']++; - - for (char ch : t) - count[ch - 'a']--; - - for (int i = 0; i < 26; i++) { - if (count[i] != 0) - return false; - } - - return true; - } - };`, - - java: ` - class Solution { - public boolean isAnagram(String s, String t) { - if (s.length() != t.length()) return false; - int[] count = new int[26]; - for (char c : s.toCharArray()) count[c - 'a']++; - for (char c : t.toCharArray()) { - if (--count[c - 'a'] < 0) return false; - } - return true; - } - };`, - - python: ` - class Solution: - def isAnagram(self, s: str, t: str) -> bool: - if len(s) != len(t): - return False - count = [0] * 26 - for ch in s: - count[ord(ch) - ord('a')] += 1 - for ch in t: - count[ord(ch) - ord('a')] -= 1 - return all(c == 0 for c in count) - `, - }, - }, - - missingNumber: { - title: "32. Missing Number", - description: - "Given an array nums containing n distinct numbers in the range [0,n], return the only number in the range that is missing from the array.", - examples: [ - { input: "[3, 0, 1]", output: "2" }, - { input: "[0, 1]", output: "2" }, - ], - solution: { - cpp: ` - class Solution { - public: - int missingNumber(vector& nums) { - int sum = 0; - int n = nums.size(); - - for (int i = 0; i < n; i++) { - sum += nums[i]; - } - - return (n * (n + 1) / 2 - sum); - } - };`, - - java: ` - class Solution { - public int missingNumber(int[] nums) { - int sum = 0, n = nums.length; - for (int num : nums) { - sum += num; - } - return n * (n + 1) / 2 - sum; - } - };`, - - python: ` - class Solution: - def missingNumber(self, nums: List[int]) -> int: - n = len(nums) - return n * (n + 1) // 2 - sum(nums) - `, - }, - }, - - guessNumber: { - title: "33. Guess Number Higher or Lower", - description: - "You are playing a Guess Game where you have to guess a number between 1 and n. Each time you guess wrong, the system will tell you whether the actual number is higher or lower.", - examples: [ - { input: "n=10, pick=6", output: "6" }, - { input: "n=1, pick=1", output: "1" }, - { input: "n=2, pick=2", output: "2" }, - ], - solution: { - cpp: ` - class Solution { - public: - int guessNumber(int n) { - int start = 1; - int end = n; - - while (start <= end) { - int mid = start + (end - start) / 2; - - if (guess(mid) == 0) - return mid; - else if (guess(mid) < 0) - end = mid - 1; - else - start = mid + 1; - } - - return -1; - } - };`, - - java: ` - class Solution extends GuessGame { - public int guessNumber(int n) { - int start = 1, end = n; - - while (start <= end) { - int mid = start + (end - start) / 2; - int result = guess(mid); - if (result == 0) return mid; - else if (result < 0) end = mid - 1; - else start = mid + 1; - } - - return -1; - } - };`, - - python: ` - class Solution: - def guessNumber(self, n: int) -> int: - start, end = 1, n - while start <= end: - mid = (start + end) // 2 - res = guess(mid) - if res == 0: - return mid - elif res < 0: - end = mid - 1 - else: - start = mid + 1 - `, - }, - }, - - intersect: { - title: "34. Intersection of Two Arrays II", - description: - "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays, and you may return the result in any order.", - examples: [ - { input: "[1, 2, 2, 1], [2, 2]", output: "[2, 2]" }, - { input: "[4, 9, 5], [9, 4, 9, 8, 4]", output: "[4, 9]" }, - ], - solution: { - cpp: ` - class Solution { - public: - vector intersect(vector& nums1, vector& nums2) { - vector ans; - sort(nums1.begin(), nums1.end()); - sort(nums2.begin(), nums2.end()); - - int i = 0, j = 0; - while (i < nums1.size() && j < nums2.size()) { - if (nums1[i] < nums2[j]) { - i++; - } else if (nums1[i] > nums2[j]) { - j++; - } else { - ans.push_back(nums1[i]); - i++; - j++; - } - } - return ans; - } - };`, - - java: ` - import java.util.Arrays; - import java.util.ArrayList; - - class Solution { - public int[] intersect(int[] nums1, int[] nums2) { - Arrays.sort(nums1); - Arrays.sort(nums2); - ArrayList result = new ArrayList<>(); - - int i = 0, j = 0; - while (i < nums1.length && j < nums2.length) { - if (nums1[i] < nums2[j]) { - i++; - } else if (nums1[i] > nums2[j]) { - j++; - } else { - result.add(nums1[i]); - i++; - j++; - } - } - - return result.stream().mapToInt(k -> k).toArray(); - } - };`, - - python: ` - class Solution: - def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: - nums1.sort() - nums2.sort() - result = [] - i = j = 0 - while i < len(nums1) and j < len(nums2): - if nums1[i] < nums2[j]: - i += 1 - elif nums1[i] > nums2[j]: - j += 1 - else: - result.append(nums1[i]) - i += 1 - j += 1 - return result - `, - }, - }, - - runningSum: { - title: "35. Running Sum of 1d Array", - description: "Given an array nums, return the running sum of nums.", - examples: [ - { input: "[1, 2, 3, 4]", output: "[1, 3, 6, 10]" }, - { input: "[5]", output: "[5]" }, - ], - solution: { - cpp: ` - class Solution { - public: - vector runningSum(vector& nums) { - for (int i = 1; i < nums.size(); i++) { - nums[i] += nums[i - 1]; - } - return nums; - } - };`, - - java: ` - class Solution { - public int[] runningSum(int[] nums) { - for (int i = 1; i < nums.length; i++) { - nums[i] += nums[i - 1]; - } - return nums; - } - };`, - - python: ` - class Solution: - def runningSum(self, nums: List[int]) -> List[int]: - for i in range(1, len(nums)): - nums[i] += nums[i - 1] - return nums - `, - }, - }, - - shuffleString: { - title: "36. Shuffle String", - description: - "Given a string s and an integer array indices of the same length as s, shuffle the string according to the indices array.", - examples: [ - { - input: `"codeleet", indices = [4, 5, 6, 7, 0, 2, 1, 3]`, - output: `"leetcode"`, - }, - ], - solution: { - cpp: ` - class Solution { - public: - string restoreString(string s, vector& indices) { - string res = s; - for (int i = 0; i < indices.size(); i++) { - res[indices[i]] = s[i]; - } - return res; - } - };`, - - java: ` - class Solution { - public String restoreString(String s, int[] indices) { - char[] res = new char[s.length()]; - for (int i = 0; i < s.length(); i++) { - res[indices[i]] = s.charAt(i); - } - return new String(res); - } - };`, - - python: ` - class Solution: - def restoreString(self, s: str, indices: List[int]) -> str: - res = [''] * len(s) - for i, idx in enumerate(indices): - res[idx] = s[i] - return ''.join(res) - `, - }, - }, - - maxLevelSum: { - title: "37. Maximum Level Sum of a Binary Tree", - description: - "Given the root of a binary tree, return the level with the maximum sum.", - examples: [{ input: "[1, 7, 0, 7, -8, null, null]", output: "2" }], - solution: { - cpp: ` - class Solution { - public: - int maxLevelSum(TreeNode* root) { - if (!root) return 0; - - queue q; - q.push(root); - - int maxSum = INT_MIN, level = 1, maxLevel = 1; - - while (!q.empty()) { - int size = q.size(); - int levelSum = 0; - - for (int i = 0; i < size; i++) { - TreeNode* node = q.front(); - q.pop(); - levelSum += node->val; - - if (node->left) q.push(node->left); - if (node->right) q.push(node->right); - } - - if (levelSum > maxSum) { - maxSum = levelSum; - maxLevel = level; - } - level++; - } - return maxLevel; - } - };`, - - java: ` - class Solution { - public int maxLevelSum(TreeNode root) { - if (root == null) return 0; - - Queue queue = new LinkedList<>(); - queue.add(root); - - int level = 1, maxLevel = 1; - int maxSum = Integer.MIN_VALUE; - - while (!queue.isEmpty()) { - int size = queue.size(); - int currentSum = 0; - - for (int i = 0; i < size; i++) { - TreeNode node = queue.poll(); - currentSum += node.val; - - if (node.left != null) queue.add(node.left); - if (node.right != null) queue.add(node.right); - } - - if (currentSum > maxSum) { - maxSum = currentSum; - maxLevel = level; - } - level++; - } - - return maxLevel; - } - };`, - - python: ` - class Solution: - def maxLevelSum(self, root: Optional[TreeNode]) -> int: - if not root: - return 0 - - q = deque([root]) - level = 1 - max_sum = float('-inf') - result_level = 1 - - while q: - current_sum = 0 - for _ in range(len(q)): - node = q.popleft() - current_sum += node.val - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - - if current_sum > max_sum: - max_sum = current_sum - result_level = level - - level += 1 - - return result_level - `, - }, - }, - - firstAlphabet: { - title: "38. First Alphabet of Each Word", - description: - "Given a string S, return a string containing the first letter of each word in the string.", - examples: [ - { input: `"geeks for geeks"`, output: `"gfg"` }, - { input: `"bad is good"`, output: `"big"` }, - ], - solution: { - cpp: ` - class Solution { - public: - string firstAlphabet(string S) { - string ans; - ans += S[0]; // Add the first character - - for (int i = 1; i < S.size(); i++) { - if (S[i - 1] == ' ') - ans += S[i]; // Add character after space - } - - return ans; - } - };`, - - java: ` - class Solution { - public String firstAlphabet(String S) { - StringBuilder ans = new StringBuilder(); - ans.append(S.charAt(0)); // Add first letter - - for (int i = 1; i < S.length(); i++) { - if (S.charAt(i - 1) == ' ') { - ans.append(S.charAt(i)); // Add letter after space - } - } - - return ans.toString(); - } - };`, - - python: ` - class Solution: - def firstAlphabet(self, S: str) -> str: - result = S[0] # Start with the first character - for i in range(1, len(S)): - if S[i-1] == ' ': - result += S[i] # Add character after space - return result - `, - }, - }, - - countLeaves: { - title: "39. Count Leaves in a Binary Tree", - description: "Given a Binary Tree, count the number of leaf nodes.", - examples: [ - { input: "[4, 8, 10, 7, 3, null, 5, null, null, null]", output: "3" }, - ], - solution: { - cpp: ` - int countLeaves(Node* root) { - if (!root) return 0; - - if (!root->left && !root->right) return 1; - - return countLeaves(root->left) + countLeaves(root->right); - };`, - - java: ` - class Solution { - public int countLeaves(Node root) { - if (root == null) return 0; - - if (root.left == null && root.right == null) return 1; - - return countLeaves(root.left) + countLeaves(root.right); - } - };`, - - python: ` - class Solution: - def countLeaves(self, root: Optional[Node]) -> int: - if not root: - return 0 - - if not root.left and not root.right: - return 1 - - return self.countLeaves(root.left) + self.countLeaves(root.right) - `, - }, - }, - - generateBinaryNumbers: { - title: "40. Generate Binary Numbers from 1 to N", - description: - "Given a number N, generate and print all binary numbers with decimal values from 1 to N.", - examples: [ - { input: "N = 2", output: "1 10" }, - { input: "N = 5", output: "1 10 11 100 101" }, - ], - solution: { - cpp: ` - vector generate(int N) { - queue q; - vector v; - - q.push("1"); - while (N--) { - string s = q.front(); - v.push_back(s); - q.pop(); - q.push(s + "0"); - q.push(s + "1"); - } - return v; - };`, - - java: ` - import java.util.*; - class Solution { - public List generate(int N) { - Queue q = new LinkedList<>(); - List result = new ArrayList<>(); - - q.add("1"); - while (N-- > 0) { - String s = q.poll(); - result.add(s); - q.add(s + "0"); - q.add(s + "1"); - } - return result; - } - };`, - - python: ` - from collections import deque - class Solution: - def generate(self, N: int) -> List[str]: - q = deque(["1"]) - result = [] - while N > 0: - s = q.popleft() - result.append(s) - q.append(s + '0') - q.append(s + '1') - N -= 1 - return result - `, - }, - }, - - minimumDifference: { - title: "41. Minimum Difference Between Any Pair", - description: - "Given an unsorted array, find the minimum difference between any pair in the given array.", - examples: [ - { input: "[2, 4, 5, 9, 7]", output: "1" }, - { input: "[3, 10, 8, 6]", output: "2" }, - ], - solution: { - cpp: ` - class Solution { - public: - int minimum_difference(vector nums) { - sort(nums.begin(), nums.end()); - int minm = INT_MAX; - - for (int i = 0; i < nums.size() - 1; i++) { - minm = min(minm, nums[i + 1] - nums[i]); - } - return minm; - } - };`, - - java: ` - import java.util.*; - class Solution { - public int minimum_difference(int[] nums) { - Arrays.sort(nums); - int minm = Integer.MAX_VALUE; - - for (int i = 0; i < nums.length - 1; i++) { - minm = Math.min(minm, nums[i + 1] - nums[i]); - } - return minm; - } - };`, - - python: ` - class Solution: - def minimum_difference(self, nums: List[int]) -> int: - nums.sort() - minm = float('inf') - - for i in range(len(nums) - 1): - minm = min(minm, nums[i + 1] - nums[i]) - - return minm - `, - }, - }, - - mthHalf: { - title: "42. Halve N, M-1 Times", - description: - "Given two values N and M, return the value when N is halved M-1 times.", - examples: [ - { input: "N = 100, M = 4", output: "12" }, - { input: "N = 10, M = 5", output: "0" }, - ], - solution: { - cpp: ` - class Solution { - public: - int mthHalf(int N, int M) { - return N / pow(2, M - 1); - } - };`, - - java: ` - class Solution { - public int mthHalf(int N, int M) { - return (int) (N / Math.pow(2, M - 1)); - } - };`, - - python: ` - class Solution: - def mthHalf(self, N: int, M: int) -> int: - return N // (2 ** (M - 1)) - `, - }, - }, - - removeChars: { - title: "43. Remove Characters from First String", - description: - "Given two strings string1 and string2, remove those characters from string1 which are present in string2.", - examples: [ - { input: 'string1 = "computer", string2 = "cat"', output: '"ompuer"' }, - { input: 'string1 = "occurrence", string2 = "car"', output: '"ouene"' }, - ], - solution: { - cpp: ` - class Solution { - public: - string removeChars(string string1, string string2) { - int arr[26] = {0}; - for (int i = 0; i < string2.size(); i++) - arr[string2[i] - 'a']++; - - string ans; - for (int i = 0; i < string1.size(); i++) { - if (arr[string1[i] - 'a'] == 0) // If value is 0, add to new string - ans += string1[i]; - } - return ans; - } - };`, - - java: ` - class Solution { - public String removeChars(String string1, String string2) { - int[] arr = new int[26]; - for (int i = 0; i < string2.length(); i++) - arr[string2.charAt(i) - 'a']++; - - StringBuilder ans = new StringBuilder(); - for (int i = 0; i < string1.length(); i++) { - if (arr[string1.charAt(i) - 'a'] == 0) - ans.append(string1.charAt(i)); - } - return ans.toString(); - } - };`, - - python: ` - class Solution: - def removeChars(self, string1: str, string2: str) -> str: - arr = [0] * 26 - for char in string2: - arr[ord(char) - ord('a')] += 1 - - ans = [] - for char in string1: - if arr[ord(char) - ord('a')] == 0: - ans.append(char) - - return ''.join(ans) - `, - }, - }, - - rotateArray: { - title: "44. Rotate Array by D Elements", - description: - "Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).", - examples: [ - { - input: "N = 5, D = 2, arr = [1, 2, 3, 4, 5]", - output: "[3, 4, 5, 1, 2]", - }, - { - input: "N = 10, D = 3, arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]", - output: "[8, 10, 12, 14, 16, 18, 20, 2, 4, 6]", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - void rotateArray(int n, int d, vector& arr) { - d = d % n; // Handle cases where d >= n - vector rotated(n); - - for (int i = 0; i < n; i++) { - rotated[(i + n - d) % n] = arr[i]; - } - - for (int i = 0; i < n; i++) { - cout << rotated[i] << " "; - } - cout << endl; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public void rotateArray(int n, int d, int[] arr) { - d = d % n; // Handle cases where d >= n - int[] rotated = new int[n]; - - for (int i = 0; i < n; i++) { - rotated[(i + n - d) % n] = arr[i]; - } - - for (int i = 0; i < n; i++) { - System.out.print(rotated[i] + " "); - } - System.out.println(); - } - };`, - - python: ` - class Solution: - def rotateArray(self, n: int, d: int, arr: List[int]) -> List[int]: - d = d % n # Handle cases where d >= n - return arr[d:] + arr[:d] - `, - }, - }, - longestIncreasingSubsequence: { - title: "45. Longest Increasing Subsequence", - description: - "Given an array arr[] of size N, find the length of the longest subsequence of the array which is strictly increasing.", - examples: [ - { - input: "N = 6, arr = [5, 8, 3, 7, 9, 1]", - output: "3", - explanation: "The longest increasing subsequence is [5, 7, 9], so the length is 3.", - }, - { - input: "N = 4, arr = [3, 10, 2, 1, 20]", - output: "3", - explanation: "The longest increasing subsequence is [3, 10, 20], so the length is 3.", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - int longestIncreasingSubsequence(int n, vector& arr) { - vector lis(n, 1); - - for (int i = 1; i < n; i++) { - for (int j = 0; j < i; j++) { - if (arr[i] > arr[j] && lis[i] < lis[j] + 1) { - lis[i] = lis[j] + 1; - } - } - } - - return *max_element(lis.begin(), lis.end()); - } - };`, - - java: ` - import java.util.*; - - class Solution { - public int longestIncreasingSubsequence(int n, int[] arr) { - int[] lis = new int[n]; - Arrays.fill(lis, 1); - - for (int i = 1; i < n; i++) { - for (int j = 0; j < i; j++) { - if (arr[i] > arr[j] && lis[i] < lis[j] + 1) { - lis[i] = lis[j] + 1; - } - } - } - - int max = 0; - for (int length : lis) { - max = Math.max(max, length); - } - return max; - } - };`, - - python: ` - from typing import List - - class Solution: - def longestIncreasingSubsequence(self, n: int, arr: List[int]) -> int: - lis = [1] * n - - for i in range(1, n): - for j in range(i): - if arr[i] > arr[j]: - lis[i] = max(lis[i], lis[j] + 1) - - return max(lis) - `, - }, - }, - - intersectionOfTwoLinkedLists: { - title: "46. Intersection of Two Linked Lists", - description: - "Given the heads of two singly linked lists, headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection, return null.", - examples: [ - { - input: "headA = [4,1,8,4,5], headB = [5,6,1,8,4,5]", - output: "Intersected at '8'", - explanation: - "The two linked lists intersect at node '8'.", - }, - { - input: "headA = [1,9,1,2,4], headB = [3,2,4]", - output: "Intersected at '2'", - explanation: - "The two linked lists intersect at node '2'.", - }, - { - input: "headA = [2,6,4], headB = [1,5]", - output: "null", - explanation: - "The two linked lists do not intersect, so the output is null.", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - struct ListNode { - int val; - ListNode *next; - ListNode(int x) : val(x), next(NULL) {} - }; - - class Solution { - public: - ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { - if (!headA || !headB) return NULL; - - ListNode *a = headA; - ListNode *b = headB; - - while (a != b) { - a = a ? a->next : headB; - b = b ? b->next : headA; - } - - return a; - } - };`, - - java: ` - public class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } - } - - public class Solution { - public ListNode getIntersectionNode(ListNode headA, ListNode headB) { - if (headA == null || headB == null) return null; - - ListNode a = headA; - ListNode b = headB; - - while (a != b) { - a = (a != null) ? a.next : headB; - b = (b != null) ? b.next : headA; - } - - return a; - } - };`, - - python: ` - class ListNode: - def __init__(self, x): - self.val = x - self.next = None - - class Solution: - def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: - if not headA or not headB: - return None - - a, b = headA, headB - - while a != b: - a = a.next if a else headB - b = b.next if b else headA - - return a - `, - }, - }, - - coinChange: { - title: "47. Coin Change", - description: - "Given an integer array 'coins' representing different coin denominations and an integer 'amount' representing a total amount of money, return the fewest number of coins that you need to make up that amount. If that amount cannot be made up by any combination of the coins, return -1.", - examples: [ - { - input: "coins = [1, 2, 5], amount = 11", - output: "3", - explanation: - "The fewest number of coins needed is 3: 11 = 5 + 5 + 1.", - }, - { - input: "coins = [2], amount = 3", - output: "-1", - explanation: - "It is not possible to make up the amount 3 with only coin of denomination 2.", - }, - { - input: "coins = [1], amount = 0", - output: "0", - explanation: - "The amount is already 0, so no coins are needed.", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - int coinChange(vector& coins, int amount) { - vector dp(amount + 1, amount + 1); - dp[0] = 0; - - for (int i = 1; i <= amount; i++) { - for (int coin : coins) { - if (i - coin >= 0) { - dp[i] = min(dp[i], 1 + dp[i - coin]); - } - } - } - - return dp[amount] == amount + 1 ? -1 : dp[amount]; - } - };`, - - java: ` - import java.util.Arrays; - - public class Solution { - public int coinChange(int[] coins, int amount) { - int[] dp = new int[amount + 1]; - Arrays.fill(dp, amount + 1); - dp[0] = 0; - - for (int i = 1; i <= amount; i++) { - for (int coin : coins) { - if (i - coin >= 0) { - dp[i] = Math.min(dp[i], 1 + dp[i - coin]); - } - } - } - - return dp[amount] == amount + 1 ? -1 : dp[amount]; - } - };`, - - python: ` - class Solution: - def coinChange(self, coins: List[int], amount: int) -> int: - dp = [float('inf')] * (amount + 1) - dp[0] = 0 - - for i in range(1, amount + 1): - for coin in coins: - if i - coin >= 0: - dp[i] = min(dp[i], 1 + dp[i - coin]) - - return dp[amount] if dp[amount] != float('inf') else -1 - `, - }, - }, - - quickSortAndMergeSort: { - title: "48. QuickSort and MergeSort", - description: - "Implement the QuickSort and MergeSort algorithms to sort an array of integers. QuickSort is a divide-and-conquer algorithm that selects a 'pivot' element and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot. MergeSort also uses divide-and-conquer by dividing the array into halves, sorting each half, and merging them back together.", - examples: [ - { - input: "array = [3, 6, 8, 10, 1, 2, 1]", - output: "[1, 1, 2, 3, 6, 8, 10]", - explanation: - "The array is sorted in ascending order using either QuickSort or MergeSort.", - }, - { - input: "array = [5, 2, 9, 1, 5, 6]", - output: "[1, 2, 5, 5, 6, 9]", - explanation: - "Both sorting algorithms yield the same sorted array.", - }, - { - input: "array = []", - output: "[]", - explanation: - "An empty array remains empty after sorting.", - }, - ], - solution: { - cpp: ` -#include -using namespace std; - -// QuickSort -void quickSort(vector& nums, int low, int high) { - if (low < high) { - int pivot = partition(nums, low, high); - quickSort(nums, low, pivot - 1); - quickSort(nums, pivot + 1, high); - } -} - -int partition(vector& nums, int low, int high) { - int pivot = nums[high]; - int i = low - 1; - for (int j = low; j < high; j++) { - if (nums[j] < pivot) { - i++; - swap(nums[i], nums[j]); - } - } - swap(nums[i + 1], nums[high]); - return i + 1; -} - -// MergeSort -void mergeSort(vector& nums, int left, int right) { - if (left < right) { - int mid = left + (right - left) / 2; - mergeSort(nums, left, mid); - mergeSort(nums, mid + 1, right); - merge(nums, left, mid, right); - } -} - -void merge(vector& nums, int left, int mid, int right) { - int n1 = mid - left + 1; - int n2 = right - mid; - vector L(n1), R(n2); - for (int i = 0; i < n1; i++) L[i] = nums[left + i]; - for (int j = 0; j < n2; j++) R[j] = nums[mid + 1 + j]; - int i = 0, j = 0, k = left; - while (i < n1 && j < n2) { - if (L[i] <= R[j]) nums[k++] = L[i++]; - else nums[k++] = R[j++]; - } - while (i < n1) nums[k++] = L[i++]; - while (j < n2) nums[k++] = R[j++]; -} -`, - - java: ` -import java.util.Arrays; - -public class Solution { - // QuickSort - public void quickSort(int[] nums, int low, int high) { - if (low < high) { - int pivot = partition(nums, low, high); - quickSort(nums, low, pivot - 1); - quickSort(nums, pivot + 1, high); - } - } - - private int partition(int[] nums, int low, int high) { - int pivot = nums[high]; - int i = (low - 1); - for (int j = low; j < high; j++) { - if (nums[j] < pivot) { - i++; - swap(nums, i, j); - } - } - swap(nums, i + 1, high); - return i + 1; - } - - private void swap(int[] nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } - - // MergeSort - public void mergeSort(int[] nums, int left, int right) { - if (left < right) { - int mid = left + (right - left) / 2; - mergeSort(nums, left, mid); - mergeSort(nums, mid + 1, right); - merge(nums, left, mid, right); - } - } - - private void merge(int[] nums, int left, int mid, int right) { - int n1 = mid - left + 1; - int n2 = right - mid; - int[] L = new int[n1]; - int[] R = new int[n2]; - for (int i = 0; i < n1; i++) L[i] = nums[left + i]; - for (int j = 0; j < n2; j++) R[j] = nums[mid + 1 + j]; - int i = 0, j = 0, k = left; - while (i < n1 && j < n2) { - if (L[i] <= R[j]) nums[k++] = L[i++]; - else nums[k++] = R[j++]; - } - while (i < n1) nums[k++] = L[i++]; - while (j < n2) nums[k++] = R[j++]; - } -} -`, - - python: ` -class Solution: - # QuickSort - def quickSort(self, nums: List[int], low: int, high: int) -> None: - if low < high: - pivot = self.partition(nums, low, high) - self.quickSort(nums, low, pivot - 1) - self.quickSort(nums, pivot + 1, high) - - def partition(self, nums: List[int], low: int, high: int) -> int: - pivot = nums[high] - i = low - 1 - for j in range(low, high): - if nums[j] < pivot: - i += 1 - nums[i], nums[j] = nums[j], nums[i] - nums[i + 1], nums[high] = nums[high], nums[i + 1] - return i + 1 - - # MergeSort - def mergeSort(self, nums: List[int], left: int, right: int) -> None: - if left < right: - mid = left + (right - left) // 2 - self.mergeSort(nums, left, mid) - self.mergeSort(nums, mid + 1, right) - self.merge(nums, left, mid, right) - - def merge(self, nums: List[int], left: int, mid: int, right: int) -> None: - n1 = mid - left + 1 - n2 = right - mid - L = nums[left:left + n1] - R = nums[mid + 1:mid + 1 + n2] - i = j = 0 - k = left - while i < n1 and j < n2: - if L[i] <= R[j]: - nums[k] = L[i] - i += 1 - else: - nums[k] = R[j] - j += 1 - k += 1 - while i < n1: - nums[k] = L[i] - i += 1 - k += 1 - while j < n2: - nums[k] = R[j] - j += 1 - k += 1 -`, - }, -}, - -countInversions: { - title: "49. Count Inversions in an Array", - description: - "Implement a function to count the number of inversions in an array. An inversion is defined as a pair of indices (i, j) such that i < j and arr[i] > arr[j]. This can be achieved efficiently using a modified MergeSort algorithm, which counts inversions while merging.", - examples: [ - { - input: "array = [2, 4, 1, 3, 5]", - output: "3", - explanation: - "The inversions are (2, 1), (4, 1), and (4, 3).", - }, - { - input: "array = [1, 20, 6, 4, 5]", - output: "5", - explanation: - "The inversions are (1, 6), (1, 4), (1, 5), (20, 6), and (20, 4).", - }, - { - input: "array = [1, 2, 3, 4, 5]", - output: "0", - explanation: - "There are no inversions in a sorted array.", - }, - ], - solution: { - cpp: ` -#include -using namespace std; - -int mergeAndCount(vector& arr, int left, int mid, int right) { - int i = left; - int j = mid + 1; - int k = 0; - int inv_count = 0; - vector temp(right - left + 1); - - while (i <= mid && j <= right) { - if (arr[i] <= arr[j]) { - temp[k++] = arr[i++]; - } else { - temp[k++] = arr[j++]; - inv_count += (mid - i + 1); // Count inversions - } - } - - while (i <= mid) temp[k++] = arr[i++]; - while (j <= right) temp[k++] = arr[j++]; - - for (int i = left; i <= right; i++) arr[i] = temp[i - left]; - - return inv_count; -} - -int mergeSortAndCount(vector& arr, int left, int right) { - int inv_count = 0; - if (left < right) { - int mid = left + (right - left) / 2; - inv_count += mergeSortAndCount(arr, left, mid); - inv_count += mergeSortAndCount(arr, mid + 1, right); - inv_count += mergeAndCount(arr, left, mid, right); - } - return inv_count; -} - -int countInversions(vector& arr) { - return mergeSortAndCount(arr, 0, arr.size() - 1); -} -`, - - java: ` -public class Solution { - public int mergeAndCount(int[] arr, int left, int mid, int right) { - int i = left; - int j = mid + 1; - int k = 0; - int invCount = 0; - int[] temp = new int[right - left + 1]; - - while (i <= mid && j <= right) { - if (arr[i] <= arr[j]) { - temp[k++] = arr[i++]; - } else { - temp[k++] = arr[j++]; - invCount += (mid - i + 1); - } - } - - while (i <= mid) temp[k++] = arr[i++]; - while (j <= right) temp[k++] = arr[j++]; - - for (int m = left; m <= right; m++) arr[m] = temp[m - left]; - - return invCount; - } - - public int mergeSortAndCount(int[] arr, int left, int right) { - int invCount = 0; - if (left < right) { - int mid = left + (right - left) / 2; - invCount += mergeSortAndCount(arr, left, mid); - invCount += mergeSortAndCount(arr, mid + 1, right); - invCount += mergeAndCount(arr, left, mid, right); - } - return invCount; - } - - public int countInversions(int[] arr) { - return mergeSortAndCount(arr, 0, arr.length - 1); - } -} -`, - - python: ` -class Solution: - def mergeAndCount(self, arr, left, mid, right): - i = left - j = mid + 1 - k = 0 - inv_count = 0 - temp = [] - - while i <= mid and j <= right: - if arr[i] <= arr[j]: - temp.append(arr[i]) - i += 1 - else: - temp.append(arr[j]) - inv_count += (mid - i + 1) - j += 1 - - while i <= mid: - temp.append(arr[i]) - i += 1 - while j <= right: - temp.append(arr[j]) - j += 1 - - for m in range(len(temp)): - arr[left + m] = temp[m] - - return inv_count - - def mergeSortAndCount(self, arr, left, right): - inv_count = 0 - if left < right: - mid = left + (right - left) // 2 - inv_count += self.mergeSortAndCount(arr, left, mid) - inv_count += self.mergeSortAndCount(arr, mid + 1, right) - inv_count += self.mergeAndCount(arr, left, mid, right) - return inv_count - - def countInversions(self, arr): - return self.mergeSortAndCount(arr, 0, len(arr) - 1) -`, - }, -}, - -sortArray012: { - title: "50. Sort an Array of 0s, 1s, and 2s", - description: - "Implement a function to sort an array containing only 0s, 1s, and 2s. The task can be efficiently accomplished using the Dutch National Flag algorithm, which categorizes the elements in a single pass through the array.", - examples: [ - { - input: "array = [2, 0, 1, 2, 0, 1, 1]", - output: "[0, 0, 1, 1, 1, 2, 2]", - explanation: - "The array is sorted in ascending order with all 0s followed by 1s and then 2s.", - }, - { - input: "array = [1, 2, 0, 0, 1, 2]", - output: "[0, 0, 1, 1, 2, 2]", - explanation: - "After sorting, the array contains all 0s first, followed by 1s and then 2s.", - }, - { - input: "array = []", - output: "[]", - explanation: - "An empty array remains empty after sorting.", - }, - ], - solution: { - cpp: ` -#include -using namespace std; - -void sortColors(vector& nums) { - int low = 0, mid = 0, high = nums.size() - 1; - while (mid <= high) { - if (nums[mid] == 0) { - swap(nums[low++], nums[mid++]); - } else if (nums[mid] == 1) { - mid++; - } else { - swap(nums[mid], nums[high--]); - } - } -} -`, - - java: ` -public class Solution { - public void sortColors(int[] nums) { - int low = 0, mid = 0, high = nums.length - 1; - while (mid <= high) { - if (nums[mid] == 0) { - swap(nums, low++, mid++); - } else if (nums[mid] == 1) { - mid++; - } else { - swap(nums, mid, high--); - } - } - } - - private void swap(int[] nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } -} -`, - - python: ` -class Solution: - def sortColors(self, nums: List[int]) -> None: - low, mid, high = 0, 0, len(nums) - 1 - while mid <= high: - if nums[mid] == 0: - nums[low], nums[mid] = nums[mid], nums[low] - low += 1 - mid += 1 - elif nums[mid] == 1: - mid += 1 - else: - nums[mid], nums[high] = nums[high], nums[mid] - high -= 1 -`, - }, -}, - -searchInNearlySortedArray: { - title: "51. Perform a Search in a Nearly Sorted Array", - description: - "Implement a function to search for a target element in a nearly sorted array. In a nearly sorted array, each element is at most one position away from its original position. This allows for an efficient search using a modified binary search algorithm.", - examples: [ - { - input: "array = [10, 3, 40, 20, 50, 80, 70], target = 20", - output: "3", - explanation: - "The target element 20 is found at index 3 in the array.", - }, - { - input: "array = [10, 3, 40, 20, 50, 80, 70], target = 90", - output: "-1", - explanation: - "The target element 90 is not present in the array, so the output is -1.", - }, - { - input: "array = [1], target = 1", - output: "0", - explanation: - "The array contains only one element, which is the target; thus, it is found at index 0.", - }, - ], - solution: { - cpp: ` -#include -using namespace std; - -int searchInNearlySortedArray(vector& arr, int target) { - int n = arr.size(); - for (int i = 0; i < n; i++) { - if (arr[i] == target) { - return i; - } - if (i > 0 && arr[i - 1] == target) { - return i - 1; - } - if (i < n - 1 && arr[i + 1] == target) { - return i + 1; - } - } - return -1; -} -`, - - java: ` -public class Solution { - public int searchInNearlySortedArray(int[] arr, int target) { - int n = arr.length; - for (int i = 0; i < n; i++) { - if (arr[i] == target) { - return i; - } - if (i > 0 && arr[i - 1] == target) { - return i - 1; - } - if (i < n - 1 && arr[i + 1] == target) { - return i + 1; - } - } - return -1; - } -} -`, - - python: ` -class Solution: - def searchInNearlySortedArray(self, arr: List[int], target: int) -> int: - n = len(arr) - for i in range(n): - if arr[i] == target: - return i - if i > 0 and arr[i - 1] == target: - return i - 1 - if i < n - 1 and arr[i + 1] == target: - return i + 1 - return -1 -`, - }, -}, - flattenMultilevelDoublyLinkedList: { - title: "52. Flatten a Multilevel Doubly Linked List", - description: - "You are given a doubly linked list, where each node contains a next pointer, a prev pointer, and an additional child pointer that may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure. Flatten the list so that all the nodes appear in a single-level, doubly linked list. Preserve the order of nodes in the list, and return the head of the flattened list.", - examples: [ - { - input: "head = [1, 2, 3, 4, 5, 6] (with 3->7->8->9->10 and 8->11->12)", - output: "[1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6]", - }, - { - input: "head = [1, 2, null, 3] (with 1->2->3, and 1->child->4->5->6)", - output: "[1, 4, 5, 6, 2, 3]", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - // Definition for a Node. - class Node { - public: - int val; - Node* next; - Node* prev; - Node* child; - Node(int _val) : val(_val), next(NULL), prev(NULL), child(NULL) {} - }; - - class Solution { - public: - Node* flatten(Node* head) { - if (!head) return head; - Node* curr = head; - while (curr) { - if (curr->child) { - Node* nextNode = curr->next; - Node* child = flatten(curr->child); - - curr->next = child; - child->prev = curr; - curr->child = NULL; - - Node* temp = child; - while (temp->next) temp = temp->next; - - temp->next = nextNode; - if (nextNode) nextNode->prev = temp; - } - curr = curr->next; - } - return head; - } - };`, - - java: ` - import java.util.*; - - class Node { - public int val; - public Node next; - public Node prev; - public Node child; - - public Node(int val) { - this.val = val; - } - } - - class Solution { - public Node flatten(Node head) { - if (head == null) return head; - Node curr = head; - while (curr != null) { - if (curr.child != null) { - Node nextNode = curr.next; - Node child = flatten(curr.child); - - curr.next = child; - child.prev = curr; - curr.child = null; - - Node temp = child; - while (temp.next != null) temp = temp.next; - - temp.next = nextNode; - if (nextNode != null) nextNode.prev = temp; - } - curr = curr.next; - } - return head; - } - }`, - - python: ` - class Node: - def __init__(self, val=0, next=None, prev=None, child=None): - self.val = val - self.next = next - self.prev = prev - self.child = child - - class Solution: - def flatten(self, head: 'Node') -> 'Node': - if not head: - return head - curr = head - while curr: - if curr.child: - next_node = curr.next - child = self.flatten(curr.child) - - curr.next = child - child.prev = curr - curr.child = None - - temp = child - while temp.next: - temp = temp.next - - temp.next = next_node - if next_node: - next_node.prev = temp - curr = curr.next - return head - `, - }, - }, - findAllAnagramsInString: { - title: "53. Find All Anagrams in a String", - description: - "Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consist of lowercase English letters, and the order of output does not matter. An anagram of p is a permutation of p, and the function should return an array of starting indices where anagrams of p begin in s.", - examples: [ - { - input: "s = 'cbaebabacd', p = 'abc'", - output: "[0, 6]", - explanation: "The substring 'cba' starting at index 0 and 'bac' starting at index 6 are anagrams of 'abc'.", - }, - { - input: "s = 'abab', p = 'ab'", - output: "[0, 1, 2]", - explanation: "The substring 'ab' starting at indices 0, 1, and 2 are all anagrams of 'ab'.", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - vector findAnagrams(string s, string p) { - vector result; - vector p_count(26, 0), s_count(26, 0); - - if (s.size() < p.size()) return result; - - for (int i = 0; i < p.size(); i++) { - p_count[p[i] - 'a']++; - s_count[s[i] - 'a']++; - } - - if (p_count == s_count) result.push_back(0); - - for (int i = p.size(); i < s.size(); i++) { - s_count[s[i] - 'a']++; - s_count[s[i - p.size()] - 'a']--; - - if (p_count == s_count) result.push_back(i - p.size() + 1); - } - - return result; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public List findAnagrams(String s, String p) { - List result = new ArrayList<>(); - if (s.length() < p.length()) return result; - - int[] p_count = new int[26]; - int[] s_count = new int[26]; - - for (int i = 0; i < p.length(); i++) { - p_count[p.charAt(i) - 'a']++; - s_count[s.charAt(i) - 'a']++; - } - - if (Arrays.equals(p_count, s_count)) result.add(0); - - for (int i = p.length(); i < s.length(); i++) { - s_count[s.charAt(i) - 'a']++; - s_count[s.charAt(i - p.length()) - 'a']--; - - if (Arrays.equals(p_count, s_count)) result.add(i - p.length() + 1); - } - - return result; - } - };`, - - python: ` - from typing import List - from collections import Counter - - class Solution: - def findAnagrams(self, s: str, p: str) -> List[int]: - p_count = Counter(p) - s_count = Counter(s[:len(p)]) - result = [] - - if s_count == p_count: - result.append(0) - - for i in range(len(p), len(s)): - s_count[s[i]] += 1 - s_count[s[i - len(p)]] -= 1 - - if s_count[s[i - len(p)] ] == 0: - del s_count[s[i - len(p)]] - - if s_count == p_count: - result.append(i - len(p) + 1) - - return result - `, - }, - }, - climbingStairs: { - title: "54. Climbing Stairs", - description: - "You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?", - examples: [ - { - input: "n = 2", - output: "2", - explanation: "There are two ways to climb to the top: 1 step + 1 step or 2 steps.", - }, - { - input: "n = 3", - output: "3", - explanation: "There are three ways to climb to the top: 1 step + 1 step + 1 step, 1 step + 2 steps, or 2 steps + 1 step.", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - int climbStairs(int n) { - if (n <= 1) return 1; - int first = 1, second = 2; - for (int i = 3; i <= n; i++) { - int temp = second; - second += first; - first = temp; - } - return second; - } - };`, - - java: ` - class Solution { - public int climbStairs(int n) { - if (n <= 1) return 1; - int first = 1, second = 2; - for (int i = 3; i <= n; i++) { - int temp = second; - second += first; - first = temp; - } - return second; - } - };`, - - python: ` - class Solution: - def climbStairs(self, n: int) -> int: - if n <= 1: - return 1 - first, second = 1, 2 - for i in range(3, n + 1): - first, second = second, first + second - return second - `, - }, - }, -}; - -export default problemsData; +const problemsData = { + twoSum: { + title: "1. Two Sum", + description: + "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.", + examples: [ + { input: "[2,7,11,15], target = 9", output: "[0,1]" }, + { input: "[3,2,4], target = 6", output: "[1,2]" }, + { input: "[3,3], target = 6", output: "[0,1]" }, + ], + solution: { + cpp: ` + class Solution { + public: + vector twoSum(vector& nums, int target) { + unordered_map res; + vector result; + + for(int i = 0; i < nums.size(); i++) { + if(res.find(target - nums[i]) != res.end()) { + result.push_back(i); + result.push_back(res[target - nums[i]]); + break; + } else { + res[nums[i]] = i; + } + } + return result; + } + };`, + java: ` + import java.util.HashMap; + + public class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + + if (map.containsKey(complement)) { + return new int[] { map.get(complement), i }; + } + + map.put(nums[i], i); + } + return new int[] {}; + } + }`, + python: ` + class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + res = {} + + for i, num in enumerate(nums): + complement = target - num + + if complement in res: + return [res[complement], i] + + res[num] = i`, + }, + }, + containerWithMostWater: { + title: "2. Container With Most Water", + description: + "Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). Find two lines that form a container with the maximum area of water.", + examples: [ + { input: "[1,8,6,2,5,4,8,3,7]", output: "49" }, + { input: "[1,1]", output: "1" }, + { input: "[4,3,2,1,4]", output: "16" }, + { input: "[1,2,1]", output: "2" }, + ], + solution: { + cpp: ` + class Solution { + public: + int maxArea(vector& height) { + int current_area = INT_MIN; + int area = 0; + int left = 0, right = height.size() - 1; + while (left < right) { + current_area = min(height[left], height[right]) * (right - left); + if (height[left] < height[right]) left++; + else right--; + area = max(area, current_area); + } + return area; + } + };`, + java: ` + public class Solution { + public int maxArea(int[] height) { + int left = 0, right = height.length - 1; + int maxArea = 0; + + while (left < right) { + int currentArea = Math.min(height[left], height[right]) * (right - left); + maxArea = Math.max(maxArea, currentArea); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return maxArea; + } + }`, + python: ` +class Solution: + def maxArea(self, height: List[int]) -> int: + left, right = 0, len(height) - 1 + max_area = 0 + + while left < right: + current_area = min(height[left], height[right]) * (right - left) + max_area = max(max_area, current_area) + + if height[left] < height[right]: + left += 1 + else: + right -= 1 + + return max_area`, + }, + }, + threeSum: { + title: "3. 3Sum", + description: + "Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.", + examples: [ + { input: "[-1,0,1,2,-1,-4]", output: "[[-1,-1,2],[-1,0,1]]" }, + { input: "[]", output: "[]" }, + { input: "[0]", output: "[]" }, + ], + solution: { + cpp: ` + vector> threeSum(vector& nums) { + vector> res; + if(nums.size() < 3) return res; + sort(nums.begin(), nums.end()); + int n = nums.size(); + for(int i = 0; i < n - 2; i++) { + if(i > 0 && nums[i] == nums[i - 1]) continue; + int j = i + 1, k = n - 1; + while(j < k) { + int s = nums[i] + nums[j] + nums[k]; + if(s < 0) j++; + else if(s > 0) k--; + else { + res.push_back({nums[i], nums[j], nums[k]}); + while(j < k && nums[j] == nums[j + 1]) j++; + while(j < k && nums[k] == nums[k - 1]) k--; + j++, k--; + } + } + } + return res; + } +};`, + java: ` +import java.util.*; +public class Solution { + public List> threeSum(int[] nums) { + List> res = new ArrayList<>(); + if(nums.length < 3) return res; + Arrays.sort(nums); + for(int i = 0; i < nums.length - 2; i++) { + if(i > 0 && nums[i] == nums[i - 1]) continue; + int j = i + 1, k = nums.length - 1; + while(j < k) { + int sum = nums[i] + nums[j] + nums[k]; + if(sum < 0) j++; + else if(sum > 0) k--; + else { + res.add(Arrays.asList(nums[i], nums[j], nums[k])); + while(j < k && nums[j] == nums[j + 1]) j++; + while(j < k && nums[k] == nums[k - 1]) k--; + j++; k--; + } + } + } + return res; + } +};`, + python: ` +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + res = [] + nums.sort() + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + j, k = i + 1, len(nums) - 1 + while j < k: + s = nums[i] + nums[j] + nums[k] + if s < 0: + j += 1 + elif s > 0: + k -= 1 + else: + res.append([nums[i], nums[j], nums[k]]) + while j < k and nums[j] == nums[j + 1]: + j += 1 + while j < k and nums[k] == nums[k - 1]: + k -= 1 + j += 1 + k -= 1 + return res`, + }, + }, + + isValidParentheses: { + title: "4. Valid Parentheses", + description: + "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.", + examples: [ + { input: "(){}", output: "true" }, + { input: "()[]{}", output: "true" }, + { input: "(]", output: "false" }, + { input: "([)]", output: "false" }, + { input: "{[]}", output: "true" }, + ], + solution: { + cpp: ` +class Solution { +public: + bool isValid(string s) { + stack stk; + for(char c : s) { + if(c == '{') stk.push('}'); + else if(c == '[') stk.push(']'); + else if(c == '(') stk.push(')'); + else if(stk.empty() || stk.top() != c) return false; + else stk.pop(); + } + return stk.empty(); + } +};`, + java: ` +import java.util.Stack; + +public class Solution { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + for (char c : s.toCharArray()) { + if (c == '(') stack.push(')'); + else if (c == '{') stack.push('}'); + else if (c == '[') stack.push(']'); + else if (stack.isEmpty() || stack.pop() != c) return false; + } + return stack.isEmpty(); + } +};`, + python: ` +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + mapping = {')': '(', '}': '{', ']': '['} + for char in s: + if char in mapping: + top_element = stack.pop() if stack else '#' + if mapping[char] != top_element: + return False + else: + stack.append(char) + return not stack`, + }, + }, + + mergeTwoLists: { + title: "5. Merge Two Sorted Lists", + description: + "Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.", + examples: [ + { input: "[1,2,4], [1,3,4]", output: "[1,1,2,3,4,4]" }, + { input: "[], []", output: "[]" }, + { input: "[], [0]", output: "[0]" }, + ], + solution: { + cpp: ` +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if (!l1) return l2; + if (!l2) return l1; + if (l1->val < l2->val) { + l1->next = mergeTwoLists(l1->next, l2); + return l1; + } else { + l2->next = mergeTwoLists(l1, l2->next); + return l2; + } + } +};`, + java: ` +public class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) return l2; + if (l2 == null) return l1; + if (l1.val < l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = mergeTwoLists(l1, l2.next); + return l2; + } + } +};`, + python: ` +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + if not l1: + return l2 + if not l2: + return l1 + if l1.val < l2.val: + l1.next = self.mergeTwoLists(l1.next, l2) + return l1 + else: + l2.next = self.mergeTwoLists(l1, l2.next) + return l2`, + }, + }, + + nextPermutation: { + title: "6. Next Permutation", + description: + "Implement next permutation which rearranges numbers into the lexicographically next greater permutation of numbers.", + examples: [ + { input: "[1,2,3]", output: "[1,3,2]" }, + { input: "[3,2,1]", output: "[1,2,3]" }, + { input: "[1,5]", output: "[5,1]" }, + { input: "[5]", output: "[5]" }, + ], + solution: { + cpp: ` +class Solution { +public: + void nextPermutation(vector& nums) { + next_permutation(nums.begin(), nums.end()); + } +};`, + java: ` +import java.util.Arrays; +public class Solution { + public void nextPermutation(int[] nums) { + int i = nums.length - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) i--; + if (i >= 0) { + int j = nums.length - 1; + while (nums[j] <= nums[i]) j--; + swap(nums, i, j); + } + reverse(nums, i + 1); + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + + private void reverse(int[] nums, int start) { + int i = start, j = nums.length - 1; + while (i < j) { + swap(nums, i++, j--); + } + } +};`, + python: ` +class Solution: + def nextPermutation(self, nums: List[int]) -> None: + i = len(nums) - 2 + while i >= 0 and nums[i] >= nums[i + 1]: + i -= 1 + if i >= 0: + j = len(nums) - 1 + while nums[j] <= nums[i]: + j -= 1 + nums[i], nums[j] = nums[j], nums[i] + nums[i + 1:] = nums[i + 1:][::-1]`, + }, + }, + searchInsert: { + title: "7. Search Insert Position", + description: + "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.", + examples: [ + { input: "[1,3,5,6], target=5", output: "2" }, + { input: "[1,3], target=0", output: "0" }, + { input: "[3], target=4", output: "1" }, + ], + solution: { + cpp: ` +class Solution { +public: + int searchInsert(vector& nums, int target) { + int low = 0, high = nums.size() - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) return mid; + else if (nums[mid] > target) high = mid - 1; + else low = mid + 1; + } + return low; + } +};`, + java: ` +class Solution { + public int searchInsert(int[] nums, int target) { + int low = 0, high = nums.length - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) return mid; + else if (nums[mid] > target) high = mid - 1; + else low = mid + 1; + } + return low; + } +};`, + python: ` +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + low, high = 0, len(nums) - 1 + while low <= high: + mid = (low + high) // 2 + if nums[mid] == target: + return mid + elif nums[mid] > target: + high = mid - 1 + else: + low = mid + 1 + return low`, + }, + }, + + isValidSudoku: { + title: "8. Valid Sudoku", + description: + "Determine if a 9 x 9 Sudoku board is valid by checking that each row, column, and 3 x 3 sub-box contains the digits 1-9 without repetition. The board may be partially filled, with empty cells represented by the character '.'. A board is considered valid if it adheres to these rules.", + examples: [ + { + input: `[['5','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','.'],['.','9','8','.','.','.','.','6','.'],['8','.','.','.','6','.','.','.','3'],['4','.','.','8','.','3','.','.','1'],['7','.','.','.','2','.','.','.','6'],['.','6','.','.','.','.','2','8','.'],['.','.' ,'.' ,'4' ,'1' ,'9' ,'.' ,'.' ,'5'],['.' ,'.' ,'.' ,'.' ,'8' ,'.' ,'.' ,'7' ,'9']]`, + output: "true", + }, + { + input: `[['8','3','.','.','7','.','.','.','.'],['6','.','.','1','9','5','.','.','.'],['.','9','8','.','.','.','.','6', '.'],['8', '.', '.', '.', '6', '.', '.', '.', '3'],['4', '.', '.', '8', '.', '3', '.', '.', '1'],['7', '.', '.', '.', '2', '.', '.', '.', '6'],['.', '6', '.', '.', '.', '.', '2', '8', '.'],['.', '.', '.', '4', '1', '9', '.', '.', '5'],['.', '.', '.', '.', '8', '.', '.', '7', '9']]`, + output: "false", + }, + ], + solution: { + cpp: ` + class Solution { + public: + bool isValidSudoku(vector>& board) { + vector> rows(9), cols(9), blocks(9); + for(int i=0; i<9; i++) { + for(int j=0; j<9; j++) { + if(board[i][j]=='.') continue; + int curr = board[i][j]-'0'; + if(rows[i].count(curr) || cols[j].count(curr) || blocks[(i/3)*3+j/3].count(curr)) return false; + rows[i].insert(curr); + cols[j].insert(curr); + blocks[(i/3)*3+j/3].insert(curr); + } + } + return true; + } + };`, + java: ` + class Solution { + public boolean isValidSudoku(char[][] board) { + HashSet seen = new HashSet<>(); + for (int r = 0; r < 9; r++) { + for (int c = 0; c < 9; c++) { + if (board[r][c] != '.') { + String num = String.valueOf(board[r][c]); + if (!seen.add(num + " in row " + r) || !seen.add(num + " in column " + c) || + !seen.add(num + " in block " + r / 3 + "-" + c / 3)) return false; + } + } + } + return true; + } + };`, + python: ` + class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + rows, cols, blocks = [set() for _ in range(9)], [set() for _ in range(9)], [set() for _ in range(9)] + for i in range(9): + for j in range(9): + if board[i][j] == '.': continue + curr = board[i][j] + if (curr in rows[i] or curr in cols[j] or curr in blocks[(i//3)*3+j//3]): + return False + rows[i].add(curr) + cols[j].add(curr) + blocks[(i//3)*3+j//3].add(curr) + return True`, + }, + }, + + firstMissingPositive: { + title: "9. First Missing Positive", + description: + "Given an unsorted integer array nums, return the smallest missing positive integer.", + examples: [ + { input: "[1,2,0]", output: "3" }, + { input: "[3,4,-1,1]", output: "2" }, + { input: "[7,8,9,11,12]", output: "1" }, + ], + solution: { + cpp: ` + class Solution { + public: + int firstMissingPositive(vector& nums) { + int n = nums.size(); + vector present(n + 1, false); + for (int num : nums) { + if (num > 0 && num <= n) present[num] = true; + } + for (int i = 1; i <= n; i++) { + if (!present[i]) return i; + } + return n + 1; + } + };`, + java: ` + class Solution { + public int firstMissingPositive(int[] nums) { + int n = nums.length; + boolean[] present = new boolean[n + 1]; + for (int num : nums) { + if (num > 0 && num <= n) present[num] = true; + } + for (int i = 1; i <= n; i++) { + if (!present[i]) return i; + } + return n + 1; + } + };`, + python: ` + class Solution: + def firstMissingPositive(self, nums: List[int]) -> int: + n = len(nums) + present = [False] * (n + 1) + for num in nums: + if 1 <= num <= n: + present[num] = True + for i in range(1, n + 1): + if not present[i]: return i + return n + 1`, + }, + }, + + maxSubArray: { + title: "10. Maximum Subarray", + description: + "Given an integer array nums, find the contiguous subarray which has the largest sum and return its sum.", + examples: [ + { input: "[-2,1,-3,4,-1,2,1,-5,4]", output: "6" }, + { input: "[1]", output: "1" }, + { input: "[5,4,-1,7,8]", output: "23" }, + ], + solution: { + cpp: ` + class Solution { + public: + int maxSubArray(vector& nums) { + int sum = nums[0], max_sum = nums[0]; + for (int i = 1; i < nums.size(); i++) { + sum = max(nums[i], sum + nums[i]); + max_sum = max(sum, max_sum); + } + return max_sum; + } + };`, + java: ` + class Solution { + public int maxSubArray(int[] nums) { + int maxSum = nums[0], currSum = nums[0]; + for (int i = 1; i < nums.length; i++) { + currSum = Math.max(nums[i], currSum + nums[i]); + maxSum = Math.max(maxSum, currSum); + } + return maxSum; + } + };`, + python: ` + class Solution: + def maxSubArray(self, nums: List[int]) -> int: + max_sum = nums[0] + curr_sum = nums[0] + for num in nums[1:]: + curr_sum = max(num, curr_sum + num) + max_sum = max(max_sum, curr_sum) + return max_sum`, + }, + }, + mySqrt: { + title: "11. Sqrt(x)", + description: + "Given a non-negative integer x, compute and return the square root of x.", + examples: [ + { input: "4", output: "2" }, + { input: "8", output: "2" }, + { input: "16", output: "4" }, + ], + solution: { + cpp: ` +class Solution { +public: + int mySqrt(int x) { + if (x < 2) return x; + long long int res; + long long int start = 1, end = x / 2; + while (start <= end) { + long long int mid = start + (end - start) / 2; + if (mid * mid == x) return mid; + else if (mid * mid < x) { + start = mid + 1; res = mid; + } else end = mid - 1; + } + return res; + } +};`, + java: ` +class Solution { + public int mySqrt(int x) { + if (x < 2) return x; + long res = 0; + long start = 1, end = x / 2; + while (start <= end) { + long mid = start + (end - start) / 2; + if (mid * mid == x) return (int) mid; + else if (mid * mid < x) { + start = mid + 1; res = mid; + } else end = mid - 1; + } + return (int) res; + } +};`, + python: ` +class Solution: + def mySqrt(self, x: int) -> int: + if x < 2: return x + start, end, res = 1, x // 2, 0 + while start <= end: + mid = start + (end - start) // 2 + if mid * mid == x: return mid + elif mid * mid < x: + start = mid + 1; res = mid + else: end = mid - 1 + return res + `, + }, + }, + + searchMatrix: { + title: "12. Search a 2D Matrix", + description: + "Write an efficient algorithm that searches for a value in an m x n matrix.", + examples: [ + { + input: "[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3", + output: "true", + }, + { input: "[[1,3,5],[10],[23]], target = 13", output: "false" }, + ], + solution: { + cpp: ` +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + if (!matrix.size()) return false; + int n = matrix.size(), m = matrix[0].size(), low = 0, high = (n * m) - 1; + while (low <= high) { + int mid = (low + (high - low) / 2); + if (matrix[mid / m][mid % m] == target) return true; + if (matrix[mid / m][mid % m] < target) low = mid + 1; + else high = mid - 1; + } + return false; + } +};`, + java: ` +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix.length == 0) return false; + int n = matrix.length, m = matrix[0].length, low = 0, high = (n * m) - 1; + while (low <= high) { + int mid = (low + (high - low) / 2); + if (matrix[mid / m][mid % m] == target) return true; + if (matrix[mid / m][mid % m] < target) low = mid + 1; + else high = mid - 1; + } + return false; + } +};`, + python: ` +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + if not matrix: return False + n, m = len(matrix), len(matrix[0]) + low, high = 0, (n * m) - 1 + while low <= high: + mid = (low + (high - low) // 2) + if matrix[mid // m][mid % m] == target: return True + if matrix[mid // m][mid % m] < target: low = mid + 1 + else: high = mid - 1 + return False + `, + }, + }, + + deleteDuplicates: { + title: "13. Remove Duplicates from Sorted List", + description: + "Given the head of a sorted linked list, delete all duplicates such that each element appears only once.", + examples: [ + { input: "[1,1,2]", output: "[1,2]" }, + { input: "[1,1,2,3,3]", output: "[1,2,3]" }, + ], + solution: { + cpp: ` +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if(head == NULL) return NULL; + ListNode* curr = head; + while(curr->next) { + if(curr->val == curr->next->val) + curr->next = curr->next->next; + else curr = curr->next; + } + return head; + } +};`, + java: ` +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if (head == null) return null; + ListNode curr = head; + while (curr.next != null) { + if (curr.val == curr.next.val) + curr.next = curr.next.next; + else curr = curr.next; + } + return head; + } +};`, + python: ` +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if head is None: return None + curr = head + while curr.next: + if curr.val == curr.next.val: + curr.next = curr.next.next + else: curr = curr.next + return head + `, + }, + }, + + mergeTwoSortedLists: { + title: "14. Merge Two Sorted Lists", + description: + "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order.", + examples: [ + { + input: "[1,2,4,0,0,0], m = 3, nums2 = [2,5,6], n = 3", + output: "[1,2,2,3,5,6]", + }, + { input: "[1], m = 1, nums2 = [], n = 0", output: "[1]" }, + ], + solution: { + cpp: ` +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int i = 0; + while (i < n) { + nums1[m++] = nums2[i]; + i++; + } + sort(nums1.begin(), nums1.end()); + } +};`, + java: ` +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = 0; + while (i < n) { + nums1[m++] = nums2[i]; + i++; + } + Arrays.sort(nums1); + } +};`, + python: ` +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + i = 0 + while i < n: + nums1[m] = nums2[i] + m += 1 + i += 1 + nums1.sort() + `, + }, + }, + inorderTraversal: { + title: "15. Binary Tree Inorder Traversal", + description: + "Given the root of a binary tree, return the inorder traversal of its nodes' values.", + examples: [ + { input: "[1,null,2,3]", output: "[1,3,2]" }, + { input: "[]", output: "[]" }, + { input: "[1]", output: "[1]" }, + ], + solution: { + cpp: ` +class Solution { +public: + vector ans; + vector inorderTraversal(TreeNode* root) { + if (root == NULL) return ans; + inorderTraversal(root->left); + ans.push_back(root->val); + inorderTraversal(root->right); + return ans; + } +};`, + java: ` +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + inorderTraversalHelper(root, ans); + return ans; + } + private void inorderTraversalHelper(TreeNode root, List ans) { + if (root == null) return; + inorderTraversalHelper(root.left, ans); + ans.add(root.val); + inorderTraversalHelper(root.right, ans); + } +};`, + python: ` +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + ans = [] + def inorder(node): + if not node: return + inorder(node.left) + ans.append(node.val) + inorder(node.right) + inorder(root) + return ans + `, + }, + }, + + isSymmetric: { + title: "16. Symmetric Tree", + description: + "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).", + examples: [ + { input: "[1,2,2,3,4,4,3]", output: "true" }, + { input: "[1,2,2,null,3,null,3]", output: "false" }, + ], + solution: { + cpp: ` +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (root == NULL) return true; + return isSymmetricTest(root->left, root->right); + } + bool isSymmetricTest(TreeNode* p, TreeNode* q) { + if (p == NULL && q == NULL) return true; + else if (p == NULL || q == NULL) return false; + else if (p->val != q->val) return false; + return isSymmetricTest(p->left, q->right) && isSymmetricTest(p->right, q->left); + } +};`, + java: ` +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null) return true; + return isSymmetricTest(root.left, root.right); + } + private boolean isSymmetricTest(TreeNode p, TreeNode q) { + if (p == null && q == null) return true; + else if (p == null || q == null) return false; + else if (p.val != q.val) return false; + return isSymmetricTest(p.left, q.right) && isSymmetricTest(p.right, q.left); + } +};`, + python: ` +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if not root: return True + return self.isSymmetricTest(root.left, root.right) + def isSymmetricTest(self, p: TreeNode, q: TreeNode) -> bool: + if not p and not q: return True + if not p or not q: return False + if p.val != q.val: return False + return self.isSymmetricTest(p.left, q.right) and self.isSymmetricTest(p.right, q.left) + `, + }, + }, + + levelOrderTraversal: { + title: "17. Binary Tree Level Order Traversal", + description: + "Given the root of a binary tree, return the level order traversal of its nodes' values.", + examples: [ + { input: "[3,9,20,null,null,15,7]", output: "[[3],[9,20],[15,7]]" }, + { input: "[1]", output: "[[1]]" }, + { input: "[]", output: "[]" }, + ], + solution: { + cpp: ` +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> ans; + if (root == NULL) return ans; + + queue q; + q.push(root); + while (!q.empty()) { + int size = q.size(); + vector level; + for (int i = 0; i < size; i++) { + TreeNode* node = q.front(); + q.pop(); + if (node->left != NULL) q.push(node->left); + if (node->right != NULL) q.push(node->right); + level.push_back(node->val); + } + ans.push_back(level); + } + return ans; + } +};`, + java: ` +class Solution { + public List> levelOrder(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) return ans; + + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + int size = q.size(); + List level = new ArrayList<>(); + for (int i = 0; i < size; i++) { + TreeNode node = q.poll(); + if (node.left != null) q.offer(node.left); + if (node.right != null) q.offer(node.right); + level.add(node.val); + } + ans.add(level); + } + return ans; + } +};`, + python: ` +class Solution: + def levelOrder(self, root: TreeNode) -> List[List[int]]: + ans = [] + if not root: return ans + q = collections.deque([root]) + while q: + size = len(q) + level = [] + for _ in range(size): + node = q.popleft() + if node.left: q.append(node.left) + if node.right: q.append(node.right) + level.append(node.val) + ans.append(level) + return ans + `, + }, + }, + + maxDepthBinaryTree: { + title: "18. Maximum Depth of Binary Tree", + description: "Given the root of a binary tree, return its maximum depth.", + examples: [ + { input: "[3,9,20,null,null,15,7]", output: "3" }, + { input: "[1,null,2]", output: "2" }, + { input: "[]", output: "0" }, + ], + solution: { + cpp: ` +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == NULL) return 0; + int leftDepth = maxDepth(root->left); + int rightDepth = maxDepth(root->right); + return max(leftDepth, rightDepth) + 1; + } +};`, + java: ` +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + int leftDepth = maxDepth(root.left); + int rightDepth = maxDepth(root.right); + return Math.max(leftDepth, rightDepth) + 1; + } +};`, + python: ` +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if not root: return 0 + leftDepth = self.maxDepth(root.left) + rightDepth = self.maxDepth(root.right) + return max(leftDepth, rightDepth) + 1 + `, + }, + }, + hasPathSum: { + title: "19. Path Sum", + description: + "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.", + examples: [ + { input: "[5,4,8,11,null,13,4], targetSum = 22", output: "true" }, + { input: "[1], targetSum = 5", output: "false" }, + ], + solution: { + cpp: ` +class Solution { +public: + bool hasPathSum(TreeNode* root, int sum) { + if (root == NULL) + return false; + + if (root->left == NULL && root->right == NULL) + return sum == root->val; + + return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); + } +};`, + java: ` +class Solution { + public boolean hasPathSum(TreeNode root, int sum) { + if (root == null) + return false; + + if (root.left == null && root.right == null) + return sum == root.val; + + return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); + } +};`, + python: ` +class Solution: + def hasPathSum(self, root: TreeNode, sum: int) -> bool: + if not root: + return False + + if not root.left and not root.right: + return sum == root.val + + return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) + `, + }, + }, + + generatePascalTriangle: { + title: "20. Pascal's Triangle", + description: + "Given an integer numRows, return a string that concatenates the elements of the first numRows of Pascal's triangle in a single line.", + examples: [ + { input: "5", output: [[1], [1, 1], [1, 2, 1], [1, 3, 3], [1, 4, 6]] }, + { input: "1", output: [[1]] }, + ], + solution: { + cpp: ` +class Solution { +public: + vector> generate(int numRows) { + vector> res(numRows); + + for (int i = 0; i < numRows; i++) { + res[i].resize(i + 1); // number of rows + res[i][0] = res[i][i] = 1; + + for (int j = 1; j < i; j++) { + res[i][j] = res[i - 1][j - 1] + res[i - 1][j]; + } + } + return res; + } +};`, + java: ` +class Solution { + public List> generate(int numRows) { + List> res = new ArrayList<>(); + + for (int i = 0; i < numRows; i++) { + List row = new ArrayList<>(Collections.nCopies(i + 1, 0)); + row.set(0, 1); + row.set(i, 1); + + for (int j = 1; j < i; j++) { + row.set(j, res.get(i - 1).get(j - 1) + res.get(i - 1).get(j)); + } + res.add(row); + } + return res; + } +};`, + python: ` +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + res = [] + + for i in range(numRows): + row = [1] * (i + 1) + for j in range(1, i): + row[j] = res[i - 1][j - 1] + res[i - 1][j] + res.append(row) + + return res + `, + }, + }, + + maxProfit: { + title: "21. Best Time to Buy and Sell Stock", + description: + "You are given an array prices where prices[i] represents the price of a given stock on the i-th day.You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.Return the maximum profit you can achieve from this transaction. If no profit can be made, return 0.", + examples: [ + { input: "[7,1,5,3,6,4]", output: "5" }, + { input: "[7,6,4,3,1]", output: "0" }, + ], + solution: { + cpp: ` +class Solution { +public: + int maxProfit(vector& prices) { + int minm = INT_MAX; + int result = 0; + + for (int i = 0; i < prices.size(); i++) { + minm = min(minm , prices[i]); + result = max(prices[i] - minm , result); + } + return result; + } +};`, + java: ` +class Solution { + public int maxProfit(int[] prices) { + int minm = Integer.MAX_VALUE; + int result = 0; + + for (int price : prices) { + minm = Math.min(minm, price); + result = Math.max(result, price - minm); + } + return result; + } +};`, + python: ` +class Solution: + def maxProfit(self, prices: List[int]) -> int: + minm = float('inf') + result = 0 + + for price in prices: + minm = min(minm, price) + result = max(result, price - minm) + + return result + `, + }, + }, + + hasCycle: { + title: "22. Linked List Cycle", + description: + "Given the head of a linked list, determine if the linked list has a cycle in it.", + examples: [ + { input: "[3,2,0,-4], pos=1", output: "true" }, + { input: "[1,2], pos=0", output: "true" }, + { input: "[1], pos=-1", output: "false" }, + ], + solution: { + cpp: ` +class Solution { +public: + bool hasCycle(ListNode *head) { + if (head == NULL || head->next == NULL) + return false; + + ListNode *slow = head; + ListNode *fast = head; + + while (fast->next != NULL && fast->next->next != NULL) { + fast = fast->next->next; + slow = slow->next; + + if (fast == slow) + return true; + } + + return false; + } +};`, + java: ` +class Solution { + public boolean hasCycle(ListNode head) { + if (head == null || head.next == null) + return false; + + ListNode slow = head; + ListNode fast = head; + + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) + return true; + } + + return false; + } +};`, + python: ` +class Solution: + def hasCycle(self, head: ListNode) -> bool: + if not head or not head.next: + return False + + slow = head + fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + if slow == fast: + return True + + return False + `, + }, + }, + preorderTraversal: { + title: "23. Binary Tree Preorder Traversal", + description: + "Given the root of a binary tree, return the preorder traversal of its nodes' values.", + examples: [ + { input: "[1,null,2,3]", output: "[1,2,3]" }, + { input: "[]", output: "[]" }, + { input: "[1]", output: "[1]" }, + { input: "[1,2]", output: "[1,2]" }, + { input: "[1,null,2]", output: "[1,2]" }, + ], + solution: { + cpp: ` + class Solution { + public: + vector ans; + vector preorderTraversal(TreeNode* root) { + if (root == NULL) + return ans; + + ans.push_back(root->val); + preorderTraversal(root->left); + preorderTraversal(root->right); + + return ans; + } + };`, + + java: ` + import java.util.*; + + class Solution { + public List preorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + preorder(root, result); + return result; + } + + private void preorder(TreeNode node, List result) { + if (node == null) return; + result.add(node.val); + preorder(node.left, result); + preorder(node.right, result); + } + };`, + + python: ` + class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + result = [] + self.preorder(root, result) + return result + + def preorder(self, node: TreeNode, result: List[int]) -> None: + if not node: + return + result.append(node.val) + self.preorder(node.left, result) + self.preorder(node.right, result) + `, + }, + }, + + postorderTraversal: { + title: "24. Binary Tree Postorder Traversal", + description: + "Given the root of a binary tree, return the postorder traversal of its nodes' values.", + examples: [ + { input: "[1,null,2,3]", output: "[3,2,1]" }, + { input: "[]", output: "[]" }, + { input: "[1]", output: "[1]" }, + { input: "[1,2]", output: "[2,1]" }, + { input: "[1,null,2]", output: "[2,1]" }, + ], + solution: { + cpp: ` + class Solution { + public: + vector ans; + vector postorderTraversal(TreeNode* root) { + if (root == NULL) + return ans; + + postorderTraversal(root->left); + postorderTraversal(root->right); + ans.push_back(root->val); + + return ans; + } + };`, + + java: ` + import java.util.*; + + class Solution { + public List postorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + postorder(root, result); + return result; + } + + private void postorder(TreeNode node, List result) { + if (node == null) return; + postorder(node.left, result); + postorder(node.right, result); + result.add(node.val); + } + };`, + + python: ` + class Solution: + def postorderTraversal(self, root: TreeNode) -> List[int]: + result = [] + self.postorder(root, result) + return result + + def postorder(self, node: TreeNode, result: List[int]) -> None: + if not node: + return + self.postorder(node.left, result) + self.postorder(node.right, result) + result.append(node.val) + `, + }, + }, + + removeElements: { + title: "25. Remove Linked List Elements", + description: + "Given the head of a linked list and an integer val, remove all the nodes of the linked list that have Node.val equal to val, and return the new head.", + examples: [ + { input: "[1,2,6,3,4,5,6], val=6", output: "[1,2,3,4,5]" }, + { input: "[], val=1", output: "[]" }, + { input: "[7,7,7,7], val=7", output: "[]" }, + ], + solution: { + cpp: ` + class Solution { + public: + ListNode* removeElements(ListNode* head, int val) { + if (head == NULL) + return head; + if (head->val == val) + return removeElements(head->next, val); + head->next = removeElements(head->next, val); + return head; + } + };`, + + java: ` + class Solution { + public ListNode removeElements(ListNode head, int val) { + if (head == null) return null; + if (head.val == val) return removeElements(head.next, val); + head.next = removeElements(head.next, val); + return head; + } + };`, + + python: ` + class Solution: + def removeElements(self, head: ListNode, val: int) -> ListNode: + if not head: + return None + if head.val == val: + return self.removeElements(head.next, val) + head.next = self.removeElements(head.next, val) + return head + `, + }, + }, + + reverseList: { + title: "26. Reverse Linked List", + description: + "Given the head of a singly linked list, reverse the list, and return the reversed list.", + examples: [ + { input: "[1,2,3,4,5]", output: "[5,4,3,2,1]" }, + { input: "[1,2]", output: "[2,1]" }, + { input: "[]", output: "[]" }, + ], + solution: { + cpp: ` + class Solution { + public: + ListNode* reverseList(ListNode* head) { + vector res; + ListNode* temp = head; + while (temp) { + res.push_back(temp->val); + temp = temp->next; + } + + temp = head; + for (int i = res.size() - 1; i >= 0; i--) { + temp->val = res[i]; + temp = temp->next; + } + return head; + } + };`, + + java: ` + class Solution { + public ListNode reverseList(ListNode head) { + List values = new ArrayList<>(); + ListNode temp = head; + while (temp != null) { + values.add(temp.val); + temp = temp.next; + } + + temp = head; + for (int i = values.size() - 1; i >= 0; i--) { + temp.val = values.get(i); + temp = temp.next; + } + + return head; + } + };`, + + python: ` + class Solution: + def reverseList(self, head: ListNode) -> ListNode: + values = [] + current = head + while current: + values.append(current.val) + current = current.next + + current = head + for val in reversed(values): + current.val = val + current = current.next + + return head + `, + }, + }, + + findKthLargest: { + title: "27. Kth Largest Element in an Array", + description: + "Given an integer array nums and an integer k, return the kth largest element in the array.", + examples: [ + { input: "[3,2,1,5,6,4], k = 2", output: "5" }, + { input: "[3,2,3,1,2,4,5,5,6], k = 4", output: "4" }, + ], + solution: { + cpp: ` + class Solution { + public: + int findKthLargest(vector& nums, int k) { + sort(nums.begin(), nums.end()); + return nums[nums.size() - k]; + } + };`, + + java: ` + import java.util.*; + + class Solution { + public int findKthLargest(int[] nums, int k) { + Arrays.sort(nums); + return nums[nums.length - k]; + } + };`, + + python: ` + class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + nums.sort() + return nums[-k] + `, + }, + }, + + containsDuplicate: { + title: "28. Contains Duplicate", + description: + "Given an integer array nums, return true if any value appears at least twice in the array.", + examples: [ + { input: "[1,2,3,1]", output: "true" }, + { input: "[1,2,3,4]", output: "false" }, + { input: "[1,1,1,3,3,4,3,2,4,2]", output: "true" }, + ], + solution: { + cpp: ` + class Solution { + public: + bool containsDuplicate(vector& nums) { + return (nums.size() > unordered_set(nums.begin(), nums.end()).size()); + } + };`, + + java: ` + import java.util.*; + + class Solution { + public boolean containsDuplicate(int[] nums) { + Set numSet = new HashSet<>(); + for (int num : nums) { + if (!numSet.add(num)) return true; + } + return false; + } + };`, + + python: ` + class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) > len(set(nums)) + `, + }, + }, + + invertBinaryTree: { + title: "29. Invert Binary Tree", + description: + "Given the root of a binary tree, invert the tree and return its root.", + examples: [ + { input: "[4,2,7,1,3,6,9]", output: "[4,7,2,9,6,3,1]" }, + { input: "[2,1,3]", output: "[2,3,1]" }, + { input: "[]", output: "[]" }, + ], + solution: { + cpp: ` + class Solution { + public: + TreeNode* invertTree(TreeNode* root) { + if (root) { + invertTree(root->left); + invertTree(root->right); + swap(root->left, root->right); + } + return root; + } + };`, + + java: ` + class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) return null; + TreeNode left = invertTree(root.left); + TreeNode right = invertTree(root.right); + root.left = right; + root.right = left; + return root; + } + };`, + + python: ` + class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if root is None: + return None + root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) + return root + `, + }, + }, + + MyQueue: { + title: "30. Implement Queue using Stacks", + description: + "Implement a first-in-first-out (FIFO) queue using only two stacks.", + examples: [ + { + input: `["MyQueue", "push", "push", "peek", "pop", "empty"]`, + output: `[null,null,null,1,1,false]`, + }, + ], + solution: { + cpp: ` + class MyQueue { + public: + stack s1, s2; + + MyQueue() {} + + void push(int x) { + while (!s1.empty()) { + s2.push(s1.top()); + s1.pop(); + } + s2.push(x); + while (!s2.empty()) { + s1.push(s2.top()); + s2.pop(); + } + } + + int pop() { + int curr = s1.top(); + s1.pop(); + return curr; + } + + int peek() { + return s1.top(); + } + + bool empty() { + return s1.empty(); + } + };`, + + java: ` + import java.util.Stack; + + class MyQueue { + private Stack s1; + private Stack s2; + + public MyQueue() { + s1 = new Stack<>(); + s2 = new Stack<>(); + } + + public void push(int x) { + while (!s1.isEmpty()) { + s2.push(s1.pop()); + } + s2.push(x); + while (!s2.isEmpty()) { + s1.push(s2.pop()); + } + } + + public int pop() { + return s1.pop(); + } + + public int peek() { + return s1.peek(); + } + + public boolean empty() { + return s1.isEmpty(); + } + };`, + + python: ` + class MyQueue: + + def __init__(self): + self.s1 = [] + self.s2 = [] + + def push(self, x: int) -> None: + while self.s1: + self.s2.append(self.s1.pop()) + self.s2.append(x) + while self.s2: + self.s1.append(self.s2.pop()) + + def pop(self) -> int: + return self.s1.pop() + + def peek(self) -> int: + return self.s1[-1] + + def empty(self) -> bool: + return not self.s1 + `, + }, + }, + + isAnagram: { + title: "31. Valid Anagram", + description: + "Given two strings s and t, return true if t is an anagram of s, and false otherwise.", + examples: [ + { input: "anagram, nagaram", output: "true" }, + { input: "rat, car", output: "false" }, + ], + solution: { + cpp: ` + class Solution { + public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) + return false; + + int count[26] = {0}; + for (char ch : s) + count[ch - 'a']++; + + for (char ch : t) + count[ch - 'a']--; + + for (int i = 0; i < 26; i++) { + if (count[i] != 0) + return false; + } + + return true; + } + };`, + + java: ` + class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) return false; + int[] count = new int[26]; + for (char c : s.toCharArray()) count[c - 'a']++; + for (char c : t.toCharArray()) { + if (--count[c - 'a'] < 0) return false; + } + return true; + } + };`, + + python: ` + class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + count = [0] * 26 + for ch in s: + count[ord(ch) - ord('a')] += 1 + for ch in t: + count[ord(ch) - ord('a')] -= 1 + return all(c == 0 for c in count) + `, + }, + }, + + missingNumber: { + title: "32. Missing Number", + description: + "Given an array nums containing n distinct numbers in the range [0,n], return the only number in the range that is missing from the array.", + examples: [ + { input: "[3, 0, 1]", output: "2" }, + { input: "[0, 1]", output: "2" }, + ], + solution: { + cpp: ` + class Solution { + public: + int missingNumber(vector& nums) { + int sum = 0; + int n = nums.size(); + + for (int i = 0; i < n; i++) { + sum += nums[i]; + } + + return (n * (n + 1) / 2 - sum); + } + };`, + + java: ` + class Solution { + public int missingNumber(int[] nums) { + int sum = 0, n = nums.length; + for (int num : nums) { + sum += num; + } + return n * (n + 1) / 2 - sum; + } + };`, + + python: ` + class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + return n * (n + 1) // 2 - sum(nums) + `, + }, + }, + + guessNumber: { + title: "33. Guess Number Higher or Lower", + description: + "You are playing a Guess Game where you have to guess a number between 1 and n. Each time you guess wrong, the system will tell you whether the actual number is higher or lower.", + examples: [ + { input: "n=10, pick=6", output: "6" }, + { input: "n=1, pick=1", output: "1" }, + { input: "n=2, pick=2", output: "2" }, + ], + solution: { + cpp: ` + class Solution { + public: + int guessNumber(int n) { + int start = 1; + int end = n; + + while (start <= end) { + int mid = start + (end - start) / 2; + + if (guess(mid) == 0) + return mid; + else if (guess(mid) < 0) + end = mid - 1; + else + start = mid + 1; + } + + return -1; + } + };`, + + java: ` + class Solution extends GuessGame { + public int guessNumber(int n) { + int start = 1, end = n; + + while (start <= end) { + int mid = start + (end - start) / 2; + int result = guess(mid); + if (result == 0) return mid; + else if (result < 0) end = mid - 1; + else start = mid + 1; + } + + return -1; + } + };`, + + python: ` + class Solution: + def guessNumber(self, n: int) -> int: + start, end = 1, n + while start <= end: + mid = (start + end) // 2 + res = guess(mid) + if res == 0: + return mid + elif res < 0: + end = mid - 1 + else: + start = mid + 1 + `, + }, + }, + + intersect: { + title: "34. Intersection of Two Arrays II", + description: + "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays, and you may return the result in any order.", + examples: [ + { input: "[1, 2, 2, 1], [2, 2]", output: "[2, 2]" }, + { input: "[4, 9, 5], [9, 4, 9, 8, 4]", output: "[4, 9]" }, + ], + solution: { + cpp: ` + class Solution { + public: + vector intersect(vector& nums1, vector& nums2) { + vector ans; + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + + int i = 0, j = 0; + while (i < nums1.size() && j < nums2.size()) { + if (nums1[i] < nums2[j]) { + i++; + } else if (nums1[i] > nums2[j]) { + j++; + } else { + ans.push_back(nums1[i]); + i++; + j++; + } + } + return ans; + } + };`, + + java: ` + import java.util.Arrays; + import java.util.ArrayList; + + class Solution { + public int[] intersect(int[] nums1, int[] nums2) { + Arrays.sort(nums1); + Arrays.sort(nums2); + ArrayList result = new ArrayList<>(); + + int i = 0, j = 0; + while (i < nums1.length && j < nums2.length) { + if (nums1[i] < nums2[j]) { + i++; + } else if (nums1[i] > nums2[j]) { + j++; + } else { + result.add(nums1[i]); + i++; + j++; + } + } + + return result.stream().mapToInt(k -> k).toArray(); + } + };`, + + python: ` + class Solution: + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + nums1.sort() + nums2.sort() + result = [] + i = j = 0 + while i < len(nums1) and j < len(nums2): + if nums1[i] < nums2[j]: + i += 1 + elif nums1[i] > nums2[j]: + j += 1 + else: + result.append(nums1[i]) + i += 1 + j += 1 + return result + `, + }, + }, + + runningSum: { + title: "35. Running Sum of 1d Array", + description: "Given an array nums, return the running sum of nums.", + examples: [ + { input: "[1, 2, 3, 4]", output: "[1, 3, 6, 10]" }, + { input: "[5]", output: "[5]" }, + ], + solution: { + cpp: ` + class Solution { + public: + vector runningSum(vector& nums) { + for (int i = 1; i < nums.size(); i++) { + nums[i] += nums[i - 1]; + } + return nums; + } + };`, + + java: ` + class Solution { + public int[] runningSum(int[] nums) { + for (int i = 1; i < nums.length; i++) { + nums[i] += nums[i - 1]; + } + return nums; + } + };`, + + python: ` + class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + for i in range(1, len(nums)): + nums[i] += nums[i - 1] + return nums + `, + }, + }, + + shuffleString: { + title: "36. Shuffle String", + description: + "Given a string s and an integer array indices of the same length as s, shuffle the string according to the indices array.", + examples: [ + { + input: `"codeleet", indices = [4, 5, 6, 7, 0, 2, 1, 3]`, + output: `"leetcode"`, + }, + ], + solution: { + cpp: ` + class Solution { + public: + string restoreString(string s, vector& indices) { + string res = s; + for (int i = 0; i < indices.size(); i++) { + res[indices[i]] = s[i]; + } + return res; + } + };`, + + java: ` + class Solution { + public String restoreString(String s, int[] indices) { + char[] res = new char[s.length()]; + for (int i = 0; i < s.length(); i++) { + res[indices[i]] = s.charAt(i); + } + return new String(res); + } + };`, + + python: ` + class Solution: + def restoreString(self, s: str, indices: List[int]) -> str: + res = [''] * len(s) + for i, idx in enumerate(indices): + res[idx] = s[i] + return ''.join(res) + `, + }, + }, + + maxLevelSum: { + title: "37. Maximum Level Sum of a Binary Tree", + description: + "Given the root of a binary tree, return the level with the maximum sum.", + examples: [{ input: "[1, 7, 0, 7, -8, null, null]", output: "2" }], + solution: { + cpp: ` + class Solution { + public: + int maxLevelSum(TreeNode* root) { + if (!root) return 0; + + queue q; + q.push(root); + + int maxSum = INT_MIN, level = 1, maxLevel = 1; + + while (!q.empty()) { + int size = q.size(); + int levelSum = 0; + + for (int i = 0; i < size; i++) { + TreeNode* node = q.front(); + q.pop(); + levelSum += node->val; + + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + + if (levelSum > maxSum) { + maxSum = levelSum; + maxLevel = level; + } + level++; + } + return maxLevel; + } + };`, + + java: ` + class Solution { + public int maxLevelSum(TreeNode root) { + if (root == null) return 0; + + Queue queue = new LinkedList<>(); + queue.add(root); + + int level = 1, maxLevel = 1; + int maxSum = Integer.MIN_VALUE; + + while (!queue.isEmpty()) { + int size = queue.size(); + int currentSum = 0; + + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + currentSum += node.val; + + if (node.left != null) queue.add(node.left); + if (node.right != null) queue.add(node.right); + } + + if (currentSum > maxSum) { + maxSum = currentSum; + maxLevel = level; + } + level++; + } + + return maxLevel; + } + };`, + + python: ` + class Solution: + def maxLevelSum(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + q = deque([root]) + level = 1 + max_sum = float('-inf') + result_level = 1 + + while q: + current_sum = 0 + for _ in range(len(q)): + node = q.popleft() + current_sum += node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + + if current_sum > max_sum: + max_sum = current_sum + result_level = level + + level += 1 + + return result_level + `, + }, + }, + + firstAlphabet: { + title: "38. First Alphabet of Each Word", + description: + "Given a string S, return a string containing the first letter of each word in the string.", + examples: [ + { input: `"geeks for geeks"`, output: `"gfg"` }, + { input: `"bad is good"`, output: `"big"` }, + ], + solution: { + cpp: ` + class Solution { + public: + string firstAlphabet(string S) { + string ans; + ans += S[0]; // Add the first character + + for (int i = 1; i < S.size(); i++) { + if (S[i - 1] == ' ') + ans += S[i]; // Add character after space + } + + return ans; + } + };`, + + java: ` + class Solution { + public String firstAlphabet(String S) { + StringBuilder ans = new StringBuilder(); + ans.append(S.charAt(0)); // Add first letter + + for (int i = 1; i < S.length(); i++) { + if (S.charAt(i - 1) == ' ') { + ans.append(S.charAt(i)); // Add letter after space + } + } + + return ans.toString(); + } + };`, + + python: ` + class Solution: + def firstAlphabet(self, S: str) -> str: + result = S[0] # Start with the first character + for i in range(1, len(S)): + if S[i-1] == ' ': + result += S[i] # Add character after space + return result + `, + }, + }, + + countLeaves: { + title: "39. Count Leaves in a Binary Tree", + description: "Given a Binary Tree, count the number of leaf nodes.", + examples: [ + { input: "[4, 8, 10, 7, 3, null, 5, null, null, null]", output: "3" }, + ], + solution: { + cpp: ` + int countLeaves(Node* root) { + if (!root) return 0; + + if (!root->left && !root->right) return 1; + + return countLeaves(root->left) + countLeaves(root->right); + };`, + + java: ` + class Solution { + public int countLeaves(Node root) { + if (root == null) return 0; + + if (root.left == null && root.right == null) return 1; + + return countLeaves(root.left) + countLeaves(root.right); + } + };`, + + python: ` + class Solution: + def countLeaves(self, root: Optional[Node]) -> int: + if not root: + return 0 + + if not root.left and not root.right: + return 1 + + return self.countLeaves(root.left) + self.countLeaves(root.right) + `, + }, + }, + + generateBinaryNumbers: { + title: "40. Generate Binary Numbers from 1 to N", + description: + "Given a number N, generate and print all binary numbers with decimal values from 1 to N.", + examples: [ + { input: "N = 2", output: "1 10" }, + { input: "N = 5", output: "1 10 11 100 101" }, + ], + solution: { + cpp: ` + vector generate(int N) { + queue q; + vector v; + + q.push("1"); + while (N--) { + string s = q.front(); + v.push_back(s); + q.pop(); + q.push(s + "0"); + q.push(s + "1"); + } + return v; + };`, + + java: ` + import java.util.*; + class Solution { + public List generate(int N) { + Queue q = new LinkedList<>(); + List result = new ArrayList<>(); + + q.add("1"); + while (N-- > 0) { + String s = q.poll(); + result.add(s); + q.add(s + "0"); + q.add(s + "1"); + } + return result; + } + };`, + + python: ` + from collections import deque + class Solution: + def generate(self, N: int) -> List[str]: + q = deque(["1"]) + result = [] + while N > 0: + s = q.popleft() + result.append(s) + q.append(s + '0') + q.append(s + '1') + N -= 1 + return result + `, + }, + }, + + minimumDifference: { + title: "41. Minimum Difference Between Any Pair", + description: + "Given an unsorted array, find the minimum difference between any pair in the given array.", + examples: [ + { input: "[2, 4, 5, 9, 7]", output: "1" }, + { input: "[3, 10, 8, 6]", output: "2" }, + ], + solution: { + cpp: ` + class Solution { + public: + int minimum_difference(vector nums) { + sort(nums.begin(), nums.end()); + int minm = INT_MAX; + + for (int i = 0; i < nums.size() - 1; i++) { + minm = min(minm, nums[i + 1] - nums[i]); + } + return minm; + } + };`, + + java: ` + import java.util.*; + class Solution { + public int minimum_difference(int[] nums) { + Arrays.sort(nums); + int minm = Integer.MAX_VALUE; + + for (int i = 0; i < nums.length - 1; i++) { + minm = Math.min(minm, nums[i + 1] - nums[i]); + } + return minm; + } + };`, + + python: ` + class Solution: + def minimum_difference(self, nums: List[int]) -> int: + nums.sort() + minm = float('inf') + + for i in range(len(nums) - 1): + minm = min(minm, nums[i + 1] - nums[i]) + + return minm + `, + }, + }, + + mthHalf: { + title: "42. Halve N, M-1 Times", + description: + "Given two values N and M, return the value when N is halved M-1 times.", + examples: [ + { input: "N = 100, M = 4", output: "12" }, + { input: "N = 10, M = 5", output: "0" }, + ], + solution: { + cpp: ` + class Solution { + public: + int mthHalf(int N, int M) { + return N / pow(2, M - 1); + } + };`, + + java: ` + class Solution { + public int mthHalf(int N, int M) { + return (int) (N / Math.pow(2, M - 1)); + } + };`, + + python: ` + class Solution: + def mthHalf(self, N: int, M: int) -> int: + return N // (2 ** (M - 1)) + `, + }, + }, + + removeChars: { + title: "43. Remove Characters from First String", + description: + "Given two strings string1 and string2, remove those characters from string1 which are present in string2.", + examples: [ + { input: 'string1 = "computer", string2 = "cat"', output: '"ompuer"' }, + { input: 'string1 = "occurrence", string2 = "car"', output: '"ouene"' }, + ], + solution: { + cpp: ` + class Solution { + public: + string removeChars(string string1, string string2) { + int arr[26] = {0}; + for (int i = 0; i < string2.size(); i++) + arr[string2[i] - 'a']++; + + string ans; + for (int i = 0; i < string1.size(); i++) { + if (arr[string1[i] - 'a'] == 0) // If value is 0, add to new string + ans += string1[i]; + } + return ans; + } + };`, + + java: ` + class Solution { + public String removeChars(String string1, String string2) { + int[] arr = new int[26]; + for (int i = 0; i < string2.length(); i++) + arr[string2.charAt(i) - 'a']++; + + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < string1.length(); i++) { + if (arr[string1.charAt(i) - 'a'] == 0) + ans.append(string1.charAt(i)); + } + return ans.toString(); + } + };`, + + python: ` + class Solution: + def removeChars(self, string1: str, string2: str) -> str: + arr = [0] * 26 + for char in string2: + arr[ord(char) - ord('a')] += 1 + + ans = [] + for char in string1: + if arr[ord(char) - ord('a')] == 0: + ans.append(char) + + return ''.join(ans) + `, + }, + }, + + rotateArray: { + title: "44. Rotate Array by D Elements", + description: + "Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).", + examples: [ + { + input: "N = 5, D = 2, arr = [1, 2, 3, 4, 5]", + output: "[3, 4, 5, 1, 2]", + }, + { + input: "N = 10, D = 3, arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]", + output: "[8, 10, 12, 14, 16, 18, 20, 2, 4, 6]", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + class Solution { + public: + void rotateArray(int n, int d, vector& arr) { + d = d % n; // Handle cases where d >= n + vector rotated(n); + + for (int i = 0; i < n; i++) { + rotated[(i + n - d) % n] = arr[i]; + } + + for (int i = 0; i < n; i++) { + cout << rotated[i] << " "; + } + cout << endl; + } + };`, + + java: ` + import java.util.*; + + class Solution { + public void rotateArray(int n, int d, int[] arr) { + d = d % n; // Handle cases where d >= n + int[] rotated = new int[n]; + + for (int i = 0; i < n; i++) { + rotated[(i + n - d) % n] = arr[i]; + } + + for (int i = 0; i < n; i++) { + System.out.print(rotated[i] + " "); + } + System.out.println(); + } + };`, + + python: ` + class Solution: + def rotateArray(self, n: int, d: int, arr: List[int]) -> List[int]: + d = d % n # Handle cases where d >= n + return arr[d:] + arr[:d] + `, + }, + }, + longestIncreasingSubsequence: { + title: "45. Longest Increasing Subsequence", + description: + "Given an array arr[] of size N, find the length of the longest subsequence of the array which is strictly increasing.", + examples: [ + { + input: "N = 6, arr = [5, 8, 3, 7, 9, 1]", + output: "3", + explanation: "The longest increasing subsequence is [5, 7, 9], so the length is 3.", + }, + { + input: "N = 4, arr = [3, 10, 2, 1, 20]", + output: "3", + explanation: "The longest increasing subsequence is [3, 10, 20], so the length is 3.", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + class Solution { + public: + int longestIncreasingSubsequence(int n, vector& arr) { + vector lis(n, 1); + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) { + lis[i] = lis[j] + 1; + } + } + } + + return *max_element(lis.begin(), lis.end()); + } + };`, + + java: ` + import java.util.*; + + class Solution { + public int longestIncreasingSubsequence(int n, int[] arr) { + int[] lis = new int[n]; + Arrays.fill(lis, 1); + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) { + lis[i] = lis[j] + 1; + } + } + } + + int max = 0; + for (int length : lis) { + max = Math.max(max, length); + } + return max; + } + };`, + + python: ` + from typing import List + + class Solution: + def longestIncreasingSubsequence(self, n: int, arr: List[int]) -> int: + lis = [1] * n + + for i in range(1, n): + for j in range(i): + if arr[i] > arr[j]: + lis[i] = max(lis[i], lis[j] + 1) + + return max(lis) + `, + }, + }, + + intersectionOfTwoLinkedLists: { + title: "46. Intersection of Two Linked Lists", + description: + "Given the heads of two singly linked lists, headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection, return null.", + examples: [ + { + input: "headA = [4,1,8,4,5], headB = [5,6,1,8,4,5]", + output: "Intersected at '8'", + explanation: + "The two linked lists intersect at node '8'.", + }, + { + input: "headA = [1,9,1,2,4], headB = [3,2,4]", + output: "Intersected at '2'", + explanation: + "The two linked lists intersect at node '2'.", + }, + { + input: "headA = [2,6,4], headB = [1,5]", + output: "null", + explanation: + "The two linked lists do not intersect, so the output is null.", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; + + class Solution { + public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + if (!headA || !headB) return NULL; + + ListNode *a = headA; + ListNode *b = headB; + + while (a != b) { + a = a ? a->next : headB; + b = b ? b->next : headA; + } + + return a; + } + };`, + + java: ` + public class ListNode { + int val; + ListNode next; + ListNode(int x) { + val = x; + next = null; + } + } + + public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + if (headA == null || headB == null) return null; + + ListNode a = headA; + ListNode b = headB; + + while (a != b) { + a = (a != null) ? a.next : headB; + b = (b != null) ? b.next : headA; + } + + return a; + } + };`, + + python: ` + class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + if not headA or not headB: + return None + + a, b = headA, headB + + while a != b: + a = a.next if a else headB + b = b.next if b else headA + + return a + `, + }, + }, + + coinChange: { + title: "47. Coin Change", + description: + "Given an integer array 'coins' representing different coin denominations and an integer 'amount' representing a total amount of money, return the fewest number of coins that you need to make up that amount. If that amount cannot be made up by any combination of the coins, return -1.", + examples: [ + { + input: "coins = [1, 2, 5], amount = 11", + output: "3", + explanation: + "The fewest number of coins needed is 3: 11 = 5 + 5 + 1.", + }, + { + input: "coins = [2], amount = 3", + output: "-1", + explanation: + "It is not possible to make up the amount 3 with only coin of denomination 2.", + }, + { + input: "coins = [1], amount = 0", + output: "0", + explanation: + "The amount is already 0, so no coins are needed.", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + class Solution { + public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); + dp[0] = 0; + + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (i - coin >= 0) { + dp[i] = min(dp[i], 1 + dp[i - coin]); + } + } + } + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } + };`, + + java: ` + import java.util.Arrays; + + public class Solution { + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount + 1]; + Arrays.fill(dp, amount + 1); + dp[0] = 0; + + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (i - coin >= 0) { + dp[i] = Math.min(dp[i], 1 + dp[i - coin]); + } + } + } + + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } + };`, + + python: ` + class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [float('inf')] * (amount + 1) + dp[0] = 0 + + for i in range(1, amount + 1): + for coin in coins: + if i - coin >= 0: + dp[i] = min(dp[i], 1 + dp[i - coin]) + + return dp[amount] if dp[amount] != float('inf') else -1 + `, + }, + }, + + quickSortAndMergeSort: { + title: "48. QuickSort and MergeSort", + description: + "Implement the QuickSort and MergeSort algorithms to sort an array of integers. QuickSort is a divide-and-conquer algorithm that selects a 'pivot' element and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot. MergeSort also uses divide-and-conquer by dividing the array into halves, sorting each half, and merging them back together.", + examples: [ + { + input: "array = [3, 6, 8, 10, 1, 2, 1]", + output: "[1, 1, 2, 3, 6, 8, 10]", + explanation: + "The array is sorted in ascending order using either QuickSort or MergeSort.", + }, + { + input: "array = [5, 2, 9, 1, 5, 6]", + output: "[1, 2, 5, 5, 6, 9]", + explanation: + "Both sorting algorithms yield the same sorted array.", + }, + { + input: "array = []", + output: "[]", + explanation: + "An empty array remains empty after sorting.", + }, + ], + solution: { + cpp: ` +#include +using namespace std; + +// QuickSort +void quickSort(vector& nums, int low, int high) { + if (low < high) { + int pivot = partition(nums, low, high); + quickSort(nums, low, pivot - 1); + quickSort(nums, pivot + 1, high); + } +} + +int partition(vector& nums, int low, int high) { + int pivot = nums[high]; + int i = low - 1; + for (int j = low; j < high; j++) { + if (nums[j] < pivot) { + i++; + swap(nums[i], nums[j]); + } + } + swap(nums[i + 1], nums[high]); + return i + 1; +} + +// MergeSort +void mergeSort(vector& nums, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + mergeSort(nums, left, mid); + mergeSort(nums, mid + 1, right); + merge(nums, left, mid, right); + } +} + +void merge(vector& nums, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + vector L(n1), R(n2); + for (int i = 0; i < n1; i++) L[i] = nums[left + i]; + for (int j = 0; j < n2; j++) R[j] = nums[mid + 1 + j]; + int i = 0, j = 0, k = left; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) nums[k++] = L[i++]; + else nums[k++] = R[j++]; + } + while (i < n1) nums[k++] = L[i++]; + while (j < n2) nums[k++] = R[j++]; +} +`, + + java: ` +import java.util.Arrays; + +public class Solution { + // QuickSort + public void quickSort(int[] nums, int low, int high) { + if (low < high) { + int pivot = partition(nums, low, high); + quickSort(nums, low, pivot - 1); + quickSort(nums, pivot + 1, high); + } + } + + private int partition(int[] nums, int low, int high) { + int pivot = nums[high]; + int i = (low - 1); + for (int j = low; j < high; j++) { + if (nums[j] < pivot) { + i++; + swap(nums, i, j); + } + } + swap(nums, i + 1, high); + return i + 1; + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + + // MergeSort + public void mergeSort(int[] nums, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + mergeSort(nums, left, mid); + mergeSort(nums, mid + 1, right); + merge(nums, left, mid, right); + } + } + + private void merge(int[] nums, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + int[] L = new int[n1]; + int[] R = new int[n2]; + for (int i = 0; i < n1; i++) L[i] = nums[left + i]; + for (int j = 0; j < n2; j++) R[j] = nums[mid + 1 + j]; + int i = 0, j = 0, k = left; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) nums[k++] = L[i++]; + else nums[k++] = R[j++]; + } + while (i < n1) nums[k++] = L[i++]; + while (j < n2) nums[k++] = R[j++]; + } +} +`, + + python: ` +class Solution: + # QuickSort + def quickSort(self, nums: List[int], low: int, high: int) -> None: + if low < high: + pivot = self.partition(nums, low, high) + self.quickSort(nums, low, pivot - 1) + self.quickSort(nums, pivot + 1, high) + + def partition(self, nums: List[int], low: int, high: int) -> int: + pivot = nums[high] + i = low - 1 + for j in range(low, high): + if nums[j] < pivot: + i += 1 + nums[i], nums[j] = nums[j], nums[i] + nums[i + 1], nums[high] = nums[high], nums[i + 1] + return i + 1 + + # MergeSort + def mergeSort(self, nums: List[int], left: int, right: int) -> None: + if left < right: + mid = left + (right - left) // 2 + self.mergeSort(nums, left, mid) + self.mergeSort(nums, mid + 1, right) + self.merge(nums, left, mid, right) + + def merge(self, nums: List[int], left: int, mid: int, right: int) -> None: + n1 = mid - left + 1 + n2 = right - mid + L = nums[left:left + n1] + R = nums[mid + 1:mid + 1 + n2] + i = j = 0 + k = left + while i < n1 and j < n2: + if L[i] <= R[j]: + nums[k] = L[i] + i += 1 + else: + nums[k] = R[j] + j += 1 + k += 1 + while i < n1: + nums[k] = L[i] + i += 1 + k += 1 + while j < n2: + nums[k] = R[j] + j += 1 + k += 1 +`, + }, +}, + +countInversions: { + title: "49. Count Inversions in an Array", + description: + "Implement a function to count the number of inversions in an array. An inversion is defined as a pair of indices (i, j) such that i < j and arr[i] > arr[j]. This can be achieved efficiently using a modified MergeSort algorithm, which counts inversions while merging.", + examples: [ + { + input: "array = [2, 4, 1, 3, 5]", + output: "3", + explanation: + "The inversions are (2, 1), (4, 1), and (4, 3).", + }, + { + input: "array = [1, 20, 6, 4, 5]", + output: "5", + explanation: + "The inversions are (1, 6), (1, 4), (1, 5), (20, 6), and (20, 4).", + }, + { + input: "array = [1, 2, 3, 4, 5]", + output: "0", + explanation: + "There are no inversions in a sorted array.", + }, + ], + solution: { + cpp: ` +#include +using namespace std; + +int mergeAndCount(vector& arr, int left, int mid, int right) { + int i = left; + int j = mid + 1; + int k = 0; + int inv_count = 0; + vector temp(right - left + 1); + + while (i <= mid && j <= right) { + if (arr[i] <= arr[j]) { + temp[k++] = arr[i++]; + } else { + temp[k++] = arr[j++]; + inv_count += (mid - i + 1); // Count inversions + } + } + + while (i <= mid) temp[k++] = arr[i++]; + while (j <= right) temp[k++] = arr[j++]; + + for (int i = left; i <= right; i++) arr[i] = temp[i - left]; + + return inv_count; +} + +int mergeSortAndCount(vector& arr, int left, int right) { + int inv_count = 0; + if (left < right) { + int mid = left + (right - left) / 2; + inv_count += mergeSortAndCount(arr, left, mid); + inv_count += mergeSortAndCount(arr, mid + 1, right); + inv_count += mergeAndCount(arr, left, mid, right); + } + return inv_count; +} + +int countInversions(vector& arr) { + return mergeSortAndCount(arr, 0, arr.size() - 1); +} +`, + + java: ` +public class Solution { + public int mergeAndCount(int[] arr, int left, int mid, int right) { + int i = left; + int j = mid + 1; + int k = 0; + int invCount = 0; + int[] temp = new int[right - left + 1]; + + while (i <= mid && j <= right) { + if (arr[i] <= arr[j]) { + temp[k++] = arr[i++]; + } else { + temp[k++] = arr[j++]; + invCount += (mid - i + 1); + } + } + + while (i <= mid) temp[k++] = arr[i++]; + while (j <= right) temp[k++] = arr[j++]; + + for (int m = left; m <= right; m++) arr[m] = temp[m - left]; + + return invCount; + } + + public int mergeSortAndCount(int[] arr, int left, int right) { + int invCount = 0; + if (left < right) { + int mid = left + (right - left) / 2; + invCount += mergeSortAndCount(arr, left, mid); + invCount += mergeSortAndCount(arr, mid + 1, right); + invCount += mergeAndCount(arr, left, mid, right); + } + return invCount; + } + + public int countInversions(int[] arr) { + return mergeSortAndCount(arr, 0, arr.length - 1); + } +} +`, + + python: ` +class Solution: + def mergeAndCount(self, arr, left, mid, right): + i = left + j = mid + 1 + k = 0 + inv_count = 0 + temp = [] + + while i <= mid and j <= right: + if arr[i] <= arr[j]: + temp.append(arr[i]) + i += 1 + else: + temp.append(arr[j]) + inv_count += (mid - i + 1) + j += 1 + + while i <= mid: + temp.append(arr[i]) + i += 1 + while j <= right: + temp.append(arr[j]) + j += 1 + + for m in range(len(temp)): + arr[left + m] = temp[m] + + return inv_count + + def mergeSortAndCount(self, arr, left, right): + inv_count = 0 + if left < right: + mid = left + (right - left) // 2 + inv_count += self.mergeSortAndCount(arr, left, mid) + inv_count += self.mergeSortAndCount(arr, mid + 1, right) + inv_count += self.mergeAndCount(arr, left, mid, right) + return inv_count + + def countInversions(self, arr): + return self.mergeSortAndCount(arr, 0, len(arr) - 1) +`, + }, +}, + +sortArray012: { + title: "50. Sort an Array of 0s, 1s, and 2s", + description: + "Implement a function to sort an array containing only 0s, 1s, and 2s. The task can be efficiently accomplished using the Dutch National Flag algorithm, which categorizes the elements in a single pass through the array.", + examples: [ + { + input: "array = [2, 0, 1, 2, 0, 1, 1]", + output: "[0, 0, 1, 1, 1, 2, 2]", + explanation: + "The array is sorted in ascending order with all 0s followed by 1s and then 2s.", + }, + { + input: "array = [1, 2, 0, 0, 1, 2]", + output: "[0, 0, 1, 1, 2, 2]", + explanation: + "After sorting, the array contains all 0s first, followed by 1s and then 2s.", + }, + { + input: "array = []", + output: "[]", + explanation: + "An empty array remains empty after sorting.", + }, + ], + solution: { + cpp: ` +#include +using namespace std; + +void sortColors(vector& nums) { + int low = 0, mid = 0, high = nums.size() - 1; + while (mid <= high) { + if (nums[mid] == 0) { + swap(nums[low++], nums[mid++]); + } else if (nums[mid] == 1) { + mid++; + } else { + swap(nums[mid], nums[high--]); + } + } +} +`, + + java: ` +public class Solution { + public void sortColors(int[] nums) { + int low = 0, mid = 0, high = nums.length - 1; + while (mid <= high) { + if (nums[mid] == 0) { + swap(nums, low++, mid++); + } else if (nums[mid] == 1) { + mid++; + } else { + swap(nums, mid, high--); + } + } + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} +`, + + python: ` +class Solution: + def sortColors(self, nums: List[int]) -> None: + low, mid, high = 0, 0, len(nums) - 1 + while mid <= high: + if nums[mid] == 0: + nums[low], nums[mid] = nums[mid], nums[low] + low += 1 + mid += 1 + elif nums[mid] == 1: + mid += 1 + else: + nums[mid], nums[high] = nums[high], nums[mid] + high -= 1 +`, + }, +}, + +searchInNearlySortedArray: { + title: "51. Perform a Search in a Nearly Sorted Array", + description: + "Implement a function to search for a target element in a nearly sorted array. In a nearly sorted array, each element is at most one position away from its original position. This allows for an efficient search using a modified binary search algorithm.", + examples: [ + { + input: "array = [10, 3, 40, 20, 50, 80, 70], target = 20", + output: "3", + explanation: + "The target element 20 is found at index 3 in the array.", + }, + { + input: "array = [10, 3, 40, 20, 50, 80, 70], target = 90", + output: "-1", + explanation: + "The target element 90 is not present in the array, so the output is -1.", + }, + { + input: "array = [1], target = 1", + output: "0", + explanation: + "The array contains only one element, which is the target; thus, it is found at index 0.", + }, + ], + solution: { + cpp: ` +#include +using namespace std; + +int searchInNearlySortedArray(vector& arr, int target) { + int n = arr.size(); + for (int i = 0; i < n; i++) { + if (arr[i] == target) { + return i; + } + if (i > 0 && arr[i - 1] == target) { + return i - 1; + } + if (i < n - 1 && arr[i + 1] == target) { + return i + 1; + } + } + return -1; +} +`, + + java: ` +public class Solution { + public int searchInNearlySortedArray(int[] arr, int target) { + int n = arr.length; + for (int i = 0; i < n; i++) { + if (arr[i] == target) { + return i; + } + if (i > 0 && arr[i - 1] == target) { + return i - 1; + } + if (i < n - 1 && arr[i + 1] == target) { + return i + 1; + } + } + return -1; + } +} +`, + + python: ` +class Solution: + def searchInNearlySortedArray(self, arr: List[int], target: int) -> int: + n = len(arr) + for i in range(n): + if arr[i] == target: + return i + if i > 0 and arr[i - 1] == target: + return i - 1 + if i < n - 1 and arr[i + 1] == target: + return i + 1 + return -1 +`, + }, +}, + flattenMultilevelDoublyLinkedList: { + title: "52. Flatten a Multilevel Doubly Linked List", + description: + "You are given a doubly linked list, where each node contains a next pointer, a prev pointer, and an additional child pointer that may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure. Flatten the list so that all the nodes appear in a single-level, doubly linked list. Preserve the order of nodes in the list, and return the head of the flattened list.", + examples: [ + { + input: "head = [1, 2, 3, 4, 5, 6] (with 3->7->8->9->10 and 8->11->12)", + output: "[1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6]", + }, + { + input: "head = [1, 2, null, 3] (with 1->2->3, and 1->child->4->5->6)", + output: "[1, 4, 5, 6, 2, 3]", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + // Definition for a Node. + class Node { + public: + int val; + Node* next; + Node* prev; + Node* child; + Node(int _val) : val(_val), next(NULL), prev(NULL), child(NULL) {} + }; + + class Solution { + public: + Node* flatten(Node* head) { + if (!head) return head; + Node* curr = head; + while (curr) { + if (curr->child) { + Node* nextNode = curr->next; + Node* child = flatten(curr->child); + + curr->next = child; + child->prev = curr; + curr->child = NULL; + + Node* temp = child; + while (temp->next) temp = temp->next; + + temp->next = nextNode; + if (nextNode) nextNode->prev = temp; + } + curr = curr->next; + } + return head; + } + };`, + + java: ` + import java.util.*; + + class Node { + public int val; + public Node next; + public Node prev; + public Node child; + + public Node(int val) { + this.val = val; + } + } + + class Solution { + public Node flatten(Node head) { + if (head == null) return head; + Node curr = head; + while (curr != null) { + if (curr.child != null) { + Node nextNode = curr.next; + Node child = flatten(curr.child); + + curr.next = child; + child.prev = curr; + curr.child = null; + + Node temp = child; + while (temp.next != null) temp = temp.next; + + temp.next = nextNode; + if (nextNode != null) nextNode.prev = temp; + } + curr = curr.next; + } + return head; + } + }`, + + python: ` + class Node: + def __init__(self, val=0, next=None, prev=None, child=None): + self.val = val + self.next = next + self.prev = prev + self.child = child + + class Solution: + def flatten(self, head: 'Node') -> 'Node': + if not head: + return head + curr = head + while curr: + if curr.child: + next_node = curr.next + child = self.flatten(curr.child) + + curr.next = child + child.prev = curr + curr.child = None + + temp = child + while temp.next: + temp = temp.next + + temp.next = next_node + if next_node: + next_node.prev = temp + curr = curr.next + return head + `, + }, + }, + findAllAnagramsInString: { + title: "53. Find All Anagrams in a String", + description: + "Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consist of lowercase English letters, and the order of output does not matter. An anagram of p is a permutation of p, and the function should return an array of starting indices where anagrams of p begin in s.", + examples: [ + { + input: "s = 'cbaebabacd', p = 'abc'", + output: "[0, 6]", + explanation: "The substring 'cba' starting at index 0 and 'bac' starting at index 6 are anagrams of 'abc'.", + }, + { + input: "s = 'abab', p = 'ab'", + output: "[0, 1, 2]", + explanation: "The substring 'ab' starting at indices 0, 1, and 2 are all anagrams of 'ab'.", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + class Solution { + public: + vector findAnagrams(string s, string p) { + vector result; + vector p_count(26, 0), s_count(26, 0); + + if (s.size() < p.size()) return result; + + for (int i = 0; i < p.size(); i++) { + p_count[p[i] - 'a']++; + s_count[s[i] - 'a']++; + } + + if (p_count == s_count) result.push_back(0); + + for (int i = p.size(); i < s.size(); i++) { + s_count[s[i] - 'a']++; + s_count[s[i - p.size()] - 'a']--; + + if (p_count == s_count) result.push_back(i - p.size() + 1); + } + + return result; + } + };`, + + java: ` + import java.util.*; + + class Solution { + public List findAnagrams(String s, String p) { + List result = new ArrayList<>(); + if (s.length() < p.length()) return result; + + int[] p_count = new int[26]; + int[] s_count = new int[26]; + + for (int i = 0; i < p.length(); i++) { + p_count[p.charAt(i) - 'a']++; + s_count[s.charAt(i) - 'a']++; + } + + if (Arrays.equals(p_count, s_count)) result.add(0); + + for (int i = p.length(); i < s.length(); i++) { + s_count[s.charAt(i) - 'a']++; + s_count[s.charAt(i - p.length()) - 'a']--; + + if (Arrays.equals(p_count, s_count)) result.add(i - p.length() + 1); + } + + return result; + } + };`, + + python: ` + from typing import List + from collections import Counter + + class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + p_count = Counter(p) + s_count = Counter(s[:len(p)]) + result = [] + + if s_count == p_count: + result.append(0) + + for i in range(len(p), len(s)): + s_count[s[i]] += 1 + s_count[s[i - len(p)]] -= 1 + + if s_count[s[i - len(p)] ] == 0: + del s_count[s[i - len(p)]] + + if s_count == p_count: + result.append(i - len(p) + 1) + + return result + `, + }, + }, + climbingStairs: { + title: "54. Climbing Stairs", + description: + "You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?", + examples: [ + { + input: "n = 2", + output: "2", + explanation: "There are two ways to climb to the top: 1 step + 1 step or 2 steps.", + }, + { + input: "n = 3", + output: "3", + explanation: "There are three ways to climb to the top: 1 step + 1 step + 1 step, 1 step + 2 steps, or 2 steps + 1 step.", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + class Solution { + public: + int climbStairs(int n) { + if (n <= 1) return 1; + int first = 1, second = 2; + for (int i = 3; i <= n; i++) { + int temp = second; + second += first; + first = temp; + } + return second; + } + };`, + + java: ` + class Solution { + public int climbStairs(int n) { + if (n <= 1) return 1; + int first = 1, second = 2; + for (int i = 3; i <= n; i++) { + int temp = second; + second += first; + first = temp; + } + return second; + } + };`, + + python: ` + class Solution: + def climbStairs(self, n: int) -> int: + if n <= 1: + return 1 + first, second = 1, 2 + for i in range(3, n + 1): + first, second = second, first + second + return second + `, + }, + }, +}; + +export default problemsData; diff --git a/src/pages/dsa-interview/index.tsx b/src/pages/dsa-interview/index.tsx index 7637a1f88..41e27a8e5 100644 --- a/src/pages/dsa-interview/index.tsx +++ b/src/pages/dsa-interview/index.tsx @@ -1,189 +1,189 @@ -import React, { useState } from "react"; -import { motion, AnimatePresence } from "framer-motion"; -import Layout from "@theme/Layout"; -import Tabs from "@theme/Tabs"; // Import Tabs component -import TabItem from "@theme/TabItem"; // Import TabItem component -import problemsData from "../../data/problemData"; - -const DSAQuestions: React.FC = () => { - const [openProblems, setOpenProblems] = useState>({}); - const [copiedLang, setCopiedLang] = useState<{ - problemKey: string; - lang: string; - } | null>(null); - - const handleToggle = (problem: string) => { - setOpenProblems((prev) => ({ - ...prev, - [problem]: !prev[problem], - })); - }; - - const handleCopySolution = ( - solution: string, - problemKey: string, - lang: string - ) => { - navigator.clipboard.writeText(solution).then(() => { - setCopiedLang({ problemKey, lang }); - setTimeout(() => setCopiedLang(null), 2000); - }); - }; - - const problemKeys = Object.keys(problemsData); - - return ( - -
-
- - Top DSA Interview Questions - - - Get prepared for your next interview with these common DSA problems. - -
- -
- {problemKeys.map((key) => ( -
-
handleToggle(key)} - > -

- {problemsData[key].title} -

- - {openProblems[key] ? "▲" : "▼"} - -
- - - {openProblems[key] && ( - -

- {problemsData[key].description} -

- -

Examples:

-
    - {problemsData[key].examples.map((example, index) => ( -
  • - Example {index + 1}: Input:{" "} - {example.input}, Output:{" "} - {example.output} -
  • - ))} -
- -
-

Solutions:

- - - -
- -
-                              {problemsData[key].solution.cpp}
-                            
-
-
- -
- -
-                              {problemsData[key].solution.java}
-                            
-
-
- -
- -
-                              {problemsData[key].solution.python}
-                            
-
-
-
-
-
- )} -
-
- ))} -
-
-
- ); -}; - -export default DSAQuestions; +import React, { useState } from "react"; +import { motion, AnimatePresence } from "framer-motion"; +import Layout from "@theme/Layout"; +import Tabs from "@theme/Tabs"; // Import Tabs component +import TabItem from "@theme/TabItem"; // Import TabItem component +import problemsData from "../../data/problemData"; + +const DSAQuestions: React.FC = () => { + const [openProblems, setOpenProblems] = useState>({}); + const [copiedLang, setCopiedLang] = useState<{ + problemKey: string; + lang: string; + } | null>(null); + + const handleToggle = (problem: string) => { + setOpenProblems((prev) => ({ + ...prev, + [problem]: !prev[problem], + })); + }; + + const handleCopySolution = ( + solution: string, + problemKey: string, + lang: string + ) => { + navigator.clipboard.writeText(solution).then(() => { + setCopiedLang({ problemKey, lang }); + setTimeout(() => setCopiedLang(null), 2000); + }); + }; + + const problemKeys = Object.keys(problemsData); + + return ( + +
+
+ + Top DSA Interview Questions + + + Get prepared for your next interview with these common DSA problems. + +
+ +
+ {problemKeys.map((key) => ( +
+
handleToggle(key)} + > +

+ {problemsData[key].title} +

+ + {openProblems[key] ? "▲" : "▼"} + +
+ + + {openProblems[key] && ( + +

+ {problemsData[key].description} +

+ +

Examples:

+
    + {problemsData[key].examples.map((example, index) => ( +
  • + Example {index + 1}: Input:{" "} + {example.input}, Output:{" "} + {example.output} +
  • + ))} +
+ +
+

Solutions:

+ + + +
+ +
+                              {problemsData[key].solution.cpp}
+                            
+
+
+ +
+ +
+                              {problemsData[key].solution.java}
+                            
+
+
+ +
+ +
+                              {problemsData[key].solution.python}
+                            
+
+
+
+
+
+ )} +
+
+ ))} +
+
+
+ ); +}; + +export default DSAQuestions;