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/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/languages/C/c-5.md b/docs/languages/C/c-5.md new file mode 100644 index 000000000..b608ae9b8 --- /dev/null +++ b/docs/languages/C/c-5.md @@ -0,0 +1,965 @@ +--- +id: pointers-in-c +sidebar_position: 4 +title: "Pointers In C" +sidebar_label: "Pointers In C" +--- + +Hey there! In this article, we will discuss C **pointers** in detail, their types, uses, advantages, and disadvantages with examples. + +- In C, the **pointers** are used to store the address of another variable and can also be used to access and manipulate the variable's data stored at that location. +- **Pointers** can also store the addresses of functions, array elements and even the addresses of another pointer +- With **pointers**, we can access and modify the data located in the memory, pass the data efficiently between the functions, and create dynamic data structures like linked lists, trees, and graphs. + + + +## 1. Pointer Declaration : + +To declare a pointer, use the **dereferencing operator (\*)** followed by the data type. + +### Syntax : + +The syntax below is used to define a pointer to a variable of a certain data type + +```c +data_type *ptr; + +``` + +- **ptr** is the name of the pointer +- **data_type** is the name of the data type its pointing to + +### Example : + +```c +int *ptr; +``` + +The pointer declared here will point to some random memory address as it is not initialized. + + + +## 2. Pointer Initialization : + +Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the **( &: ampersand ) address of** operator to get the memory address of a variable and then store it in the pointer variable. + +### Example : + +```c +int num = 24; +int *ptr; //declaration of an integer pointer +ptr = # +``` + +We can also declare a pointer in a single line,like below : + +```c +int *ptr = # //pointer definition +``` + +In **Pointer Definition** a pointer can be declared & initialized at the same time. + +## 3. Pointer Dereferencing : + +Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same **( \* ) dereferencing operator** that we used in the pointer declaration. + +```c +int num =20; +int *ptr = # +printf("%d\n",*ptr); //OUTPUT : 20 +printf("%x\n",ptr); //OUTPUT : 81b694b4 | Address of the 'num' variable (Address of a variable can be accessed via '&' operator) + +*ptr = 34; //changing the value of num via dereferencing +printf("%d\n",*ptr); // OUTPUT : 34 +``` + +--- + +### C Program to illustrate pointers : + +```c +#include +void main() +{ + int num = 10; + + // declare pointer variable + int* ptr; + + //data type of ptr and num must be same + ptr = # // pointer initialization + + + printf("Value at ptr = %p \n", ptr); //Address of 'num' + printf("Value at num = %d \n", num); + printf("Value at *ptr = %d \n", *ptr); + + *ptr = 24; + printf("Value at num = %d \n", num); + printf("Value at *ptr = %d \n", *ptr); + +} +``` + +#### Output : + +``` +Value at ptr = 0x7ffd1070ce84 +Value at num = 10 +Value at *ptr = 10 +Value at num = 24 +Value at *ptr = 24 +``` + +--- + +## 4. Size of a Pointer : + +The memory (or, size) occupied by a pointer variable does not depend on the type of the variable it is pointing to. The size of a pointer depends on the system architecture. + +The size of pointers in C is : + +- 8 bytes for a 64-bit System +- 4 bytes for a 32-bit System + +In the below example, we are printing the size of different types of pointers (64-bit architechture): +### Example : + +```c +#include + +void main() { + int x = 10; + float y = 1.354; + char z = 'p'; + + // Pointer declaration and initialization + int *ptr_x = &x; + float *ptr_y = &y; + char *ptr_z = &z; + + // Printing the size of pointer variables + printf("Size of integer pointer : %lu\n", sizeof(ptr_x)); + printf("Size of float pointer : %lu\n", sizeof(ptr_y)); + printf("Size of char pointer : %lu\n", sizeof(ptr_z)); + +} +``` + +### Output : + +``` +Size of integer pointer : 8 +Size of float pointer : 8 +Size of char pointer : 8 +``` + +--- + + + +## 5. Types of Pointers in C : + +Based on the type of variable stored in the memory location pointed by the pointer, the +**Pointers** in C can be classified into the following types : + +### 1. **Integer Pointers** + As the name suggests, these are the pointers that point to the integer values. They are called **pointer to integer** + +```c +int *ptr; +``` + +Similarly, a pointer can point to any primitive data type. + +```c +double *dp; /* pointer to a double */ +float *fp; /* pointer to a float */ +char *ch /* pointer to a character */ +``` + +--- + +C pointers can point also point to derived data types such as arrays and user-defined data types such as structures. + + ### 2. **Array Pointer** + Pointers and Array are closely related to each other. Even **the array name is the pointer to its first element**. They are also known as **pointer to arrays**. + +```c +int arr[]={2,4,6,8,10,12}; +int *ptr = arr ; //"arr" points to the very first [0th] element '2' of the integer array "arr" +``` + +Similarly, we can also declare a pointer that can **point to whole array** instead of only one element of the array. This pointer is useful when talking about **multidimensional arrays**. + +```c +#include + +void main() +{ + // Pointer to an integer + int *p; + + // Pointer to an array of 5 integers + int (*ptr)[5]; + int arr[5]; + + // Points to 0th element of the arr. + p = arr; + + // Points to the whole array arr. + ptr = &arr; + + printf("p = %p, ptr = %p\n", p, ptr); //p = 0x7fff6463e890, ptr = 0x7fff6463e890 + + p++; + ptr++; + + printf("p = %p, ptr = %p\n", p, ptr); //p = 0x7fff6463e894, ptr = 0x7fff6463e8a4 + +} +``` + +--- + +### 3. **Structure Pointer** + The pointer pointing to the structure type is called **Structure Pointer** or **Pointer to Structure**. It can be declared in the same way as we declare the other primitive data types. + +```c +struct student { + char name[35]; + int roll; + int total; +}; + +struct student Eshita; +strcpy(Eshita.name,"Eshita"); +Eshita.roll=1; +Eshita.total=500; + +//structure pointer definition +struct student *ptr = &Eshita; + +//access structure members using the structure pointer +printf("Roll = %d\n",(*ptr).roll); // OUTPUT :Roll = 1 + +``` + +--- + + + +### 4. **Function Pointer** + **Function pointers point to the functions**. They are different from the rest of the pointers in the sense that **instead of pointing to the data, they point to the code** + +```c +#include +// A normal function with an int parameter +// and void return type +void fun(int a) { printf("Value of a is %d\n", a); } + +void main() +{ + // fun_ptr is a pointer to function fun() + void (*fun_ptr)(int) = &fun; //function pointer definition + + // Invoking fun() using fun_ptr + (*fun_ptr)(10); + +} +``` + +- Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. +- Unlike normal pointers, we do not allocate de-allocate memory using function pointers. +- A function's name can also be used to get function's address. + **Example** + +```c +#include + +void fun(int a) { printf("Value of a is %d\n", a); } + +void main() +{ + void (*fun_ptr)(int) = fun; //function pointer definition via the name of the function only + + fun_ptr(10); // invoking fun() using fun_ptr() & not the '*' sign + +} +``` + +--- + + + +### 5. **Double Pointers** + In C language, we can define **a pointer that stores the memory address of another pointer**. Such pointers are called **double-pointers** or **pointers-to-pointer**. Instead of pointing to a data value, they point to another pointer. + +**Syntax**: + +```c +data_type_of_pointer **name_of_variable = &normal_pointer_variable; +``` + +**Example**: + +```c +int val = 5; +int *ptr = &val; // storing address of val to pointer ptr. +//d_ptr points to ptr which is a pointer itself +int **d_ptr = &ptr; // pointer to a pointer declared & initialized + // which is pointing to an integer. + +``` + +- The double pointer is declared using the syntax shown above. +- After that, we store the address of another pointer as the value of this new double pointer. +- Now, if we want to manipulate or dereference to any of its levels, we have to use Asterisk ( \* ) operator the number of times down the level we want to go. + +--- + + + +### 6. **Void Pointer** + The **Void pointers** in C are the pointers of type void. It means that they do not have any associated data type. They are also called **generic pointers** as they can point to any type and can be typecasted to any type. + +**Syntax** + +```c +void * pointer_name; +``` + +**Some uses of Void Pointers:** + +- **malloc()** and **calloc()** return **void \* type** and this allows these functions to be used to allocate memory of any data type (just because of void \*). +- void pointers used along with Function pointers of type void (\*)(void) point to the functions that take any arguments and return any value. +- void pointers are mainly used in the implementation of data structures such as linked lists, trees, and queues i.e. dynamic data structures. +- void pointers are also commonly used for typecasting. + +--- + +### 7. **NULL Pointer** + The **Null Pointers** are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value. + +```c +data_type *pointer_name = NULL; +``` + +- It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. +- The NULL pointer is a constant with a value of "0" defined in several standard libraries. + +**Some uses of NULL Pointers:** + +- We initialize a pointer variable when that pointer variable hasn't been assigned any valid memory address yet. +- We check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer-related code, e.g., dereference a pointer variable only if it's not NULL. +- We pass a null pointer to a function argument when we don't want to pass any valid memory address. +- NULL pointers are also used in data structures like trees, linked lists, etc. to indicate the end. + +--- + + + +## 6. Other important pointer types : +### 1. **Dangling Pointer** + **A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer**. Such a situation can lead to unexpected behavior in the program and also serve as a source of bugs in C programs. + There are different ways where a pointer acts as a dangling pointer.Like, + + #### 1. **Deallocation of memory** + When a memory pointed by a pointer is deallocated the pointer becomes a dangling pointer. + **Example :** + + ```c + void main() + { + int* ptr = (int*)malloc(sizeof(int)); + + // After free call, ptr becomes a dangling pointer + free(ptr); + printf("Memory freed\n"); + + // removing Dangling Pointer + ptr = NULL; + + + + } + ``` + + #### 2. **Variable Goes Out of Scope** + When a variable goes out of scope the pointer pointing to that variable becomes a dangling pointer.Similarly, if we return the address of a local variable then it becomes a dangling pointer. + **Example :** + + ```c + int* fun(){ + int num = 45; // if the 'num' variable was static it had scope throughout the program + int* ptr = # + return ptr; + } + void main() + { + int* p = fun(); + + // p points to something which is not + // valid anymore + printf("%d\n", *p); + + } + ``` + +--- + +### 2. **Wild Pointer** + **A pointer that has not been initialized to anything (not even NULL) is known as a wild pointer.** The pointer may be initialized to a non-NULL garbage value that may not be a valid address. + The below example demonstrates the undefined behavior of the Wild pointer. + **Example** + + ```c + #include + void main() + { + int* p; //wild pointer + + // trying to access the value pointed by a wild pointer + // is undefined behavior + // printf("Value pointed by wild pointer: %d\n", *p); + // //give error + + int x = 10; + + // Accessing the value pointed by 'p' + printf("Value pointed by 'p' is: %d\n", *p); + + } + ``` + + **Output :** + + ``` + Segmentation Fault (SIGSEGV) + timeout: the monitored command dumped core + /bin/bash: line 1: 32 Segmentation fault + ``` + +--- + + + +## 7. Pointer Arithmetic +**Pointer Arithmetic** is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn’t store any value. + +Hence, there are only a few operations that are allowed to be performed on Pointers in C language. The C pointer arithmetic operations are slightly different from the ones that we generally use for mathematical calculations. These operations are: +- Increment and Decrement of a Pointer +- Addition and Subtraction of Integer to Pointer +- Subtraction of Pointers +- Comparison of Pointers + + + +### a. Increment and Decrement of a Pointer +The "++" and "--" are used as the increment and decrement operators in C. They are unary operators, used in prefix or postfix manner with numeric variable operands, and they increment or decrease the value of the variable by one. + +Assume that an integer variable "a" is created at address 1000 in the memory, with 24 as its value. Then, "a++" makes the value of "a" as 25. + +```c +int a = 24; // created at address 1000 + +a++; // a becomes 25 +``` +Now, let's see what happens if we declare "p" as a pointer to "a" and increment "p" by 1 (with "p++")? Assume that the address of "p" itself is 2000. + +```c +int a = 24; // created at address 1000 + +// "p" is created at address 2000 +// it holds 1000 (address of "x") +int *p = &a ; + +p++; // p becomes 1004 +``` +Since the variable "p" stores 1000 (the address of "a"), we expect it to become 1001 because of the "++" operator, but it increments by 4, which is the size of "int" variable. + +The is why because, if the address of "a" is 1000, then it occupies 4 bytes: 1000, 1001, 1002 and 1003. Hence, the next integer can be put only in 1004 and not before it. Hence "p" (the pointer to "a") becomes 1004 when incremented. + + + +#### Example of Incrementing a Pointer +```c +#include + +void main(){ + + int x = 30; + int *y = &x; + + printf("Value of y before increment: %d\n", y); + + y++; + + printf("Value of y after increment: %d", y); +} +``` +#### Output: +``` +Value of y before increment: 6422036 +Value of y after increment: 6422040 +``` +You can see that the value has increased by 4. Similarly, the "--" operator decrements the value by the size of the data type. + +#### Example of Decrementing a Pointer +Now, let us change the types of "x" and "y" to "double" and "float" and see the effect of the decrement operator. +```c +#include +void main(){ + + double x = 10; + double *y = &x; + + printf("value of y before decrement: %ld\n", y); + + y--; + + printf("value of y after decrement: %ld", y); +} +``` +#### Output +``` +Value of y before decrement: 6422032 +Value of y after decrement: 6422024 +``` +--- + + + +#### Example of Traversing an Array by Incrementing Pointer + +When an array is declared, the elements are stored in adjacent memory locations. In case of "int" array, each array subscript is placed apart by 4 bytes. + +Hence, if a variable stores the address of 0th element of the array, then the "increment" takes it to the 1st element. + +The following example shows how you can traverse an array by incrementing a pointer successively - + +```c +#include + +void main(){ + + int a[]= {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; + int len = sizeof(a)/sizeof(int); + int *x = a; + int i = 0; + + for(i = 0; i < len; i++){ + printf("Address of subscript %d = %d Value = %d\n", i, x, *x); + x++; + } + +} +``` +#### Output +```c +Address of subscript 0 = 6421984 Value = 10 +Address of subscript 1 = 6421988 Value = 20 +Address of subscript 2 = 6421992 Value = 30 +Address of subscript 3 = 6421996 Value = 40 +Address of subscript 4 = 6422000 Value = 50 +Address of subscript 5 = 6422004 Value = 60 +Address of subscript 6 = 6422008 Value = 70 +Address of subscript 7 = 6422012 Value = 80 +Address of subscript 8 = 6422016 Value = 90 +Address of subscript 9 = 6422020 Value = 100 +``` + + + +### b. Addition and Subtraction of Integer to Pointer +An integer value can be added and subtracted to a pointer. When an integer is added to a pointer, the pointer points to the next memory address. Similarly, when an integer is subtracted from a pointer, the pointer points to the previous memory location. + +Addition and subtraction of an integer to a pointer does not add and subtract that value to the pointer, multiplication with the size of the data type is added or subtracted to the pointer. + +For example, there is an integer pointer variable ptr and it is pointing to an address 123400, if you add 1 to the ptr (ptr+1), it will point to the address 123404 (size of an integer is 4). +Let's evaluate it, +``` +ptr = 123400 +ptr = ptr + 1 +ptr = ptr + sizeof(int)*1 +ptr = 123400 + 4 +ptr = 123404 +``` +#### Example of Adding Value to a Pointer +```c +#include + +void main() { + int int_arr[] = {12, 23, 45, 67, 89}; + int *ptrArr = int_arr; + + printf("Value at ptrArr: %d\n", *ptrArr); + + // Adding 2 in ptrArr + ptrArr = ptrArr + 2; + + printf("Value at ptrArr after adding 2: %d\n", *ptrArr); + +} +``` +#### Output +``` +Value at ptrArr: 12 +Value at ptrArr after adding 2: 45 +``` +#### Example of Subtracting Value to a Pointer +In the following example, we are declaring an array and pointer to an array. Initializing the pointer with the last element of the array and then subtracting an integer value (2) from the pointer to get the third element of the array. + +```c +#include +void main() { + int int_arr[] = {12, 23, 45, 67, 89}; + int *ptrArr = &int_arr[4]; // points to last element + + printf("Value at ptrArr: %d\n", *ptrArr); + + // Subtracting 2 in ptrArr + ptrArr = ptrArr - 2; + + printf("Value at ptrArr after adding 2: %d\n", *ptrArr); + +} +``` +#### Output +``` +Value at ptrArr: 89 +Value at ptrArr after adding 2: 45 +``` + + +] +### c. Subtraction of Pointers +The "+" and "−" operators are used with regular numeric operands. However, when you use these operators with pointers, they behave in a little different way. + +Since pointers are fairly large integers (especially in modern 64-bit systems), addition of two pointers is meaningless. When we add a 1 to a pointer, it points to the next location where an integer may be stored. Obviously, when we add a pointer (itself a large integer), the location it points may not be in the memory layout. + +However, the subtraction of two pointers is realistic. It returns the number of data types that can fit in the two pointers. + +#### Example of Subtracting Two Pointers +Let us take the array in the previous example and perform the subtraction of pointers of a[0] and a[9] +```c +#include + +void main(){ + + int a[]= {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; + int *x = &a[0]; // zeroth element + int *y = &a[9]; // last element + + printf("Add of a[0]: %ld add of a[9]: %ld\n", x, y); + printf("Subtraction of two pointers: %ld", y-x); + +} +``` +#### Output +``` +Add of a[0]: 140729162482768 add of a[9]: 140729162482804 +Subtraction of two pointers: 9 +``` +It can be seen that the numerical difference between the two integers is 36; it suggests that the subtraction is 9 because it can accommodate 9 integers between the two pointers. + +### d.Comparison of Pointers +Pointers can be compared by using **relational operators** such as `==`, `<`, and `>`. If "p1" and "p2" point to variables that are related to each other (such as elements of the same array), then "p1" and "p2" can be meaningfully compared. + + + +#### Example of Comparing Pointers +In the following example, we are declaring two pointers and initializing them with the first and last elements of the array respectively. We will keep incrementing the first variable pointer as long as the address to which it points is either less than or equal to the address of the last element of the array, which is "&var[MAX − 1]" (i.e., the second pointer). +```c +#include + +const int MAX = 3; + +void main() { + int var[] = {10, 100, 200}; + int i, *ptr1, *ptr2; + + // Initializing pointers + ptr1 = var; + ptr2 = &var[MAX - 1]; + + while (ptr1 <= ptr2) { + printf("Address of var[%d] = %p\n", i, ptr1); + printf("Value of var[%d] = %d\n", i, *ptr1); + + /* point to the previous location */ + ptr1++; + i++; + } +} +``` +#### Output +``` +Address of var[0] = 0x7ffe7101498c +Value of var[0] = 10 +Address of var[1] = 0x7ffe71014990 +Value of var[1] = 100 +Address of var[2] = 0x7ffe71014994 +Value of var[2] = 200 +``` + + + +## 8. Applications of pointers in C : +The following are some major applications of pointers in the C programming language: + +### 1. **Passing Arguments by Reference** + Passing arguments by reference serves two purposes: + + #### a. to modify the variable in another function. + **Example :** + ```c + #include + void swap(int* x, int* y) + { + int temp = *x; + *x = *y; + *y = temp; + } + void main() + { + int x = 10, y = 20; + printf("%d %d\n", x, y); // OUTPUT : 10 20 + swap(&x, &y); + printf("%d %d\n", x, y); // OUTPUT : 20 10 + + } + ``` + #### b. For Efficiency Purpose. + **Example :** + ```c + #include + // function to print an array by passing reference to array + void printArray(int* arr, int n) + { + // here array elements are passed by reference + for (int i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + } + + void main() + { + int arr[5] = { 1, 2, 3, 4, 5 }; + printArray(arr, 5); + } + ``` +### 2. **To Access Array Elements** + **Example :** + ```c + #include + int main() + { + int arr[] = { 100, 200, 300, 400 }; + + // Compiler converts below to *(arr + 2). + printf("%d ", arr[2]);//300 + + // So below also works. + printf("%d\n", *(arr + 2));//300 + + return 0; + } + ``` +### 3. **To Return Multiple Values** + The functions in C can only return a single value, but we can use pointers to return multiple values from a C function. + **Example :** + ```c + #include + #include + + void fun(int n, int* square, double* sq_root) + { + *square = n * n; + *sq_root = sqrt(n); + } + + int main() + { + + int n = 100; + int sq; + double sq_root; + fun(n, &sq, &sq_root); + + printf("%d %f\n", sq, sq_root); + return 0; + } + ``` + + + +### 4. **For dynamic memory Allocation** + We can use pointers to dynamically allocate memory i.e Dynamic memory allocation.But dynamic memory doesn't get deleted automatically, we need to delete it for a good practice after using it. + **Example** + ```c + #include + #include + int* createArr(int n) + { + int* arr = (int*)(malloc(n * sizeof(int))); + return arr; + } + + int main() + { + int* pt = createArr(10); + return 0; + } + ``` + +--- + +## 9. Array of Pointers : +In C, a pointer array is a homogeneous collection of indexed pointer variables that are references to a memory location. It is generally used in C Programming when we want to point at multiple memory locations of a similar data type in our C program. We can access the data by dereferencing the pointer pointing to it. +### Syntax : +```c +pointer_type *array_name [array_size]; +``` +- **pointer_type**: Type of data the pointer is pointing to. +- **array_name**: Name of the array of pointers. +- **array_size**: Size of the array of pointers. + + + +### a. An Array of Pointers to Integers +#### Syntax +```c +int *ptr[MAX]; +``` +It declares ptr as an array of MAX integer pointers. Thus, each element in ptr holds a pointer to an int value. + +#### Example +```c +#include + +void main(){ + + int numbers[] = {10, 100, 200}; + int i, *ptr[3]; + + for(i = 0; i < MAX; i++){ + ptr[i] = &numbers[i]; //address of the numbers[i] integer + } + + for (i = 0; i < MAX; i++){ + printf("Value of numbers[%d] = %d\n", i, *ptr[i]); + } + +} +``` +#### Output +``` +Value of numbers[0] = 10 +Value of numbers[1] = 100 +Value of numbers[2] = 200 +``` +### b. An Array of Pointers to Characters +#### Example +```c +#include + +void main(){ + + char *names[] = { + "Eshita Das", + "Srijita Mondal", + "Monami Das", + "Poulami Bhandari" + }; + + int i = 0; + + for(i = 0; i < 4; i++){ + printf("Value of names[%d] = %s\n", i, names[i]); + } + + return 0; +} +``` +#### Output +``` +Value of names[0] = Eshita Das +Value of names[1] = Srijita Mondal +Value of names[2] = Monami Das +Value of names[3] = Poulami Bhandari +``` + + +### c. An Array of Pointers to Structures +When you have a list of structures and want to manage it using a pointer. You can declare an array of structures to access and manipulate the list of structures. +#### Example +```c +#include +#include +#include + +// Declaring a structure +typedef struct { + char title[50]; + float price; +} Book; + +const int MAX = 3; +void main() { + Book *book[MAX]; + + // Initialize each book (pointer) + for (int i = 0; i < MAX; i++) { + book[i] = malloc(sizeof(Book)); + snprintf(book[i]->title, 50, "Book %d", i + 1); + book[i]->price = 100 + i; + } + + // Print details of each book + for (int i = 0; i < MAX; i++) { + printf("Title: %s, Price: %.2f\n", book[i]->title, book[i]->price); + } + + // Free allocated memory + for (int i = 0; i < MAX; i++) { + free(book[i]); + } + +} +``` +#### Output +``` +Title: Book 1, Price: 100.00 +Title: Book 2, Price: 101.00 +Title: Book 3, Price: 102.00 +``` + +--- + + + +## 10. Advantages & Disadvantages of Pointers in C : + +### Advantages of Pointers in C +Following are the major advantages of pointers in C: + +- Pointers are used for dynamic memory allocation and deallocation. +- An Array or a structure can be accessed efficiently with pointers +- Pointers are useful for accessing memory locations. +- Pointers are used to form complex data structures such as linked lists, graphs, trees, etc. +- Pointers reduce the length of the program and its execution time as well. + +### Disadvantages of Pointers in C + +Pointers are vulnerable to errors and have following disadvantages: + +- Memory corruption can occur if an incorrect value is provided to pointers. +- Pointers are a little bit complex to understand. +- Pointers are majorly responsible for memory leaks in C. +- Pointers are comparatively slower than variables in C. +- Uninitialized pointers might cause a segmentation fault. + +## 11. Conclusion : + +In conclusion, pointers in C are very capable tools and provide C language with its distinguishing features, such as low-level memory access, referencing, etc. But as powerful as they are, they should be used with responsibility as they are one of the most vulnerable parts of the language. diff --git a/docs/languages/C/c-6.md b/docs/languages/C/c-6.md new file mode 100644 index 000000000..91e77738e --- /dev/null +++ b/docs/languages/C/c-6.md @@ -0,0 +1,777 @@ +--- +id: structures-in-c +sidebar_position: 5 +title: "Structures In C" +sidebar_label: "Structures In C" +--- + +Hey there! In this article, we will discuss C **structures** in detail, their uses, advantages, and disadvantages with examples. + +- A **structure** in C is a derived or user-defined data type. We use the keyword struct to define a custom data type that groups together the elements of different types. The difference between an array and a structure is that an array is a homogenous collection of similar types, whereas a structure can have elements of different types stored adjacently and identified by a name. + +- We are often required to work with values of different data types having certain relationships among them. For example, a book is described by its title (string), author (string), price (double), number of pages (integer), etc. Instead of using four different variables, these values can be stored in a single struct variable. + +## 1. C Structure Declaration +We have to declare structure in C before using it in our program. In structure declaration, we specify its member variables along with their datatype. We can use the struct keyword to declare the structure in C using the following syntax: + +```c +struct structure_name { + data_type member_name1; + data_type member_name1; + .... + .... +}; +``` +The above syntax is also called a structure template or structure prototype and no memory is allocated to the structure in the declaration + +## 2. C Structure Definition +### A. Structure Variable Declaration with Structure +```c +struct structure_name { + data_type member_name1; + data_type member_name1; + .... + .... +}variable1, varaible2, ...; +``` +#### Example +```c +struct book{ + char title[50]; + char author[50]; + double price; + int pages; +} book1; +``` +### B. Structure Variable Declaration after Structure +```c +// structure declared beforehand +struct structure_name variable1, variable2, .......; +``` +#### Example +```c +struct book book1; +``` +--- + +## 3. Structure Initialization + +### A. Initialization using Assignment Operator +```c +struct structure_name str; +str.member1 = value1; +str.member2 = value2; +str.member3 = value3; +. +. +. +``` +### B. Default Initialization +By default, structure members are not automatically initialized to 0 or NULL. Uninitialized structure members will contain garbage values. However, when a structure variable is declared with an initializer, all members not explicitly initialized are zero-initialized. +```c +struct Point +{ + int x; + int y; +}; + +struct Point p = {0}; // Both x and y are initialized to 0 +``` +### C. Initialization using Initializer List +The initialization of a struct variable is done by placing the value of each element inside curly brackets. +#### Example +```c +struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325}; +``` +### D. Initialization using Designated Initializer List +```c +struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 }; +``` +--- + +## 4. Accessing the Structure Members +We can access structure members by using the **( . ) dot operator**. +### Syntax +```c +structure_name.member1; +structure_name.member2; +``` +### Example +```c +#include + +struct book{ + char title[10]; + char author[20]; + double price; + int pages; +}; + +void main(){ + struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325}; + + printf("Title: %s \n", book1.title); + printf("Author: %s \n", book1.author); + printf("Price: %lf\n", book1.price); + printf("Pages: %d \n", book1.pages); + printf("Size of book struct: %d", sizeof(struct book)); + +} +``` + +### Output +``` +Title: Learn C +Author: Dennis Ritchie +Price: 675.500000 +Pages: 325 +Size of book struct: 48 +``` +In the case where we have a pointer to the structure, we can also use the arrow operator to access the members. +### Syntax +```c +struct_pointer->title; +``` +### Example +```c +#include +#include + +struct book{ + char title[10]; + char author[20]; + double price; + int pages; +}; + +int main (){ + struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325}; + struct book *strptr; + strptr = &book1; + + printf("Title: %s \n", strptr -> title); + printf("Author: %s \n", strptr -> author); + printf("Price: %lf \n", strptr -> price); + printf("Pages: %d \n", strptr -> pages); + return 0; +} +``` +### Output +``` +Title: Learn C +Author: Dennis Ritchie +Price: 675.500000 +Pages: 325 +``` +### Note : +The dot (.) operator is used to access the struct elements via the struct variable. To access the elements via its pointer, we must use the indirection (->) operator + +--- + +## 5. typedef for Structures +The typedef keyword is used to define an alias for the already existing datatype. In structures, we have to use the struct keyword along with the structure name to define the variables. Sometimes, this increases the length and complexity of the code. We can use the typedef to define some new shorter name for the structure. + +### Example +```c +#include + +// defining structure +typedef struct { + int a; +} str1; + +// another way of using typedef with structures +typedef struct { + int x; +} str2; + +void main() +{ + // creating structure variables using new names + str1 var1 = { 20 }; + str2 var2 = { 314 }; + + printf("var1.a = %d\n", var1.a); + printf("var2.x = %d\n", var2.x); + +} + +``` +### Output +``` +var1.a = 20 +var2.x = 314 +``` +--- + +## 6. Bit Fields +**Bit Fields** are used to specify the length of the structure members in bits. When we know the maximum length of the member, we can use bit fields to specify the size and reduce memory consumption. + +### Syntax +```c +struct structure_name { + data_type member_name: width_of_bit-field; +}; +``` +### Example +```c +#include + +// declaring structure for reference +struct str1 { + int a; + char c; +}; + +// structure with bit fields +struct str2 { + int a : 24; // size of 'a' is 3 bytes = 24 bits + char c; +}; + +// driver code +int main() +{ + printf("Size of Str1: %d\nSize of Str2: %d", + sizeof(struct str1), sizeof(struct str2)); + return 0; +} + +``` +### Output +``` +Size of Str1: 8 +Size of Str2: 4 +``` + +--- + +## 7. Structure Pointer in C +We can define a pointer that points to the structure like any other variable. Such pointers are generally called **Structure Pointers**. We can access the members of the structure pointed by the structure pointer using the **( -> ) arrow** operator. +### Example +```c +#include + +// structure declaration +struct Point { + int x, y; +}; + +void main() +{ + struct Point str = { 1, 2 }; + + // p2 is a pointer to structure p1 + struct Point* ptr = &str; + + // Accessing structure members using structure pointer + printf("%d %d", ptr->x, ptr->y); + +} + +``` +### Output +``` +1 2 +``` +### Structures as Function Arguments +You can pass a structure as a function argument in the same way as you pass any other variable or pointer. +#### Example +```c +#include +#include + +struct Books{ + char title[50]; + char author[50]; + char subject[100]; + int book_id; +}; + +/* function declaration */ +void printBook(struct Books book); + +int main(){ + struct Books Book1; /* Declare Book1 of type Book */ + struct Books Book2; /* Declare Book2 of type Book */ + + /* book 1 specification */ + strcpy(Book1.title, "C Programming"); + strcpy(Book1.author, "Nuha Ali"); + strcpy(Book1.subject, "C Programming Tutorial"); + Book1.book_id = 6495407; + + /* book 2 specification */ + strcpy(Book2.title, "Telecom Billing"); + strcpy(Book2.author, "Zara Ali"); + strcpy(Book2.subject, "Telecom Billing Tutorial"); + Book2.book_id = 6495700; + + /* print Book1 info */ + printBook(Book1); + + /* Print Book2 info */ + printBook(Book2); + return 0; +} + +void printBook(struct Books book){ + + printf("Book title : %s\n", book.title); + printf("Book author : %s\n", book.author); + printf("Book subject : %s\n", book.subject); + printf("Book book_id : %d\n", book.book_id); +} +``` +#### Output +``` +Book title : C Programming +Book author : Nuha Ali +Book subject : C Programming Tutorial +Book book_id : 6495407 +Book title : Telecom Billing +Book author : Zara Ali +Book subject : Telecom Billing Tutorial +Book book_id : 6495700 +``` +### How to Pass a Struct by Reference +In C language, a function may be defined to have its arguments passed by value or reference. A reference is the pointer to an existing variable. +#### Example +```c +#include + +struct rectangle{ + float len, brd; + double area; +}; + +int area(struct rectangle *); + +int main(){ + + struct rectangle r; + r.len = 10.50; r.brd = 20.5; + area(&r); + + return 0; +} + +int area(struct rectangle *r){ + + r -> area = (double)(r -> len * r -> brd); + printf("Length: %f \nBreadth: %f \nArea: %lf\n", r -> len, r -> brd, r -> area); + + return 0; +} +``` +#### Output +``` +Length: 10.500000 +Breadth: 20.500000 +Area: 215.250000 +``` + +### How to Return a Struct Pointer +#### Example +```c +#include + +struct rectangle { + float len, brd; + double area; +}; + +struct rectangle * area(float x, float y); + +int main (){ + + struct rectangle *r; + float x, y; + + x = 10.5; y = 20.5; + r = area(x, y); + printf("Length: %f \n Breadth: %f \n Area: %lf\n", r->len, r->brd, r->area); + + return 0; +} + +struct rectangle * area(float x, float y){ + + double area = (double)(x*y); + static struct rectangle r; + r.len = x; r.brd = y; r.area = area; + + return &r; +} +``` +#### Output +``` +Length: 10.500000 +Breadth: 20.500000 +Area: 215.250000 +``` +--- +## 8. Self-Referential Structures +The self-referential structures in C are those structures that contain references to the same type as themselves i.e. they contain a member of the type pointer pointing to the same structure type. +### Example +```c +struct structure_name { + data_type member1; + data_type member2; + struct structure_name* str; +} +``` +```c +// C program to illustrate the self referential structures +#include + +// structure template +typedef struct str { + int mem1; + int mem2; + struct str* next; +}str; + +// driver code +int main() +{ + str var1 = { 1, 2, NULL }; + str var2 = { 10, 20, NULL }; + + // assigning the address of var2 to var1.next + var1.next = &var2; + + // pointer to var1 + str *ptr1 = &var1; + + // accessing var2 members using var1 + printf("var2.mem1: %d\nvar2.mem2: %d", ptr1->next->mem1, + ptr1->next->mem2); + + return 0; +} + +``` +### Output +``` +var2.mem1: 10 +var2.mem2: 20 +``` +--- + +## 9. Array of Structures in C +In C programming, the struct keyword is used to define a derived data type. Once defined, you can declare an array of struct variables, just like an array of int, float or char types is declared. An array of structures has a number of use-cases such as in storing records similar to a database table where you have each row with different data types. + +Usually, a struct type is defined at the beginning of the code so that its type can be used inside any of the functions. You can declare an array of structures and later on fill data in it or you can initialize it at the time of declaration itself. +### Initializing a Struct Array +#### Example +```c +struct book{ + char title[10]; + double price; + int pages; +}; + +struct book b[3] = { + {"Learn C", 650.50, 325}, + {"C Pointers", 175, 225}, + {"C Pearls", 250, 250} +}; + +``` +### Declaring a Struct Array +#### Example +```c +struct book b[3]; +strcpy(b[0].title, "Learn C"); +b[0].price = 650.50; +b[0].pages=325; + +strcpy(b[1].title, "C Pointers"); +b[1].price = 175; +b[1].pages=225; + +strcpy(b[2].title, "C Pearls"); +b[2].price = 250;250 +b[2].pages=325; +``` +### Reading a Struct Array +#### Example +```c +#include + +struct book{ + char title[10]; + double price; + int pages; +}; + +int main(){ + + struct book b[3]; + + strcpy(b[0].title, "Learn C"); + b[0].price = 650.50; + b[0].pages = 325; + + strcpy(b[1].title, "C Pointers"); + b[1].price = 175; + b[1].pages = 225; + + strcpy(b[2].title, "C Pearls"); + b[2].price = 250; + b[2].pages = 325; + + printf("\nList of Books:\n"); + for (int i = 0; i < 3; i++){ + printf("Title: %s \tPrice: %7.2lf \tPages: %d\n", b[i].title, b[i].price, b[i].pages); + } + + return 0; +} +``` +#### Output +``` +List of Books: +Title: Learn C Price: 650.50 Pages: 325 +Title: C Pointers Price: 175.00 Pages: 225 +Title: C Pearls Price: 250.00 Pages: 325 +``` +--- + +## 10. Difference between Structures & Unions in C +**Structures in C** is a user-defined data type available in C that allows to combining of data items of different kinds. Structures are used to represent a record. + +**Defining a structure**: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct statement is as follows: +```c +struct [structure name] + { + member definition; + member definition; + ... + member definition; + }; + + (OR) + + struct [structure name] + { + member definition; + member definition; + ... + member definition; + }structure variable declaration; +``` + +**Union in C** is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes. + +**Defining a Union**: To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows: +```c + union [union name] + { + member definition; + member definition; + ... + member definition; + }; + + (OR) + + union [union name] + { + member definition; + member definition; + ... + member definition; + }union variable declaration; +``` +### Similarities Between Structure and Union +- Both are user-defined data types used to store data of different types as a single unit. +Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field. +- Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types. +- A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter. +- **'.' operator or selection operator**, which has one of the highest precedences, is used for accessing member variables inside both the user-defined datatypes. + +### Differences between Structure and Union +#### a. Memory Allocation +- **Structures**: Each member of a structure has its own memory location. The total memory allocated is the sum of the memory required for each member. +- **Unions**: All members share the same memory location. The memory allocated is equal to the size of the largest member. Only one member can hold a value at any given time. +#### b. Accessing Members +- **Structures**: All members can be accessed simultaneously because they have separate memory. +- **Unions**: Only one member's value is valid at a time, as all members share the same memory location. +#### c. Use cases +- **Structures**: Used when multiple values are needed at the same time, such as data collections where all attributes are relevant. +- **Unions**: Useful when a variable may hold multiple data types but only one at a time, such as in cases involving memory or space constraints, like implementing a variant data type. +#### d. Initialization and Assignment +- **Structures**: Can be initialized with multiple values for all members. +- **Unions**: Can be initialized with only one member at a time. + +#### Example +Let's consider a scenario where we have a structure to represent an employee's details, which includes a union for a field that may store different types of IDs (e.g., an integer employee ID, a string for government ID, or a floating-point ID for a special category). +```c +#include +#include + +// Define a union for multiple types of IDs +union ID { + int empID; + char govID[20]; + float specialID; +}; + +// Define a structure that includes the union along with other employee details +struct Employee { + char name[50]; + int age; + float salary; + union ID id; // Union for storing one type of ID at a time + int idType; // 1 for empID, 2 for govID, 3 for specialID +}; + +int main() { + struct Employee emp; + + // Set up employee details + strcpy(emp.name, "Alice"); + emp.age = 30; + emp.salary = 75000.0; + + // Example 1: Using empID + emp.idType = 1; // Set ID type + emp.id.empID = 12345; + printf("Employee Details:\n"); + printf("Name: %s\n", emp.name); + printf("Age: %d\n", emp.age); + printf("Salary: %.2f\n", emp.salary); + if (emp.idType == 1) { + printf("Employee ID: %d\n", emp.id.empID); + } + + // Example 2: Using govID (overwrites empID) + emp.idType = 2; + strcpy(emp.id.govID, "A12345XYZ"); + printf("\nUsing Government ID:\n"); + printf("Name: %s\n", emp.name); + if (emp.idType == 2) { + printf("Government ID: %s\n", emp.id.govID); + } + + // Example 3: Using specialID (overwrites govID) + emp.idType = 3; + emp.id.specialID = 4567.89; + printf("\nUsing Special ID:\n"); + printf("Name: %s\n", emp.name); + if (emp.idType == 3) { + printf("Special ID: %.2f\n", emp.id.specialID); + } + + return 0; +} + +``` + +##### Explanation +- Employee Structure: The Employee structure contains standard information about the employee (e.g., name, age, salary) and a union, ID, for storing one type of identifier at a time. + +- ID Union: The union ID can store an integer employee ID (empID), a government ID as a string (govID), or a floating-point special ID (specialID). + +- ID Type Indicator: The idType field is used to keep track of which type of ID is currently stored in the union. + +#### Output +The output will show different details depending on which type of ID is used. Only one type of ID is active at any time because all members in the union share the same memory. +``` +Employee Details: +Name: Alice +Age: 30 +Salary: 75000.00 +Employee ID: 12345 + +Using Government ID: +Name: Alice +Government ID: A12345XYZ + +Using Special ID: +Name: Alice +Special ID: 4567.89 + +``` +This example demonstrates: + +- Structure fields (name, age, salary) remain consistent across all cases. +- Union fields show different IDs based on idType, illustrating how unions allow only one active value at a time. + +--- + +## 11. Differences between Structure and Arrays in C +### 1. Data Type of Elements +- **Structures**: Can contain elements (members) of different data types. Each member can be of any type, including other structures. +- **Arrays**: All elements must be of the same data type (e.g., all int, all float, etc.). +### 2. Memory Allocation +- **Structures**: Each member has its own memory space, and the total size is the sum of all member sizes (with potential padding for alignment). +- **Arrays**: A contiguous block of memory is allocated for all elements, where the total size is the size of one element multiplied by the number of elements. +### 3. Accessing Elements +- **Structures**: Members are accessed by name using the dot (.) operator with the structure variable. +- **Arrays**: Elements are accessed using an index inside square brackets ([]), with indices starting at 0. +### 4. Homogeneous vs. Heterogeneous Data +- **Structures**: Used for heterogeneous data, where different types of information are grouped together (e.g., name, age, and height of a person). +- **Arrays**: Used for homogeneous data, where all elements are of the same type, like a list of scores. +### 5. Usage +- **Structures**: Commonly used to represent a complex data entity, like a student, employee, or product, where various attributes are combined. +- **Arrays**: Typically used for lists, sequences, or collections of data items of the same type. + +### 6. Initialization +- **Structures**: Can initialize each member individually. +- **Arrays**: Can initialize elements in a list using {} notation. + +### Example +```c +#include + +struct Person { + char name[50]; + int age; + float height; +}; + +int main() { + struct Person people[2] = { + {"Alice", 25, 5.6}, + {"Bob", 30, 6.1} + }; + + printf("Name: %s, Age: %d, Height: %.1f\n", people[0].name, people[0].age, people[0].height); + printf("Name: %s, Age: %d, Height: %.1f\n", people[1].name, people[1].age, people[1].height); + + return 0; +} + +``` +In this example, "people" is an array of 'Person' structures, allowing you to store multiple persons and access each one's details separately. + +#### Output +``` +Name: Alice, Age: 25, Height: 5.6 +Name: Bob, Age: 30, Height: 6.1 +``` + +--- + +## 12. Uses of Structure in C +C structures are used for the following: + +- The structure can be used to define the custom data types that can be used to create some complex data types such as dates, time, complex numbers, etc. which are not present in the language. +- It can also be used in data organization where a large amount of data can be stored in different fields. +- Structures are used to create data structures such as trees, linked lists, etc. +- They can also be used for returning multiple values from a function. + +## 13. Limitations of C Structures +In C language, structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logically related data items. However, C structures also have some limitations. + +- Higher Memory Consumption: It is due to structure padding. +- No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the structure. +- Functions inside Structure: C structures do not permit functions inside the structure so we cannot provide the associated functions. +- Static Members: C Structure cannot have static members inside its body. +Construction creation in Structure: Structures in C cannot have a constructor inside Structures. + +## 14. Conclusion +In conclusion, structures in C enhance the language's capabilities to handle complex data, making it versatile for a wide range of applications. Proper use of structures not only optimizes memory management but also improves the overall design and functionality of C-based software. \ No newline at end of file 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/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 cc5663978..0bd48ed2c 100644 --- a/src/data/problemData.ts +++ b/src/data/problemData.ts @@ -1,3982 +1,3657 @@ -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.", - leetcodeUrl:"https://leetcode.com/problems/two-sum/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/container-with-most-water/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/3sum/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/valid-parentheses/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/merge-two-sorted-lists/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/next-permutation/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/search-insert-position?envType=problem-list-v2&envId=binary-search&difficulty=EASY", - 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.", - leetcodeUrl:"https://leetcode.com/problems/valid-sudoku/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/first-missing-positive/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/maximum-subarray/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/sqrtx/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/search-a-2d-matrix?envType=problem-list-v2&envId=binary-search&difficulty=MEDIUM", - 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.", - leetcodeUrl:"https://leetcode.com/problems/remove-duplicates-from-sorted-list/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/merge-two-sorted-lists/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/binary-tree-inorder-traversal/description/", - 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).", - leetcodeUrl:"https://leetcode.com/problems/symmetric-tree/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/binary-tree-level-order-traversal/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/maximum-depth-of-binary-tree/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/path-sum/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/pascals-triangle/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/best-time-to-buy-and-sell-stock/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/linked-list-cycle/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/binary-tree-preorder-traversal/description/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/binary-tree-postorder-traversal/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/remove-linked-list-elements/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/reverse-linked-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.", - leetcodeUrl:"https://leetcode.com/problems/kth-largest-element-in-an-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.", - leetcodeUrl:"https://leetcode.com/problems/contains-duplicate/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/invert-binary-tree/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/implement-queue-using-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.", - leetcodeUrl:"https://leetcode.com/problems/valid-anagram/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/missing-number/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/guess-number-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.", - leetcodeUrl:"https://leetcode.com/problems/intersection-of-two-arrays-ii/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/running-sum-of-1d-array/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/shuffle-string/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/print-first-letter-of-every-word-in-the-string3632/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card", - - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/count-leaves-in-binary-tree/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/generate-binary-numbers-1587115620/1", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/find-minimum-difference-pair/", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/geek-and-coffee-shop5721/0", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/remove-character3815/1", - 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).", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/rotate-array-by-n-elements-1587115621/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card", - - 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.", - leetcodeUrl:"https://leetcode.com/problems/longest-increasing-subsequence/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/intersection-of-two-linked-lists/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/coin-change/", - 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.", - leetcodeUrl:"https://leetcode.com/problems/sort-an-array/description/", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/inversion-of-array-1587115620/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s4231/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card", - 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.", - leetcodeUrl:"https://www.geeksforgeeks.org/problems/search-in-an-almost-sorted-array/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card", - 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.", - leetcodeUrl:"https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-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.", - leetcodeUrl:"https://leetcode.com/problems/find-all-anagrams-in-a-string/", - 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?", - leetcodeUrl:"https://leetcode.com/problems/climbing-stairs/", - 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 - `, - }, - }, - evaluateReversePolishNotation: { - title: "56. Evaluate Reverse Polish Notation", - description: - "Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero.", - examples: [ - { - input: 'tokens = ["2", "1", "+", "3", "*"]', - output: "9", - explanation: "((2 + 1) * 3) = 9", - }, - { - input: 'tokens = ["4", "13", "5", "/", "+"]', - output: "6", - explanation: "(4 + (13 / 5)) = 6", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - int evalRPN(vector& tokens) { - stack s; - for (string& token : tokens) { - if (token == "+" || token == "-" || token == "*" || token == "/") { - int b = s.top(); s.pop(); - int a = s.top(); s.pop(); - if (token == "+") s.push(a + b); - else if (token == "-") s.push(a - b); - else if (token == "*") s.push(a * b); - else if (token == "/") s.push(a / b); - } else { - s.push(stoi(token)); - } - } - return s.top(); - } - };`, - - java: ` - import java.util.Stack; - - class Solution { - public int evalRPN(String[] tokens) { - Stack stack = new Stack<>(); - for (String token : tokens) { - if ("+-*/".contains(token)) { - int b = stack.pop(); - int a = stack.pop(); - switch (token) { - case "+" -> stack.push(a + b); - case "-" -> stack.push(a - b); - case "*" -> stack.push(a * b); - case "/" -> stack.push(a / b); - } - } else { - stack.push(Integer.parseInt(token)); - } - } - return stack.pop(); - } - };`, - - python: ` - class Solution: - def hammingDistance(self, x: int, y: int) -> int: - xor_val = x ^ y - distance = 0 - while xor_val > 0: - distance += xor_val & 1 - xor_val >>= 1 - return distance - `, - }, - }, - alienDictionary: { - title: "Alien Dictionary", - description: - "In an alien language, each word is sorted lexicographically based on unknown alphabetical order. Given a list of words sorted in this alien language, determine the order of the characters. If the order is valid, return a string of characters in the correct order. If no valid ordering exists, return an empty string.", - examples: [ - { - input: "words = [\"wrt\", \"wrf\", \"er\", \"ett\", \"rftt\"]", - output: "\"wertf\"", - explanation: - "From the given list, we can infer that 'w' comes before 'e', 'r' comes before 't', 't' comes before 'f'. A possible order is 'wertf'.", - }, - { - input: "words = [\"z\", \"x\", \"z\"]", - output: "\"\"", - explanation: - "The given words form a cycle ('z' -> 'x' -> 'z'), so no valid ordering is possible, and we return an empty string.", - }, - ], - solution: { - cpp: ` - #include - using namespace std; - - class Solution { - public: - string alienOrder(vector& words) { - unordered_map> adj; - unordered_map indegree; - for (string word : words) - for (char c : word) - indegree[c] = 0; - - for (int i = 0; i < words.size() - 1; i++) { - string w1 = words[i], w2 = words[i + 1]; - int len = min(w1.size(), w2.size()); - if (w1.substr(0, len) == w2.substr(0, len) && w1.size() > w2.size()) - return ""; - - for (int j = 0; j < len; j++) { - if (w1[j] != w2[j]) { - if (adj[w1[j]].insert(w2[j]).second) - indegree[w2[j]]++; - break; - } - } - } - - queue q; - for (auto& [c, count] : indegree) - if (count == 0) q.push(c); - - string order; - while (!q.empty()) { - char c = q.front(); - q.pop(); - order += c; - for (char neighbor : adj[c]) - if (--indegree[neighbor] == 0) - q.push(neighbor); - } - return order.size() == indegree.size() ? order : ""; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public String alienOrder(String[] words) { - Map> adj = new HashMap<>(); - Map indegree = new HashMap<>(); - for (String word : words) - for (char c : word) - indegree.put(c, 0); - - for (int i = 0; i < words.length - 1; i++) { - String w1 = words[i], w2 = words[i + 1]; - int len = Math.min(w1.length(), w2.length()); - if (w1.startsWith(w2) && w1.length() > w2.length()) - return ""; - - for (int j = 0; j < len; j++) { - if (w1.charAt(j) != w2.charAt(j)) { - adj.computeIfAbsent(w1.charAt(j), k -> new HashSet<>()); - if (adj.get(w1.charAt(j)).add(w2.charAt(j))) - indegree.put(w2.charAt(j), indegree.get(w2.charAt(j)) + 1); - break; - } - } - } - - Queue queue = new LinkedList<>(); - for (Map.Entry entry : indegree.entrySet()) - if (entry.getValue() == 0) - queue.offer(entry.getKey()); - - StringBuilder order = new StringBuilder(); - while (!queue.isEmpty()) { - char c = queue.poll(); - order.append(c); - if (adj.containsKey(c)) { - for (char neighbor : adj.get(c)) - if (indegree.put(neighbor, indegree.get(neighbor) - 1) == 1) - queue.offer(neighbor); - } - } - return order.length() == indegree.size() ? order.toString() : ""; - } - };`, - - python: ` - from collections import defaultdict, deque - - class Solution: - def alienOrder(self, words: list[str]) -> str: - adj = defaultdict(set) - indegree = {char: 0 for word in words for char in word} - - for i in range(len(words) - 1): - w1, w2 = words[i], words[i + 1] - min_len = min(len(w1), len(w2)) - if w1[:min_len] == w2[:min_len] and len(w1) > len(w2): - return "" - - for j in range(min_len): - if w1[j] != w2[j]: - if w2[j] not in adj[w1[j]]: - adj[w1[j]].add(w2[j]) - indegree[w2[j]] += 1 - break - - queue = deque([c for c in indegree if indegree[c] == 0]) - order = [] - while queue: - c = queue.popleft() - order.append(c) - for neighbor in adj[c]: - indegree[neighbor] -= 1 - if indegree[neighbor] == 0: - queue.append(neighbor) - - return "".join(order) if len(order) == len(indegree) else "" - `, - }, -}, - bestMeetingPoint: { - title: "Best Meeting Point", - description: - "Given a grid where each cell represents a location in a city, find the best meeting point for all people. The best meeting point is the location that minimizes the total distance to all other people in the grid. The distance between two points is calculated using the Manhattan distance.", - examples: [ - { - input: "grid = [[1,0,0],[0,1,0],[0,0,1]]", - output: "2", - explanation: - "The best meeting point is at location (1, 1), which minimizes the sum of Manhattan distances to all people (1 + 1 + 1 = 3).", - }, - { - input: "grid = [[0,0,0],[0,1,0],[0,0,0]]", - output: "2", - explanation: - "The best meeting point is at (1, 1), which minimizes the sum of Manhattan distances to all other people in the grid.", - }, - ], - solution: { - cpp: ` - #include - #include - using namespace std; - - class Solution { - public: - int minTotalDistance(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector row, col; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (grid[i][j] == 1) { - row.push_back(i); - col.push_back(j); - } - } - } - - sort(row.begin(), row.end()); - sort(col.begin(), col.end()); - - int medianRow = row[row.size() / 2], medianCol = col[col.size() / 2]; - int distance = 0; - for (int i = 0; i < row.size(); i++) { - distance += abs(row[i] - medianRow) + abs(col[i] - medianCol); - } - - return distance; - } - };`, - - java: ` - import java.util.*; - - class Solution { - public int minTotalDistance(int[][] grid) { - List row = new ArrayList<>(); - List col = new ArrayList<>(); - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[0].length; j++) { - if (grid[i][j] == 1) { - row.add(i); - col.add(j); - } - } - } - - Collections.sort(row); - Collections.sort(col); - - int medianRow = row.get(row.size() / 2), medianCol = col.get(col.size() / 2); - int distance = 0; - for (int i = 0; i < row.size(); i++) { - distance += Math.abs(row.get(i) - medianRow) + Math.abs(col.get(i) - medianCol); - } - - return distance; - } - };`, - - python: ` - class Solution: - def minTotalDistance(self, grid: list[list[int]]) -> int: - row, col = [], [] - for i in range(len(grid)): - for j in range(len(grid[0])): - if grid[i][j] == 1: - row.append(i) - col.append(j) - - row.sort() - col.sort() - - medianRow = row[len(row) // 2] - medianCol = col[len(col) // 2] - - distance = 0 - for i in range(len(row)): - distance += abs(row[i] - medianRow) + abs(col[i] - medianCol) - - return distance - `, - }, -}, -}; - -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 + `, + }, + }, + hammingDistance: { + title: "461. Hamming Distance", + description: + "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.", + examples: [ + { + input: "x = 1, y = 4", + output: "2", + explanation: "1 in binary is 0001, and 4 in binary is 0100. They differ at two positions (2nd and 3rd from the right).", + }, + { + input: "x = 3, y = 1", + output: "1", + explanation: "3 in binary is 0011, and 1 in binary is 0001. They differ at one position (2nd from the right).", + }, + ], + solution: { + cpp: ` + #include + using namespace std; + + class Solution { + public: + int hammingDistance(int x, int y) { + int xorVal = x ^ y, distance = 0; + while (xorVal > 0) { + distance += xorVal & 1; + xorVal >>= 1; + } + return distance; + } + };`, + + java: ` + class Solution { + public int hammingDistance(int x, int y) { + int xorVal = x ^ y, distance = 0; + while (xorVal > 0) { + distance += (xorVal & 1); + xorVal >>= 1; + } + return distance; + } + };`, + + python: ` + class Solution: + def hammingDistance(self, x: int, y: int) -> int: + xor_val = x ^ y + distance = 0 + while xor_val > 0: + distance += xor_val & 1 + xor_val >>= 1 + return distance + `, + }, + }, +}; + +export default problemsData; diff --git a/src/pages/dsa-interview/index.tsx b/src/pages/dsa-interview/index.tsx index 28329f1f1..41e27a8e5 100644 --- a/src/pages/dsa-interview/index.tsx +++ b/src/pages/dsa-interview/index.tsx @@ -1,217 +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;