diff --git a/README.md b/README.md index 7343c8963..ff7723afb 100644 --- a/README.md +++ b/README.md @@ -275,17 +275,17 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - nishant4500 + + kjl98
- Nishant Dwivedi + Kajal Ahirwar
- - kjl98 + + nishant4500
- Kajal Ahirwar + Nishant Dwivedi
@@ -304,13 +304,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Mahak - - - IkkiOcean -
- Vivek Prakash -
- PradeepFSTdhane123 @@ -319,10 +312,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - PrAyAg9 + + IkkiOcean
- Prayag Thakur + Vivek Prakash
@@ -332,6 +325,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Shariq + + + AE-Hertz +
+ Abhinandan +
+ MithanshuHedau @@ -342,24 +342,24 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Mahateaa + + PrAyAg9
- Mahathi + Prayag Thakur
- - AE-Hertz + + Mahateaa
- Abhinandan + Mahathi
- - J-B-Mugundh + + monishkumardvs
- Mugundh J B + Dvs monish kumar
@@ -370,10 +370,10 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - monishkumardvs + + J-B-Mugundh
- Dvs monish kumar + Mugundh J B
@@ -386,54 +386,54 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Subashree-selvaraj + + Alpha1zln
- subashree + SHREYAS YADUVANSHI
- - Abhishek2634 + + Rashigera
- Abhishek Farshwal + Rashigera
- - KashishJuneja101003 + + Meetpidev
- Kashish Juneja + Meet Shah
- - Rashigera + + Subashree-selvaraj
- Rashigera + subashree
- - Alpha1zln + + aditiverma-21
- SHREYAS YADUVANSHI + Aditi Verma
- - Meetpidev + + KashishJuneja101003
- Meet Shah + Kashish Juneja
- - aditiverma-21 + + Abhishek2634
- Aditi Verma + Abhishek Farshwal
@@ -443,6 +443,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Kundan Rajoria + + + Mansi07sharma +
+ Mansi07sharma +
+ PavanTeja2005 @@ -457,13 +464,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Mehul Prajapati - - - Mansi07sharma -
- Mansi07sharma -
- sarthaxtic @@ -480,6 +480,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Srishti Soni + + + T-Fathima +
+ Tatheer Fathima +
+ AKSHITHA-CHILUKA @@ -501,6 +508,22 @@ Thanks to these amazing people who have contributed to the **Algo** project: SIDDHARTH A + + + shriyadindi +
+ Shriya Dindi +
+ + + + + + jvkousthub +
+ Kousthub J V +
+ sriraghavi22 @@ -508,27 +531,48 @@ Thanks to these amazing people who have contributed to the **Algo** project: sriraghavi22 + + + tanishqkolhatkar93 +
+ Tanishq Kolhatkar +
+ govindumeesala
Meesala Govindu
+ + + + khurshed07 +
+ khurshed Ansari +
+ + + + anshika-1102 +
+ anshika-1102 +
- - tanishqkolhatkar93 + + Hamza1821
- Tanishq Kolhatkar + Hamza Mubin
- - jvkousthub + + jainaryan04
- Kousthub J V + Aryan Ramesh Jain
@@ -539,24 +583,24 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - Hamza1821 + + Bhumika-00
- Hamza Mubin + Bhumika Sharma
- - anshika-1102 + + AdityaJani616
- anshika-1102 + Aditya Jani
- - khurshed07 + + Lighting-pixel
- khurshed Ansari + Ayan
@@ -575,13 +619,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Sarthak - - - AdityaJani616 -
- Aditya Jani -
- AswaniBolisetti @@ -590,26 +627,17 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - 4F24L -
- Md Afzal Mir -
- - - - shriyadindi + + alo7lika
- Shriya Dindi + alolika bhowmik
- - - - Shantnu-singh + + c4dr-me
- shantnu + c4dr-me
@@ -619,18 +647,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Kunika Makker + + - - c4dr-me -
- c4dr-me -
- - - - alo7lika + + Shantnu-singh
- alolika bhowmik + shantnu
@@ -647,20 +670,18 @@ Thanks to these amazing people who have contributed to the **Algo** project: Samarth Vaidya - - - - Lighting-pixel + + 4F24L
- Ayan + Md Afzal Mir
- - Bhumika-00 + + 17arindam
- Bhumika Sharma + Arindam
@@ -670,11 +691,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Purnima Gupta + + - - Dishaaa-T + + Bhum-ika
- Disha T + Bhumika Sharma
@@ -685,91 +708,91 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - IRFANSARI + + Kunj05
- Irfan Ansari + Kunj Chandak
- - - - shashmitha46 + + Dishaaa-T
- Shashmitha V + Disha T
- - AnushkaChouhan25 + + IRFANSARI
- Anushka Chouhan + Irfan Ansari
- - karanmaheshwari16 + + narendra-dhangar
- karanmaheshwari16 + Narendra Dhangar
+ + - - vishantrathi + + karthikyandrapu
- Vishant Rathi + Durga Karthik Yandrapu
- - tanushrigoel + + AnushkaChouhan25
- tanushrigoel + Anushka Chouhan
- - Soumya03007 + + shashmitha46
- Soumyadeep Paul + Shashmitha V
- - - - narendra-dhangar + + kaabilcoder
- Narendra Dhangar + Saurabh Kumar Sahu
- - Kunj05 + + Soumya03007
- Kunj Chandak + Soumyadeep Paul
- - Bhum-ika + + karanmaheshwari16
- Bhumika Sharma + karanmaheshwari16
+ + - - 17arindam + + vishantrathi
- Arindam + Vishant Rathi
- - T-Fathima + + tanushrigoel
- Tatheer Fathima + tanushrigoel
@@ -778,15 +801,6 @@ Thanks to these amazing people who have contributed to the **Algo** project:
Navya Sharma - - - - - - karthikyandrapu -
- Durga Karthik Yandrapu -
@@ -809,6 +823,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Vishwas M D + + ShudarsanRegmi @@ -816,6 +832,13 @@ Thanks to these amazing people who have contributed to the **Algo** project: Shudarsan Regmi + + + Shreya7tripathy +
+ Shreya Tripathy +
+ AmanPathan @@ -823,13 +846,11 @@ Thanks to these amazing people who have contributed to the **Algo** project: Ronin - - - - ADITHYA-NS + + meghanakn473
- Adithya N S + K N Meghana
@@ -840,10 +861,19 @@ Thanks to these amazing people who have contributed to the **Algo** project: - - meghanakn473 + + ADITHYA-NS
- K N Meghana + Adithya N S +
+ + + + + + ananydev +
+ Anany Dev
@@ -867,8 +897,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Shalini Bhandari - - Uvesh99 @@ -883,6 +911,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Suvadip Sana + + Ruksina01 @@ -911,8 +941,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Rahul - - PRASHANTSWAROOP001 @@ -927,6 +955,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Nishita Panchal + + Nelcy17 @@ -955,8 +985,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: PEDDIREDDY MADHAVI - - Aasthaa10 @@ -971,6 +999,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Rajat singhal + + RchtDshr @@ -999,8 +1029,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: aditya - - amiya-cyber @@ -1015,6 +1043,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Ishita Srivastava + + Mohith1490 @@ -1043,8 +1073,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Anandha-Vihari - - Lokesh11868 @@ -1059,6 +1087,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Saurbh Kumar + + Aditijainnn @@ -1087,8 +1117,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Ananya Ravikiran Vastare - - ChetanSingh14 @@ -1103,6 +1131,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Rahul Goswami + + meghanakn22 @@ -1131,8 +1161,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Kratik Mandloi - - Mahi3454 @@ -1147,6 +1175,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Mansi-Tanwar + + NishantRana07 @@ -1175,8 +1205,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Rahul7raj - - RanaJay3101 @@ -1191,6 +1219,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: RohanSai22 + + sejals23 @@ -1219,8 +1249,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Bhabuk Thapa - - aasritha-24 @@ -1235,6 +1263,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Adwitya Chakraborty + + sujal-GITHUB @@ -1263,8 +1293,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Lokesh_Bijarniya_ - - LNischala @@ -1279,6 +1307,8 @@ Thanks to these amazing people who have contributed to the **Algo** project: Krish Pathak + + jayanththalla @@ -1307,8 +1337,6 @@ Thanks to these amazing people who have contributed to the **Algo** project: Harsh - - ArchanRD diff --git a/docs/DSA-Problem-Solution/Merge_K_Sorted_Arrays.md b/docs/DSA-Problem-Solution/Merge_K_Sorted_Arrays.md new file mode 100644 index 000000000..4ca4863fd --- /dev/null +++ b/docs/DSA-Problem-Solution/Merge_K_Sorted_Arrays.md @@ -0,0 +1,100 @@ +--- +id: merge-k-sorted-arrays +title: Merge K Sorted Arrays +sidebar_label: GFG +tags: [GFG, Arrays, Sorting, Heap, DSA] +description: Given k sorted arrays with each of size k arranged in the form of a matrix of size k * k. The task is to merge them into one sorted array. +--- + +# Partition Equal Subset Sum Algorithm (GFG) + +## Description + +The **Merge K Sorted Arrays** problem is an intuitive problem based on Priority Queue where we have to merge k sorted arrays into one final sorted array. + +### Problem Definition + +Given: + +- A 2D array of integers `arr` of size k\*k. + +Objective: + +- Merge these arrays into 1 sorted array. Return the merged sorted array. + +### Algorithm Overview + +1. **Min Heap Approach**: + +- Creating a `MinHeap` and Insert the `first` element `of all the k arrays`. +- Remove the `top most` element of Minheap and `put` it in the output array. +- And insert the `next` element `from`the `array of removed` elements. +- To get the `result` the step must continue until there is no element left in the MinHeap. + +2. **Return** `result`, which is the final sorted array after merging k sorted arrays. + +### Time Complexity + +- **Time Complexity**: O(K^2\* log(K)), where insertion and deletion in a Min Heap requires log K time and for all K^2 elements it takes (K^2 \* log(K)) time +- **Space Complexity**: O(K) for the result array. + +### C++ Implementation + +```cpp +#include +using namespace std; + +//User function Template for C++ + + +class Solution +{ + public: + + class triplet{ + public: + int val; + int arr; + int i_indx; + }; + + struct cmp{ + bool operator()(triplet a , triplet b){ + return (a.val > b.val); + } + }; + //Function to merge k sorted arrays. + vector mergeKArrays(vector> arr, int k) + { + //code here + priority_queue , cmp> pq_min; + + + for(int i = 0 ; i < k ; i++){ + pq_min.push({arr[i][0] , i , 0});// pushing the first element of each array + //Heap Node => { element , array-number , indx of element in that array} + } + + vector ans; + + while(ans.size() != k*k){ + + triplet f = pq_min.top(); + pq_min.pop(); + + ans.push_back(f.val); + + int arr_indx = f.arr , i = f.i_indx; + i = i+1; + + if(i < arr[arr_indx].size()){ + pq_min.push({arr[arr_indx][i] , arr_indx , i}); //Pushing the next of that array from which popped out elements belongs to + } + } + + return ans; + } +}; + + +``` diff --git a/docs/DSA-Problem-Solution/Sliding Window Maximum.md b/docs/DSA-Problem-Solution/Sliding Window Maximum.md new file mode 100644 index 000000000..c53debfbb --- /dev/null +++ b/docs/DSA-Problem-Solution/Sliding Window Maximum.md @@ -0,0 +1,85 @@ +--- +id: sliding-window-maximum +title: Sliding Window Maximum +sidebar_label: LeetCode 239 +tags: [LeetCode , Arrays, Queue , Sliding Window , Heap (Priority Queue) , Monotonic Queue] +description: Given array of integers nums , with sliding window of size k which is moving from the very left of the array to the very right.Return the max for each sliding window. +--- + +# Sliding Window Maximum (LeetCode 239) + +## Description + +The **Sliding Window Maximum** problem involves finding the maximum value in each subarray of fixed size k that slides across array from left to right. + +### Problem Definition + +Given: + +- An array of integers `nums` of size N , with a sliding window of size K , moving from left to right , every time sliding window shifts to right by 1 position. + +Objective: + +- Return the max for each sliding window of size K. + +### Algorithm Overview + +1. **Using Deque*: + +- Create a `Deque`, `dq` of `capacity k`, that stores only useful elements of current window of k elements. +- An element is `useful` if it is in current window and is `greater` than all other `elements on right side` of it in current window. +- Process all array elements one by one and maintain dq to contain useful elements of current window and these useful elements are maintained in sorted order. +- The element at `front` of the dq is the `largest` and `element at rear/back` of dq `is` the `smallest of current window`. + +2. **Return** `result`, which is the final array containing max of each sliding window of size k. + +### Time Complexity + +- **Time Complexity**: O(N) time +- **Space Complexity**: O(K) for the deque. + +### C++ Implementation + +```cpp +#include +using namespace std; + +//User function Template for C++ + +class Solution { +public: + vector maxSlidingWindow(vector& a, int k) { + + + vector ans; int n = a.size(); + deque dq; + + int i = 0; + for(int j = 0 ; j < n ; j++){ + + while(!dq.empty() && dq.back() < a[j]){ + //pop all the elements from the back if smaller than the current element since max of that window is the current element since greater than all of them. + dq.pop_back(); + } + + dq.push_back(a[j]); // push the current element + + if(j-i+1 == k){ + ans.push_back(dq.front()); // max of that window is the deque front + + if(dq.front() == a[i]){ + // if after shifting the window by 1 step the deque front is window's front element that need to be popped b/c now window is changed ,and so window max also. + dq.pop_front(); + } + + i++; + } + + } + + return ans; + + } +}; + +``` diff --git a/docs/Stack/Balanced-Parenthesis.md b/docs/Stack/Balanced-Parenthesis.md new file mode 100644 index 000000000..67f32f18b --- /dev/null +++ b/docs/Stack/Balanced-Parenthesis.md @@ -0,0 +1,106 @@ +--- +id: balanced-parentheses +title: Balanced Parentheses +sidebar_label: Balanced Parentheses +description: "The Balanced Parentheses problem involves determining whether a given string of parentheses is valid, meaning every opening bracket has a corresponding closing bracket in the correct order." +tags: [dsa, algorithms, stack] +--- + +### Definition: +The Balanced Parentheses problem is a classic problem in computer science that checks if a string containing parentheses is valid. A string is considered valid if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. + +### Problem Statement: +Given a string `s` consisting of parentheses (i.e., `(`, `)`, `{`, `}`, `[`, `]`), determine if the input string is valid. An input string is valid if: +- Open brackets are closed by the same type of brackets. +- Open brackets are closed in the correct order. + +### Algorithm Steps: + +1. **Initialize a Stack:** Use a stack to keep track of opening parentheses. +2. **Iterate through the string:** For each character in the string: + - If it is an opening bracket, push it onto the stack. + - If it is a closing bracket, check if the stack is not empty and the top of the stack is the corresponding opening bracket; if so, pop the stack. If not, return false. +3. **Final Check:** After processing all characters, if the stack is empty, return true (all brackets are matched); otherwise, return false. + +### Steps Involved: +**1. Stack Structure:** + - Use a stack data structure to store opening brackets. + +**2. Functions:** + - `isValid(s: str) -> bool:` Checks if the parentheses in the string are balanced. + +### Time Complexity: +- The time complexity of the `isValid` function is `O(n)`, where `n` is the length of the string. This is because we scan through the string once, and each push/pop operation on the stack takes constant time. + +### Space Complexity: +- The space complexity is `O(n)` in the worst case, where all characters in the string are opening brackets, and they are stored in the stack. + +### Sample Input: +"()" "()[]{}" "(]" "([)]" "{[]}" + +### Sample Output: +true true false false true + +### Explanation of Sample: +- The input strings are evaluated for balanced parentheses. +- `()`, `()[]{}`, and `{[]}` are valid, while `(]` and `([)]` are not, due to mismatched or improperly nested brackets. + +### Python Implementation: + +```python +def isValid(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 + +# Sample Test Cases +test_cases = ["()", "()[]{}", "(]", "([)]", "{[]}"] +for case in test_cases: + print(f"{case}: {isValid(case)}") + +``` + +### C++ Implementation: +```cpp +#include +#include +#include +using namespace std; + +bool isValid(string s) { + stack stack; + unordered_map mapping = {{')', '('}, {'}', '{'}, {']', '['}}; + + for (char &c : s) { + if (mapping.count(c)) { + char top_element = stack.empty() ? '#' : stack.top(); + stack.pop(); + if (mapping[c] != top_element) { + return false; + } + } else { + stack.push(c); + } + } + + return stack.empty(); +} + +// Sample Test Cases +int main() { + string test_cases[] = {"()", "()[]{}", "(]", "([)]", "{[]}"}; + for (const string& case : test_cases) { + cout << case << ": " << (isValid(case) ? "true" : "false") << endl; + } + return 0; +} +``` diff --git a/docs/Stack/Reverse-Stack.md b/docs/Stack/Reverse-Stack.md new file mode 100644 index 000000000..d4c52edf5 --- /dev/null +++ b/docs/Stack/Reverse-Stack.md @@ -0,0 +1,123 @@ +--- +id: stack-reversal +title: Stack Reversal +sidebar_label: Stack Reversal +description: "Reversing a stack involves changing the order of elements so that the bottom becomes the top and vice versa." +tags: [dsa, algorithms, stack] +--- + +### Definition: +Reversing a stack means rearranging the elements in such a way that the last element added becomes the first element to be removed, effectively flipping the order of the stack. + +### Problem Statement: +Given a stack of integers, the task is to reverse the stack using recursion. The function should return the stack with the order of elements reversed, without using any additional data structures except for the recursion stack. + +### Algorithm Steps: + +1. **Base Case:** If the stack is empty, return from the function. +2. **Recursive Case:** + - Pop the top element from the stack. + - Call the function recursively to reverse the remaining stack. + - Insert the popped element at the bottom of the reversed stack. + +3. **Insertion at Bottom:** A helper function is required to insert an element at the bottom of the stack. + +### Steps Involved: +1. **Function `reverseStack`:** This function is responsible for reversing the stack recursively. + + *Step 1.1:* Check if the stack is empty; if it is, return. + *Step 1.2:* Pop the top element and store it. + *Step 1.3:* Recursively call `reverseStack` for the remaining stack. + +2. **Function `insertAtBottom`:** This function inserts an element at the bottom of the stack. + + *Step 2.1:* Check if the stack is empty; if it is, push the element. + *Step 2.2:* Pop the top element, call `insertAtBottom` recursively, and push the popped element back. + +3. **Main Function:** The main function initializes the stack, calls `reverseStack`, and displays the reversed stack. + +### Time Complexity: +- The time complexity of this solution is `O(n)`, where `n` is the number of elements in the stack. This is because each element is processed a constant number of times (popped and inserted). + +### Sample Input: +Stack: [1, 2, 3, 4, 5] + +### Sample Output: +Stack after reversal: [5, 4, 3, 2, 1] + +### Explanation of Sample: +- The stack is reversed so that the top element (5) becomes the bottom, and the bottom element (1) becomes the top. + +### C++ Implementation: +```cpp +#include +#include +using namespace std; + +// Function to insert an element at the bottom of the stack +void insertAtBottom(stack& s, int x) { + if (s.empty()) { + s.push(x); + } else { + int temp = s.top(); + s.pop(); + insertAtBottom(s, x); + s.push(temp); + } +} + +// Function to reverse the stack +void reverseStack(stack& s) { + if (!s.empty()) { + int x = s.top(); + s.pop(); + reverseStack(s); + insertAtBottom(s, x); + } +} + +int main() { + stack s; + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + + reverseStack(s); + + cout << "Stack after reversal: "; + while (!s.empty()) { + cout << s.top() << " "; + s.pop(); + } + return 0; +} +``` +### Python Implementation: +```py +def insert_at_bottom(stack, x): + """Helper function to insert an element at the bottom of the stack.""" + if not stack: + stack.append(x) + else: + temp = stack.pop() + insert_at_bottom(stack, x) + stack.append(temp) + +def reverse_stack(stack): + """Function to reverse the stack using recursion.""" + if stack: + x = stack.pop() + reverse_stack(stack) + insert_at_bottom(stack, x) + +if __name__ == "__main__": + # Sample stack + stack = [1, 2, 3, 4, 5] + + reverse_stack(stack) + + print("Stack after reversal:", stack) + +``` diff --git a/docs/Stack/Stack-permutation.md b/docs/Stack/Stack-permutation.md index 4e0762b49..a04a99632 100644 --- a/docs/Stack/Stack-permutation.md +++ b/docs/Stack/Stack-permutation.md @@ -101,3 +101,33 @@ int main() { ``` +### Python Implementation: +```python +def is_stack_permutation(input, output): + stack = [] + j = 0 + n = len(input) + + for i in range(n): + # Push the current element of the input array to the stack + stack.append(input[i]) + + # Check if the top of the stack matches the output array + while stack and stack[-1] == output[j]: + stack.pop() + j += 1 + + # If j has reached n, then output is a valid permutation + return j == n + +if __name__ == "__main__": + input = [1, 2, 3] + output = [2, 1, 3] + + if is_stack_permutation(input, output): + print("Yes, it is a stack permutation") + else: + print("No, it is not a stack permutation") +``` + + diff --git a/docs/Stack/Stock-span.md b/docs/Stack/Stock-span.md new file mode 100644 index 000000000..519c9a992 --- /dev/null +++ b/docs/Stack/Stock-span.md @@ -0,0 +1,117 @@ +--- +id: stock-span +title: Stock Span Problem +sidebar_label: Stock Span Problem +description: "The Stock Span Problem is a financial problem that calculates the span of stock's price on a given day." +tags: [dsa, algorithms, stack] +--- + +### Definition: +The Stock Span Problem is defined as follows: Given a list of daily stock prices, the span of the stock's price on a given day is defined as the maximum number of consecutive days (including the current day) for which the price of the stock was less than or equal to the price on the given day. + +### Problem Statement: +You are given an array of stock prices, where each element represents the stock price on a particular day. Your task is to compute an array of the same size, where each element at index `i` contains the span of the stock price on day `i`. + +The span of the stock price is defined as the number of consecutive days (including the current day) for which the stock price was less than or equal to the price on day `i`. + +### Algorithm Steps: + +1. Initialize an empty stack to hold indices of the days. +2. Traverse the array of stock prices from left to right. +3. For each day, while the stack is not empty and the price of the current day is greater than the price of the day at the index on the top of the stack, pop from the stack. +4. If the stack is empty, it means the current price is greater than all previous prices, so the span is the current index + 1. If the stack is not empty, the span is the difference between the current index and the index at the top of the stack. +5. Push the current index onto the stack. +6. Repeat the above steps for all stock prices. + +### Steps Involved: +1. **Input Array:** The program receives an array of stock prices. +2. **Function `calculateStockSpan`:** This function calculates the span for each day. + + *Step 2.1:* A `stack` is initialized to store indices of the stock prices. + + *Step 2.2:* An array `span[]` is initialized to store the span of each day. +3. **Iterate through `prices`:** For each price in the stock prices: + + *Step 3.1:* While the stack is not empty and the current price is greater than the price at the index of the stack's top, the top index is popped from the stack. + + *Step 3.2:* If the stack is empty, the span is the current index + 1; otherwise, it's the difference between the current index and the index at the top of the stack. + +4. **Push the current index:** After calculating the span for the current price, push the index onto the stack. +5. **Return the `span[]`:** After processing all prices, return the computed spans. + +### Time Complexity: +- The time complexity of this solution is `O(n)`, where `n` is the number of stock prices. Each price is pushed and popped from the stack at most once. + +### Sample Input: +```cpp +int prices[] = {100, 80, 60, 70, 60, 75, 85}; +int n = sizeof(prices) / sizeof(prices[0]); +``` +### Sample Output: +Span array: [1, 1, 1, 2, 1, 4, 6] + +### C++ Implementation: +```cpp +#include +#include +using namespace std; + +// Function to calculate stock span values +void calculateStockSpan(int prices[], int span[], int n) { + stack st; + st.push(0); // First day's price always has a span of 1 + span[0] = 1; + + for (int i = 1; i < n; i++) { + // Pop elements from the stack while the current price is greater + while (!st.empty() && prices[st.top()] <= prices[i]) { + st.pop(); + } + + // If the stack is empty, current price is greater than all previous prices + span[i] = st.empty() ? i + 1 : i - st.top(); + st.push(i); + } +} +int main() { + int prices[] = {100, 80, 60, 70, 60, 75, 85}; + int n = sizeof(prices) / sizeof(prices[0]); + int span[n]; + + calculateStockSpan(prices, span, n); + + cout << "Span array: "; + for (int i = 0; i < n; i++) { + cout << span[i] << " "; + } + cout << endl; + + return 0; +} +``` +### Python Implementation: +```python +def calculate_stock_span(prices): + n = len(prices) + span = [0] * n + stack = [] + + for i in range(n): + # Calculate span for the current price + while stack and prices[stack[-1]] <= prices[i]: + stack.pop() + + # If the stack is empty, current price is greater than all previous prices + span[i] = i + 1 if not stack else i - stack[-1] + + # Push the current index onto the stack + stack.append(i) + + return span + +if __name__ == "__main__": + prices = [100, 80, 60, 70, 60, 75, 85] + span = calculate_stock_span(prices) + + print("Span array:", span) +``` diff --git a/docs/Stack/String_Reversal.md b/docs/Stack/String_Reversal.md new file mode 100644 index 000000000..39f4da23d --- /dev/null +++ b/docs/Stack/String_Reversal.md @@ -0,0 +1,71 @@ +--- +id: string-reversal +title: String Reversal +sidebar_label: String Reversal +description: "This program reverses a given string by pushing its characters onto a stack and then popping them back into the string." +tags: [dsa, algorithms, stack] +--- + +## Problem Statement: +Write a program to reverse a string using stack data structure. + +## Defination +The program reverses a given string using the stack data structure. The program reads a string input from the user, pushes each character onto a stack, and then pops the characters from the stack to display the string in reverse order. + + +## Algorithm Steps: + +This C++ program uses a stack data structure to reverse a string, demonstrating fundamental stack operations like push and pop. The stack is implemented using a structure that holds an array for the items (characters of the string) and an integer top that tracks the position of the top element. Several helper functions manage the stack, including initialize to set up an empty stack, + +```isFull``` to check if the stack has reached its capacity, + +```isEmpty``` to check if the stack is empty, + +```push``` to add characters to the stack, and + +```pop``` to remove characters from it. + +The main logic of the program lies in the ```reverseString``` function. + +The function first pushes each character of the input string onto the stack. Since a stack operates on a Last-In-First-Out (LIFO) principle, when the characters are popped back off the stack and placed into the string, they are inserted in reverse order. Thus, the string is reversed by the end of the process. The program reads the string from the user, uses the stack to reverse it, and then prints the reversed string. + +## Time Complexity +The time complexity of the `reverseString` function is `O(n)`, where n is the length of the input string. This is because the function first iterates through each character in the string to push it onto the stack, taking O(n) time. Then, in a second loop, it pops each character from the stack and places it back into the string, also taking `O(n)` time. Since both loops run sequentially, the overall time complexity is `O(n) + O(n)` = `O(n)`. + +## Space Complexity +The space complexity of the `reverseString` function is `O(n)` due to the use of a stack to store each character of the input string. The stack requires `O(n)` additional space since it stores all characters temporarily until they are popped back into the string. While the input string itself takes `O(n)` space, it is not considered extra memory allocation by the function, as it is passed by reference. Thus, the dominant additional space usage is from the stack, resulting in an overall space complexity of `O(n)`. + + +## Sample Input: +Enter a string (max 100 characters): My Contribution + +## Sample Output: +Reversed string: noitubirtnoC yM + +## C++ Implementation: + +```cpp +#include +#include +#include + +void reverseString(std::string &str) { + std::stack stack; + for (char ch : str) { + stack.push(ch); + } + for (size_t i = 0; i < str.length(); i++) { + str[i] = stack.top(); + stack.pop(); + } +} + +int main() { + std::string str; + std::cout << "Enter a string (max 100 characters): "; + std::getline(std::cin, str); + reverseString(str); + std::cout << "Reversed string: " << str << std::endl; + return 0; +} +``` diff --git a/docs/algorithms/backtracking-algorithms/Bron-Kerbosch-Algorithm.md b/docs/algorithms/backtracking-algorithms/Bron-Kerbosch-Algorithm.md new file mode 100644 index 000000000..2f108a363 --- /dev/null +++ b/docs/algorithms/backtracking-algorithms/Bron-Kerbosch-Algorithm.md @@ -0,0 +1,163 @@ +--- +id: Bron-Kerbosch-Algorithm +sidebar_position: 3 +title: Bron-Kerbosch Algorithm +sidebar_label: Bron-Kerbosch Algorithm +description: "The Bron-Kerbosch algorithm is a backtracking algorithm used to find all maximal cliques in an undirected graph. Known for its efficiency, especially on sparse graphs, it is widely applied in social network analysis, bioinformatics, and computational chemistry. The algorithm can be optimized with pivoting to reduce recursive calls and improve performance." +tags: [graph-theory, bron-kerbosch, maximal-clique, backtracking, clique-detection, pivoting, optimization] +--- + +The **Bron-Kerbosch algorithm** is a backtracking algorithm used to find all maximal cliques in an undirected graph. A clique is a subset of vertices, all of which are adjacent to each other, and a maximal clique is a clique that cannot be extended by including an adjacent vertex. This algorithm is known for its recursive nature and efficiency in finding cliques in graphs without needing to search through all vertex subsets. + +## Definition + +The Bron-Kerbosch algorithm is a **recursive backtracking algorithm** that enumerates all maximal cliques in an undirected graph. By maintaining three sets during recursion, the algorithm explores all potential cliques and ensures that each maximal clique is discovered only once. + +## Characteristics + +- **Exactness**: The algorithm is exact and produces all maximal cliques without duplication. +- **Recursiveness**: It uses recursive backtracking with sets of vertices to manage the state at each step. +- **Efficiency**: The algorithm is highly efficient, especially for sparse graphs. +- **Pivoting**: The pivoting technique can be used to reduce the number of recursive calls, optimizing performance by reducing the search space. + +## Time Complexity + +The time complexity of the Bron-Kerbosch algorithm varies depending on the implementation: + +- **Without pivoting**: , where \(n\) is the number of vertices. +- **With pivoting**: The worst-case complexity remains `O(3^(n/3))`, but pivoting reduces the number of recursive calls in practice, making the algorithm faster on average. + +## Space Complexity + +The space complexity is **O(n + E)**, where \(n\) is the number of vertices and \(E\) is the number of edges. This is primarily due to storing the adjacency list or matrix and maintaining three sets (R, P, and X) in each recursive call. + +## Approach + +The Bron-Kerbosch algorithm follows these steps: + +1. **Initialize three sets**: + - **R**: The growing clique being constructed. + - **P**: The set of vertices that can still be added to the current clique. + - **X**: The set of vertices that have already been considered for the current clique. + +2. **Recursive Backtracking**: + - At each step, choose a vertex from \(P\) and add it to \(R\), forming a new potential clique. + - Recur with updated sets: + - **R** includes the chosen vertex. + - **P** is restricted to vertices adjacent to the new vertex. + - **X** is updated to avoid revisiting vertices. + +3. **Base Case**: + - If both \(P\) and \(X\) are empty, \(R\) is a maximal clique. + +4. **Pivot Optimization (Optional)**: + - Choose a pivot vertex to minimize the number of recursive calls by excluding vertices that are unlikely to form new cliques. + +## C++ Implementation + +```cpp title="Bron-Kerbosch Algorithm in C++" +#include +#include +#include +using namespace std; + +void bronKerbosch(set R, set P, set X, const vector>& graph) { + if (P.empty() && X.empty()) { + // Output the maximal clique found + cout << "Maximal Clique: "; + for (int v : R) cout << v << " "; + cout << endl; + return; + } + + set P_copy = P; + for (int v : P_copy) { + set newR = R, newP, newX; + newR.insert(v); + + for (int w : graph[v]) { + if (P.find(w) != P.end()) newP.insert(w); + if (X.find(w) != X.end()) newX.insert(w); + } + + bronKerbosch(newR, newP, newX, graph); + + P.erase(v); + X.insert(v); + } +} + +int main() { + int n = 5; // Number of vertices + vector> graph(n); + + // Define graph edges (example) + graph[0] = {1, 2}; + graph[1] = {0, 2, 3}; + graph[2] = {0, 1, 4}; + graph[3] = {1, 4}; + graph[4] = {2, 3}; + + bronKerbosch({}, {0, 1, 2, 3, 4}, {}, graph); + + return 0; +} +``` + +## Java Implementation + +```java title="Bron-Kerbosch Algorithm in Java" +import java.util.HashSet; +import java.util.Set; + +public class BronKerbosch { + public static void bronKerbosch(Set R, Set P, Set X, Set[] graph) { + if (P.isEmpty() && X.isEmpty()) { + System.out.println("Maximal Clique: " + R); + return; + } + + Set P_copy = new HashSet<>(P); + for (Integer v : P_copy) { + Set newR = new HashSet<>(R); + newR.add(v); + + Set newP = new HashSet<>(); + Set newX = new HashSet<>(); + for (Integer w : graph[v]) { + if (P.contains(w)) newP.add(w); + if (X.contains(w)) newX.add(w); + } + + bronKerbosch(newR, newP, newX, graph); + + P.remove(v); + X.add(v); + } + } + + public static void main(String[] args) { + int n = 5; // Number of vertices + Set[] graph = new Set[n]; + for (int i = 0; i < n; i++) graph[i] = new HashSet<>(); + + // Define graph edges (example) + graph[0].add(1); graph[0].add(2); + graph[1].add(0); graph[1].add(2); graph[1].add(3); + graph[2].add(0); graph[2].add(1); graph[2].add(4); + graph[3].add(1); graph[3].add(4); + graph[4].add(2); graph[4].add(3); + + Set R = new HashSet<>(); + Set P = new HashSet<>(); + for (int i = 0; i < n; i++) P.add(i); + Set X = new HashSet<>(); + + bronKerbosch(R, P, X, graph); + } +} +``` + +## Summary + +The Bron-Kerbosch algorithm efficiently finds all maximal cliques in a graph, making it useful in various fields such as social network analysis and bioinformatics. With optional pivoting, it is adaptable to dense and sparse graphs alike, offering high-performance clique detection for applications requiring maximal clique identification. diff --git a/docs/backtracking algorithms/N-QueensProblem.md b/docs/backtracking algorithms/N-QueensProblem.md new file mode 100644 index 000000000..33535c0aa --- /dev/null +++ b/docs/backtracking algorithms/N-QueensProblem.md @@ -0,0 +1,149 @@ +--- +id: n-queens-problem +title: N-Queens Problem in C +sidebar_label: Backtracking algorithms +sidebar_position: 1 +description: "The N-Queens Problem is a classic problem where the objective is to place `N` queens on an `N x N` chessboard such that no two queens can attack each other. A queen can attack any other piece in the same row, column, or diagonal, making it challenging to place all `N` queens without conflict." +tags: [backtracking, algorithms] +--- + +## Problem Definition + +Given: +- An integer `N`, representing the size of the chessboard (`N x N`) and the number of queens. + +Objective: +- Place `N` queens on the chessboard such that no two queens threaten each other. + +## Constraints +- Queens can move horizontally, vertically, or diagonally, which means no two queens can share the same row, column, or diagonal. + +## Algorithm Overview + +The **backtracking** approach is used to solve the N-Queens problem. The idea is to place queens one by one in different columns, starting from the first row. Whenever a queen is placed, the solution checks whether the position is safe. If so, it moves on to the next row. If no safe column is found, it backtracks and tries a different column. + +### Steps: +1. Start by placing a queen in the first row. +2. For each row, try placing a queen in each column (one by one). +3. Check if placing a queen is safe (no other queens can attack it). +4. If safe, place the queen and move to the next row. +5. If a position is not safe or leads to no solution, backtrack by removing the queen and trying a different column. +6. Repeat until all queens are placed or no solution is found. + +### Functions: +1. **isSafe(row, col)**: Checks if placing a queen at `(row, col)` is safe. +2. **solveNQueens(row)**: Recursively places queens row by row and uses backtracking when necessary. +3. **printSolution()**: Displays a valid chessboard configuration. + +## Time Complexity + +The time complexity for solving the N-Queens problem using backtracking is `O(N!)`, since we try placing a queen in every column of each row and backtrack if needed. + +## Program: +```c +#include +#include + +#define N 8 // Change this value for different N + +// Function to print the solution +void printSolution(int board[N][N]) +{ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + printf("%d ", board[i][j]); + } + printf("\n"); + } +} + +// Function to check if placing a queen is safe +bool isSafe(int board[N][N], int row, int col) +{ + int i, j; + + // Check this row on the left side + for (i = 0; i < col; i++) + { + if (board[row][i] == 1) + { + return false; + } + } + + // Check the upper diagonal on the left side + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) + { + if (board[i][j] == 1) + { + return false; + } + } + + // Check the lower diagonal on the left side + for (i = row, j = col; i < N && j >= 0; i++, j--) + { + if (board[i][j] == 1) + { + return false; + } + } + + return true; +} + +// Function to solve the N-Queens problem using backtracking +bool solveNQueensUtil(int board[N][N], int col) +{ + // Base case: If all queens are placed, return true + if (col >= N) + { + return true; + } + + // Try placing this queen in all rows of the current column + for (int i = 0; i < N; i++) + { + if (isSafe(board, i, col)) + { + // Place the queen + board[i][col] = 1; + + // Recur to place the rest of the queens + if (solveNQueensUtil(board, col + 1)) + { + return true; + } + + // If placing queen doesn't lead to a solution, backtrack + board[i][col] = 0; + } + } + + return false; // If no placement is possible, return false +} + +// Function to solve the N-Queens problem +bool solveNQueens() +{ + int board[N][N] = {0}; + + if (!solveNQueensUtil(board, 0)) + { + printf("Solution does not exist\n"); + return false; + } + + printSolution(board); + return true; +} + +int main() +{ + solveNQueens(); + return 0; +} + +``` diff --git a/docs/binary-search/binary-search_rotated-sorted-array.md b/docs/binary-search/binary-search_rotated-sorted-array.md new file mode 100644 index 000000000..73dfae2a7 --- /dev/null +++ b/docs/binary-search/binary-search_rotated-sorted-array.md @@ -0,0 +1,323 @@ +--- +id: binary-search-rotated-sorted-array +sidebar_position: 5 +title: Binary Search Rotated sort array +sidebar_label: Binary Search +description: "In this blog post, we'll dive into the rotated array approach with binary search algorithm, a fundamental technique in computer science for efficiently finding an element in a sorted array." +tags: [dsa, algorithms, binary search] +--- + + +# Binary Search in Rotated Sorted Array + +## Problem Description + +Given a sorted array that has been rotated at some pivot point, implement a function to find a target element in the array. The function should return the index of the target element if found, or -1 if not found. + +A rotated sorted array is an array that was originally sorted in ascending order but has been rotated around a pivot point. For example: +- Original sorted array: `[1, 2, 3, 4, 5, 6, 7]` +- After rotation at index 3: `[4, 5, 6, 7, 1, 2, 3]` + +## Time Complexity +- **Time Complexity**: O(log n) +- **Space Complexity**: O(1) + +## Algorithm Overview + +The algorithm uses a modified binary search approach that takes into account the rotation of the array. The key insight is that at least one half of the array (either left or right) will always be sorted. + +### Key Steps: + +1. Initialize two pointers: + - `left` pointing to the start of array (index 0) + - `right` pointing to the end of array (index n-1) + +2. While `left <= right`: + - Calculate middle point: `mid = (left + right) / 2` + - If target is found at mid, return mid + +3. Check which half of the array is sorted: + - If left half is sorted (`arr[left] <= arr[mid]`): + - Check if target lies in the left half + - If yes, search left half + - If no, search right half + - If right half is sorted: + - Check if target lies in the right half + - If yes, search right half + - If no, search left half + +4. If element is not found, return -1 + +## Implementation + +```python +def search(nums: list[int], target: int) -> int: + if not nums: + return -1 + + left, right = 0, len(nums) - 1 + + while left <= right: + mid = (left + right) // 2 + + # Found target + if nums[mid] == target: + return mid + + # Check if left half is sorted + if nums[left] <= nums[mid]: + # Check if target is in left half + if nums[left] <= target <= nums[mid]: + right = mid - 1 + else: + left = mid + 1 + # Right half is sorted + else: + # Check if target is in right half + if nums[mid] <= target <= nums[right]: + left = mid + 1 + else: + right = mid - 1 + + return -1 +``` + +## Example Usage + +```python +# Example 1: Regular case +arr = [4, 5, 6, 7, 0, 1, 2] +target = 0 +result = search(arr, target) # Returns 4 + +# Example 2: Target not found +arr = [4, 5, 6, 7, 0, 1, 2] +target = 3 +result = search(arr, target) # Returns -1 + +# Example 3: Array with single element +arr = [1] +target = 1 +result = search(arr, target) # Returns 0 +``` + +## Edge Cases to Consider + +1. Empty array +2. Array with single element +3. Target not present in array +4. Duplicate elements (not handled in basic implementation) +5. Array not rotated (regular sorted array) +6. Array rotated n times (back to original position) +7. Target at the first or last position + +## Common Pitfalls + +1. **Not Handling Empty Arrays**: Always check if the input array is empty before processing. +2. **Integer Overflow**: When calculating mid point, use `left + (right - left) // 2` instead of `(left + right) // 2` to prevent integer overflow in some languages. +3. **Incorrect Boundary Conditions**: Be careful with the conditions when checking if target lies in sorted portion. +4. **Duplicate Elements**: The basic implementation assumes all elements are unique. Handling duplicates requires additional logic. + +## Applications + +1. **Database Indexing**: When indexes are partially sorted or reorganized +2. **Circular Buffer Search**: Finding elements in circular buffer data structures +3. **Version Control**: Finding specific versions in circular version histories +4. **Resource Allocation**: Finding available slots in circular resource allocation systems + +## Related Problems + +1. Find Minimum in Rotated Sorted Array +2. Search in Rotated Sorted Array II (with duplicates) +3. Find Rotation Count in Rotated Sorted Array +4. Find Maximum in Rotated Sorted Array + +## Testing Guide + +### Test Cases to Cover: + +1. Basic cases: + ```python + assert search([4, 5, 6, 7, 0, 1, 2], 0) == 4 + assert search([4, 5, 6, 7, 0, 1, 2], 3) == -1 + ``` + +2. Edge cases: + ```python + assert search([], 5) == -1 + assert search([1], 1) == 0 + assert search([1], 0) == -1 + ``` + +3. Rotation variations: + ```python + assert search([1, 2, 3, 4, 5], 4) == 3 # No rotation + assert search([2, 3, 4, 5, 1], 1) == 4 # Rotated once + assert search([5, 1, 2, 3, 4], 5) == 0 # Target at start + ``` + +## Performance Optimization Tips + +1. Use binary search variant that avoids integer overflow +2. Consider adding early termination conditions for obvious cases +3. If dealing with large arrays, consider parallelization for multiple searches +4. Cache frequently searched values if appropriate for your use case + +## Additional Resources + +1. Time Complexity Analysis: [Master Theorem](https://en.wikipedia.org/wiki/Master_theorem_(analysis_of_algorithms)) +2. Related Reading: Binary Search Trees and Their Applications +3. Practice Problems: LeetCode #33, #81, #153 +4. Advanced Topics: Variants with duplicates, Finding multiple occurrences + +## Practice Problems Collection + +### Essential Problems + +| Problem | Difficulty | LeetCode Link | Description | Key Concepts | +|---------|------------|---------------|-------------|--------------| +| Search in Rotated Sorted Array | Medium | [LC-33](https://leetcode.com/problems/search-in-rotated-sorted-array/) | Find target in rotated array with unique elements | Basic rotated array search | +| Search in Rotated Sorted Array II | Medium | [LC-81](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | Find target in rotated array with duplicates | Handling duplicates | +| Find Minimum in Rotated Sorted Array | Medium | [LC-153](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | Find minimum element in rotated array | Modified binary search | +| Find Minimum in Rotated Sorted Array II | Hard | [LC-154](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | Find minimum in rotated array with duplicates | Complex duplicate handling | + +### Related Binary Search Problems + +| Problem | Difficulty | LeetCode Link | Description | Key Concepts | +|---------|------------|---------------|-------------|--------------| +| Peak Element | Medium | [LC-162](https://leetcode.com/problems/find-peak-element/) | Find any peak element in array | Binary search on unsorted array | +| Find First and Last Position | Medium | [LC-34](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) | Find range of target element | Modified binary search | +| Single Element in Sorted Array | Medium | [LC-540](https://leetcode.com/problems/single-element-in-a-sorted-array/) | Find element that appears once | Binary search with parity | +| Search Insert Position | Easy | [LC-35](https://leetcode.com/problems/search-insert-position/) | Find insertion position | Basic binary search | + +### Problem-Solving Patterns + +#### Pattern 1: Basic Rotated Array Search +```python +def findPivot(nums): + left, right = 0, len(nums) - 1 + while left < right: + mid = left + (right - left) // 2 + if nums[mid] > nums[right]: + left = mid + 1 + else: + right = mid + return left +``` + +#### Pattern 2: Handling Duplicates +```python +def searchWithDuplicates(nums, target): + left, right = 0, len(nums) - 1 + while left <= right: + # Skip duplicates from left + while left < right and nums[left] == nums[left + 1]: + left += 1 + # Skip duplicates from right + while left < right and nums[right] == nums[right - 1]: + right -= 1 + # Regular binary search logic follows... +``` + +#### Pattern 3: Finding Range +```python +def searchRange(nums, target): + def findBound(nums, target, isFirst): + left, right = 0, len(nums) - 1 + while left <= right: + mid = left + (right - left) // 2 + if nums[mid] == target: + if isFirst: + if mid == left or nums[mid-1] < target: + return mid + right = mid - 1 + else: + if mid == right or nums[mid+1] > target: + return mid + left = mid + 1 + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return -1 + + return [findBound(nums, target, True), + findBound(nums, target, False)] +``` + +### Problem-Solving Tips + +1. **For Basic Rotated Array**: + - Always check which half is sorted first + - Compare target with endpoints of sorted half + - Move to appropriate half based on comparison + +2. **For Duplicate Elements**: + - Skip duplicate elements at boundaries + - Consider worst-case time complexity becomes O(n) + - Handle edge cases where all elements are same + +3. **For Finding Ranges**: + - Use two binary searches for left and right bounds + - Modify condition to find first/last occurrence + - Handle cases where element doesn't exist + +### Common Patterns and Templates + +#### Template 1: Basic Binary Search in Rotated Array +```python +def search(nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + + while left <= right: + mid = left + (right - left) // 2 + + if nums[mid] == target: + return mid + + # Check if left half is sorted + if nums[left] <= nums[mid]: + if nums[left] <= target <= nums[mid]: + right = mid - 1 + else: + left = mid + 1 + # Right half is sorted + else: + if nums[mid] <= target <= nums[right]: + left = mid + 1 + else: + right = mid - 1 + + return -1 +``` + +#### Template 2: Binary Search with Duplicates +```python +def searchWithDuplicates(nums: List[int], target: int) -> bool: + left, right = 0, len(nums) - 1 + + while left <= right: + # Handle duplicates + while left < right and nums[left] == nums[left + 1]: + left += 1 + while left < right and nums[right] == nums[right - 1]: + right -= 1 + + mid = left + (right - left) // 2 + + if nums[mid] == target: + return True + + if nums[left] <= nums[mid]: + if nums[left] <= target <= nums[mid]: + right = mid - 1 + else: + left = mid + 1 + else: + if nums[mid] <= target <= nums[right]: + left = mid + 1 + else: + right = mid - 1 + + return False +``` \ No newline at end of file diff --git a/docs/bit-manipulation/clear-ith-Bit.md b/docs/bit-manipulation/clear-ith-Bit.md new file mode 100644 index 000000000..be67f3cbd --- /dev/null +++ b/docs/bit-manipulation/clear-ith-Bit.md @@ -0,0 +1,56 @@ +--- +id: clear-ith-bit +tittle: Clear ith Bit +sidebar-level: Clear ith Bit +sidebar-position: 2 +Description: Clearing the i-th bit in a number is a nifty bit manipulation technique. This involves setting the i-th bit to 0, leaving all other bits unchanged. +tags: [dsa, bit manipulation, clear bits] +--- + +# Description + +Clearing the i-th bit in a number is a common bit manipulation technique. This operation involves setting the i-th bit to 0 while leaving all other bits unchanged. + +## Steps to Clear the i-th Bit +**1. Create a Mask:** Create a number that has all bits set to 1 except for the i-th bit, which is set to 0. + +**2. AND Operation:** Perform a bitwise AND between the original number and the mask. This will clear the i-th bit while keeping all other bits unchanged. + +## Formula +> `mask =∼ (1<<𝑖)` + +> `result = num&mask` + + +# Code in Java +```java +import java.util.*; + +public class clearIthBit { + + public static int clearIthBit(int n, int i) { + int bitMask = ~(1< tuple[list[int], float]: + """Ant colony optimization main function for TSP.""" + cities_num = len(cities) + pheromone = [[1.0] * cities_num] * cities_num + + best_path: list[int] = [] + best_distance = float("inf") + for _ in range(iterations_num): + ants_route = [] + for _ in range(ants_num): + unvisited_cities = copy.deepcopy(cities) + current_city = {next(iter(cities.keys())): next(iter(cities.values()))} + del unvisited_cities[next(iter(current_city.keys()))] + ant_route = [next(iter(current_city.keys()))] + while unvisited_cities: + current_city, unvisited_cities = city_select( + pheromone, current_city, unvisited_cities, alpha, beta + ) + ant_route.append(next(iter(current_city.keys()))) + ant_route.append(0) + ants_route.append(ant_route) + + pheromone, best_path, best_distance = pheromone_update( + pheromone, + cities, + pheromone_evaporation, + ants_route, + q, + best_path, + best_distance, + ) + return best_path, best_distance + + +def distance(city1: list[int], city2: list[int]) -> float: + """Calculate the Euclidean distance between two cities.""" + return (((city1[0] - city2[0]) ** 2) + ((city1[1] - city2[1]) ** 2)) ** 0.5 + + +def pheromone_update( + pheromone: list[list[float]], + cities: dict[int, list[int]], + pheromone_evaporation: float, + ants_route: list[list[int]], + q: float, + best_path: list[int], + best_distance: float, +) -> tuple[list[list[float]], list[int], float]: + """Update pheromones on routes and determine the best route.""" + for a in range(len(cities)): + for b in range(len(cities)): + pheromone[a][b] *= pheromone_evaporation + for ant_route in ants_route: + total_distance = 0.0 + for i in range(len(ant_route) - 1): + total_distance += distance(cities[ant_route[i]], cities[ant_route[i + 1]]) + delta_pheromone = q / total_distance + for i in range(len(ant_route) - 1): + pheromone[ant_route[i]][ant_route[i + 1]] += delta_pheromone + pheromone[ant_route[i + 1]][ant_route[i]] = pheromone[ant_route[i]][ + ant_route[i + 1] + ] + + if total_distance < best_distance: + best_path = ant_route + best_distance = total_distance + + return pheromone, best_path, best_distance + + +def city_select( + pheromone: list[list[float]], + current_city: dict[int, list[int]], + unvisited_cities: dict[int, list[int]], + alpha: float, + beta: float, +) -> tuple[dict[int, list[int]], dict[int, list[int]]]: + """Select the next city based on pheromone levels and distances.""" + probabilities = [] + for city in unvisited_cities: + city_distance = distance( + unvisited_cities[city], next(iter(current_city.values())) + ) + probability = (pheromone[city][next(iter(current_city.keys()))] ** alpha) * ( + (1 / city_distance) ** beta + ) + probabilities.append(probability) + + chosen_city_i = random.choices( + list(unvisited_cities.keys()), weights=probabilities + )[0] + chosen_city = {chosen_city_i: unvisited_cities[chosen_city_i]} + del unvisited_cities[next(iter(chosen_city.keys()))] + return chosen_city, unvisited_cities + + +if __name__ == "__main__": + best_path, best_distance = main( + cities=cities, + ants_num=10, + iterations_num=20, + pheromone_evaporation=0.7, + alpha=1.0, + beta=5.0, + q=10, + ) + + print(f"{best_path = }") + print(f"{best_distance = }") + +``` + +### Time Complexity: +- **Time Complexity: O(N * ants_num * iterations_num)** + The time complexity depends on the number of cities (N), the number of ants (ants_num), and the number of iterations (iterations_num). + +### Space Complexity: +- **Space Complexity: O(N^2)** + The algorithm requires storage for pheromone levels on all paths, resulting in a space complexity of O(N^2) for a fully connected graph. + +### Summary: +The Ant Colony Optimization (ACO) algorithm effectively tackles the Travelling Salesman Problem by simulating ant behavior with pheromone trails to find the shortest path. By balancing pheromone influence and heuristic distance measures, the algorithm iteratively improves routes, offering a practical solution for complex optimization challenges. This approach is highly valuable in network routing, scheduling, and various other optimization domains. diff --git a/docs/languages/SQL/sql-20.md b/docs/languages/SQL/sql-20.md new file mode 100644 index 000000000..eb9ba0bf7 --- /dev/null +++ b/docs/languages/SQL/sql-20.md @@ -0,0 +1,54 @@ +--- +id: SQL-Having-Clause +sidebar_position: 20 +title: "SQL Having Clause" +sidebar_label: "SQL Having Clause" +description: "The `HAVING` clause in SQL is used to filter records in combination with the `GROUP BY` clause." +tags: [sql, dbms, database, having] +--- + +The `HAVING` clause is used in conjunction with the `GROUP BY` clause to filter the results of aggregated data. It allows you to specify conditions on groups created by the `GROUP BY` clause, enabling more advanced data filtering. + +### Syntax + +```sql +SELECT column_name(s), aggregate_function(column_name) +FROM table_name +WHERE condition +GROUP BY column_name(s) +HAVING condition; +``` +### Key Points + +* The HAVING clause is similar to the WHERE clause, but it is applied to groups rather than individual rows. +* You typically use HAVING to filter records after aggregation, making it suitable for conditions on aggregated data. + +### Examples +**Example 1: Find all categories with more than 10 products** + +```sql +SELECT CategoryID, COUNT(ProductID) AS ProductCount +FROM Products +GROUP BY CategoryID +HAVING COUNT(ProductID) > 10; +``` + +**Example 2: Retrieve suppliers who have provided products worth more than $1,000** + +```sql +SELECT SupplierID, SUM(Price) AS TotalValue +FROM Products +GROUP BY SupplierID +HAVING SUM(Price) > 1000; +``` + +**Example 3: List all customers with more than one order** + +```sql +SELECT CustomerID, COUNT(OrderID) AS OrderCount +FROM Orders +GROUP BY CustomerID +HAVING COUNT(OrderID) > 1; +``` +**Note**: +The HAVING clause is often used with aggregate functions such as SUM(), COUNT(), AVG(), etc. It is important to note that the HAVING clause is evaluated after the GROUP BY clause, which means you cannot use it without grouping your results first. diff --git a/docs/linked-list/Polynomial-Addition.md b/docs/linked-list/Polynomial-Addition.md new file mode 100644 index 000000000..934b5d765 --- /dev/null +++ b/docs/linked-list/Polynomial-Addition.md @@ -0,0 +1,181 @@ +--- +id: polynomial-addition +title: Polynomial-addition +sidebar_label: Polynomial-addition +description: "Addition of two polynomials represented as linked lists and displays the resulting polynomial" +tags: [dsa, algorithms, linked-list] +--- + +### Problem Statement: + Write a program in C++ to add two polynomials using a linked list. Each node of the linked list will represent a term in the polynomial, containing the coefficient and exponent of the term. The program will take two polynomials as input, add them, and output the resulting polynomial in simplified form. + +### Features + +- Input two polynomials from the user. +- Add polynomials by combining like terms. +- Display polynomials in a readable format (e.g., 3x^2 + 2x + 1). + +### Algorithm Steps: + +1. **Define the Node Structure:** + - Create a structure `Node` with fields for coefficient (`coeff`), exponent (`exp`), and a pointer to the next node (`next`). + +2. **Create the Polynomial:** + - Initialize the head of the polynomial as `nullptr`. + +3. **Insert Terms:** + - Define a function `insertTerm(Node*& head, int coeff, int exp)` to insert a new term into the polynomial. + - If the head is `nullptr`, set it to the new node. Otherwise, traverse to the end of the list and append the new node. + +4. **Display Polynomial:** + - Define a function `displayPolynomial(Node* head)` to print the polynomial in a formatted manner. + - Handle special cases for exponents 1 and 0 to omit unnecessary parts of the output. + +5. **Add Polynomials:** + - Define a function `addPolynomials(Node* poly1, Node* poly2)` that takes two polynomial linked lists. + - Initialize an empty result polynomial. + - Traverse both polynomials: + - If the exponent of the first polynomial term is greater, insert it into the result. + - If the exponent of the second polynomial term is greater, insert it into the result. + - If the exponents are equal, sum the coefficients and insert the resulting term if non-zero. + - After finishing one polynomial, insert any remaining terms from the other polynomial. + +6. **Main Function:** + - Initialize pointers for the two input polynomials and the result polynomial. + - Input the number of terms and the corresponding coefficients and exponents for each polynomial. + - Display both polynomials and the sum of the polynomials. + +7. **End of Program:** + - Return 0 to indicate successful execution. + +### Time Complexity: +- The time complexity of this program is `O(max(n, m))` , where `n` and `m` are the number of terms in the two polynomials being added. The `addPolynomials` function processes each term from both polynomials once, resulting in linear time complexity relative to the larger polynomial. The `insertTerm` function performs insertions in constant time, and displaying the polynomials has a linear complexity as well, but it is dominated by the addition process. + +### Sample Input: + + Enter the number of terms for the first polynomial: 3 + Enter coefficient and exponent for term 1: 3 2 + Enter coefficient and exponent for term 2: 2 1 + Enter coefficient and exponent for term 3: 1 0 + Enter the number of terms for the second polynomial: 2 + Enter coefficient and exponent for term 1: 4 2 + Enter coefficient and exponent for term 2: 3 0 + +### Sample Output: + First Polynomial: 3x^2 + 2x + 1 + Second Polynomial: 4x^2 + 3 + Sum of Polynomials: 7x^2 + 2x + 4 + +### C++ Implementation: + +```cpp + +#include +using namespace std; + +struct Node { + int coeff; + int exp; + Node* next; + Node(int c, int e) : coeff(c), exp(e), next(nullptr) {} // Constructor for easy initialization +}; + +// Function to insert a term at the end of the polynomial +void insertTerm(Node*& head, int coeff, int exp) { + Node* newNode = new Node(coeff, exp); + if (head == nullptr) { + head = newNode; + } else { + Node* temp = head; + while (temp->next != nullptr) { + temp = temp->next; + } + temp->next = newNode; + } +} + +// Function to display the polynomial in a formatted way +void displayPolynomial(Node* head) { + Node* temp = head; + bool isFirstTerm = true; + + while (temp != nullptr) { + // Adjust display for x^1 and x^0 cases + if (temp->exp == 1) { + cout << (temp->coeff > 0 && !isFirstTerm ? " + " : "") << temp->coeff << "x"; + } else if (temp->exp == 0) { + cout << (temp->coeff > 0 && !isFirstTerm ? " + " : "") << temp->coeff; + } else { + cout << (temp->coeff > 0 && !isFirstTerm ? " + " : "") << temp->coeff << "x^" << temp->exp; + } + temp = temp->next; + isFirstTerm = false; + } + cout << endl; +} + +// Function to add two polynomials and return the resulting polynomial +Node* addPolynomials(Node* poly1, Node* poly2) { + Node* result = nullptr; + Node* p1 = poly1; + Node* p2 = poly2; + + while (p1 != nullptr && p2 != nullptr) { + if (p1->exp > p2->exp) { + insertTerm(result, p1->coeff, p1->exp); + p1 = p1->next; + } else if (p1->exp < p2->exp) { + insertTerm(result, p2->coeff, p2->exp); + p2 = p2->next; + } else { + int sumCoeff = p1->coeff + p2->coeff; + if (sumCoeff != 0) { // Only add non-zero coefficients + insertTerm(result, sumCoeff, p1->exp); + } + p1 = p1->next; + p2 = p2->next; + } + } + + // Insert remaining terms from either polynomial if any are left + while (p1 != nullptr) { + insertTerm(result, p1->coeff, p1->exp); + p1 = p1->next; + } + while (p2 != nullptr) { + insertTerm(result, p2->coeff, p2->exp); + p2 = p2->next; + } + + return result; +} + +int main() { + Node* poly1 = nullptr; + Node* poly2 = nullptr; + Node* result = nullptr; + int n, coeff, exp; + cout << "Enter the number of terms for the first polynomial: "; + cin >> n; + for (int i = 0; i < n; i++) { + cout << "Enter coefficient and exponent for term " << i + 1 << ": "; + cin >> coeff >> exp; + insertTerm(poly1, coeff, exp); + } + cout << "Enter the number of terms for the second polynomial: "; + cin >> n; + for (int i = 0; i < n; i++) { + cout << "Enter coefficient and exponent for term " << i + 1 << ": "; + cin >> coeff >> exp; + insertTerm(poly2, coeff, exp); + } + cout << "First Polynomial: "; + displayPolynomial(poly1); + cout << "Second Polynomial: "; + displayPolynomial(poly2); + result = addPolynomials(poly1, poly2); + cout << "Sum of Polynomials: "; + displayPolynomial(result); + return 0; +} +``` diff --git a/docs/machine-learning/PC_Visualizations.md b/docs/machine-learning/PC_Visualizations.md new file mode 100644 index 000000000..24bb41ac4 --- /dev/null +++ b/docs/machine-learning/PC_Visualizations.md @@ -0,0 +1,145 @@ +--- + +id: pca-visualizations +title: PCA Visualizations +sidebar_label: PCA +description: "Implement Principal Component Analysis (PCA) to reduce the dimensionality of high-dimensional data while preserving its essential features. Visualize the transformed data to gain insights into underlying patterns." +tags: [data science, dimensionality reduction, PCA, data visualization, machine learning] + +--- + +### Definition: +**Principal Component Analysis (PCA)** is a statistical technique used for dimensionality reduction. It transforms high-dimensional data into a lower-dimensional space, capturing the most variance in the data while minimizing loss of information. PCA helps simplify complex datasets, making them easier to visualize and analyze. + +### Characteristics: +- **Dimensionality Reduction**: + PCA reduces the number of variables (dimensions) in a dataset while retaining the essential patterns and structures. + +- **Eigenvalues and Eigenvectors**: + PCA identifies principal components by calculating the eigenvalues and eigenvectors of the covariance matrix of the data. + +- **Variance Explained**: + Each principal component captures a portion of the total variance, allowing users to understand how much information is retained. + +### Components of PCA: +1. **Data Standardization**: + Standardize the dataset to have a mean of zero and a standard deviation of one to ensure each feature contributes equally. + +2. **Covariance Matrix**: + Compute the covariance matrix to examine the relationships between different features in the dataset. + +3. **Eigen Decomposition**: + Calculate the eigenvalues and eigenvectors of the covariance matrix to determine the principal components. + +4. **Projection**: + Transform the original data onto the new principal component axes, reducing its dimensionality. + +### Steps Involved: +1. **Standardize the Data**: + Center and scale the data to prepare it for PCA. + +2. **Compute the Covariance Matrix**: + Analyze the relationships between features by calculating the covariance matrix. + +3. **Calculate Eigenvalues and Eigenvectors**: + Find the eigenvalues and eigenvectors to determine the direction of the principal components. + +4. **Sort Eigenvalues**: + Sort the eigenvalues and their corresponding eigenvectors in descending order to identify the most significant components. + +5. **Select Principal Components**: + Choose the top k eigenvectors (principal components) based on the desired level of variance explained. + +6. **Project the Data**: + Transform the original data onto the selected principal components to achieve dimensionality reduction. + +### Key Concepts: +- **Variance Explained Ratio**: + Indicates how much of the total variance is captured by each principal component, helping determine how many components to retain. + +- **Scree Plot**: + A graphical representation of the eigenvalues that helps visualize the importance of each principal component. + +- **Biplot**: + A visualization that combines the principal component scores and the loading vectors, providing insights into the relationships between variables. + +### Advantages of PCA: +- **Reduces Complexity**: + Simplifies high-dimensional datasets, making them easier to visualize and interpret. + +- **Improves Model Performance**: + By reducing noise and redundancy, PCA can enhance the performance of machine learning models. + +- **Facilitates Visualization**: + Enables effective visualization of complex datasets by projecting them into two or three dimensions. + +### Limitations of PCA: +- **Linear Assumption**: + PCA assumes linear relationships among features, which may not hold in all datasets. + +- **Loss of Information**: + Some information is inevitably lost during dimensionality reduction, potentially impacting analysis. + +- **Interpretability**: + The transformed components may not have clear meanings, making it difficult to interpret results in context. + +### Popular Applications of PCA: +1. **Data Visualization**: + Reduce dimensions for visual exploration of high-dimensional data. + +2. **Image Compression**: + Compress images by retaining only the most significant principal components. + +3. **Genomics**: + Analyze genetic data to identify patterns and relationships among genes. + +4. **Market Research**: + Explore customer data to uncover underlying factors influencing purchasing behavior. + +5. **Anomaly Detection**: + Detect outliers in high-dimensional datasets by examining the variance captured by principal components. + +### Example of PCA in Python: +```python +import numpy as np +import pandas as pd +from sklearn.decomposition import PCA +import matplotlib.pyplot as plt + +# Sample dataset +data = pd.DataFrame(np.random.rand(100, 5), columns=['A', 'B', 'C', 'D', 'E']) + +# Standardize the data +data_standardized = (data - data.mean()) / data.std() + +# Apply PCA +pca = PCA(n_components=2) # Reduce to 2 dimensions +pca_result = pca.fit_transform(data_standardized) + +# Create a DataFrame for the PCA results +pca_df = pd.DataFrame(data=pca_result, columns=['Principal Component 1', 'Principal Component 2']) + +# Visualize the PCA results +plt.figure(figsize=(8, 6)) +plt.scatter(pca_df['Principal Component 1'], pca_df['Principal Component 2'], alpha=0.7) +plt.title('PCA Result') +plt.xlabel('Principal Component 1') +plt.ylabel('Principal Component 2') +plt.grid() +plt.show() +``` + +### Time and Space Complexity: +- **Time Complexity**: + The dominant factor is the eigen decomposition, which typically runs in $O(n^3)$, where $n$ is the number of features. + +- **Space Complexity**: + The space required is $O(n^2)$ for storing the covariance matrix and eigenvectors. + +### Summary & Applications: +- **PCA** is a powerful technique for simplifying data analysis and visualization by reducing dimensionality while retaining essential information. + +- **Applications**: + Widely used in exploratory data analysis, image processing, and machine learning to enhance interpretability and model performance. + +--- diff --git a/java/Arrays/1.Easy/Find missing number.md b/java/Arrays/1.Easy/Find missing number.md new file mode 100644 index 000000000..fbf4c768b --- /dev/null +++ b/java/Arrays/1.Easy/Find missing number.md @@ -0,0 +1,98 @@ +--- +id: find-missing-number +title: Find the Missing Number in Array +sidebar_label: Find Missing Number in Array +sidebar_position: 1 +description: Find the missing number in an array of size N containing numbers from 1 to N. +tags: [Array, XOR, DSA] +--- + +# Problem Statement +You are given an array `a` of size `N-1` containing numbers from `1` to `N`. The array has one number missing. Find the missing number. + +[LeetCode Problem Link](https://leetcode.com/problems/missing-number/description/) + +--- + +## Examples + +**Example 1**: +Input: +`a = [1, 2, 4, 5]`, `N = 5` + +Output: +`3` + +Explanation: +Numbers between `1` to `N` are `[1, 2, 3, 4, 5]`. The missing number is `3`. + +--- + +**Example 2**: +Input: +`a = [2, 3, 4, 5]`, `N = 5` + +Output: +`1` + +Explanation: +Numbers between `1` to `N` are `[1, 2, 3, 4, 5]`. The missing number is `1`. + +--- + +## Intuition +This problem can be solved using the properties of XOR: +1. **Property 1**: XOR of two identical numbers is always 0 (`a ^ a = 0`). +2. **Property 2**: XOR of a number with 0 results in the number itself (`0 ^ a = a`). + +### Key Idea: +- XOR all the numbers from `1` to `N`, which results in `xor1 = 1 ^ 2 ^ ... ^ N`. +- XOR all the elements in the array `a[]`, which results in `xor2 = 1 ^ 2 ^ ... ^ N` (excluding the missing number). +- The result of `xor1 ^ xor2` will cancel out all the numbers except the missing one, as explained by the XOR properties. Hence, `missing number = xor1 ^ xor2`. + +--- + +## Approach +1. Initialize two variables `xor1` and `xor2` to 0. +2. XOR all the numbers from `1` to `N` and store the result in `xor1`. +3. XOR all the elements of the array and store the result in `xor2`. +4. XOR the values of `xor1` and `xor2`. The result will be the missing number. + +--- + +## Java Implementation + +```java +import java.util.*; + +public class FindMissingNumber { + public static int missingNumber(int []a, int N) { + int xor1 = 0, xor2 = 0; + + for (int i = 0; i < N - 1; i++) { + xor2 = xor2 ^ a[i]; // XOR of array elements + xor1 = xor1 ^ (i + 1); // XOR up to [1...N-1] + } + xor1 = xor1 ^ N; // XOR up to [1...N] + + return (xor1 ^ xor2); // the missing number + } + + public static void main(String args[]) { + int N = 5; + int a[] = {1, 2, 4, 5}; + + int ans = missingNumber(a, N); + System.out.println("The missing number is: " + ans); + } +} +``` +--- +## Time Complexity +**Time Complexity**: `O(N)`, where N is the number of elements in the array. We only need to iterate over the array once to calculate the XORs. + +**Space Complexity**: `O(1)`, as we are only using a constant amount of extra space. + +--- +## Conclusion +Using XOR properties, we can find the missing number in linear time without using any extra space, making it an optimal solution for this problem. \ No newline at end of file diff --git a/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md new file mode 100644 index 000000000..aec67e5f4 --- /dev/null +++ b/java/Arrays/1.Easy/Remove Duplicates from Sorted Array.md @@ -0,0 +1,96 @@ +--- +id: remove-duplicates-sorted-array +title: Remove Duplicates in-place from Sorted Array +sidebar_label: Remove Duplicates in-place +sidebar_position: 1 +description: Given a sorted array, remove the duplicates in-place and return the new length. +tags: [Array, In-place, DSA] +--- + +# Remove Duplicates in-place from Sorted Array + +## Problem Statement +Given a sorted array `arr`, remove duplicates in-place such that each element appears only once and return the new length. The solution should modify the input array in-place and not use extra space. + +[LeetCode Problem Link](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/) + +--- + +## Examples + +**Example 1**: +Input: +`arr = [1, 1, 2, 2, 2, 3, 3]` + +Output: +`arr = [1, 2, 3, _, _, _, _]` + +Explanation: +The unique elements are `[1, 2, 3]`, so the function returns `3` and places `[1, 2, 3]` at the start of the array. + +--- + +**Example 2**: +Input: +`arr = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4]` + +Output: +`arr = [1, 2, 3, 4, _, _, _, _, _, _, _]` + +Explanation: +The unique elements are `[1, 2, 3, 4]`, so the function returns `4` and places `[1, 2, 3, 4]` at the start of the array. + +--- + +## Approach +The problem can be solved using the two-pointer technique: + +1. Maintain two pointers, `i` and `j`, where `i` tracks the position of unique elements and `j` iterates over the array. +2. If the element at index `j` is different from the element at index `i`, increment `i` and set `arr[i] = arr[j]`. +3. The new length of the array will be `i + 1`. + +### Steps: +- Initialize `i = 0` to track the first unique element. +- Traverse the array from `j = 1` to the end. +- If `arr[j]` is different from `arr[i]`, update `arr[i + 1]` with `arr[j]` and increment `i`. +- After the loop, the first `i + 1` elements of the array will be unique. + +--- + +## Java Implementation + +```java +import java.util.*; + +public class Main { + public static void main(String[] args) { + int arr[] = {1, 1, 2, 2, 2, 3, 3}; + int k = removeDuplicates(arr); + System.out.println("The array after removing duplicate elements is "); + for (int i = 0; i < k; i++) { + System.out.print(arr[i] + " "); + } + } + + static int removeDuplicates(int[] arr) { + int i = 0; + for (int j = 1; j < arr.length; j++) { + if (arr[i] != arr[j]) { + i++; + arr[i] = arr[j]; + } + } + return i + 1; + } +} +``` + +--- +## Time Complexity +**Time Complexity**: `O(n)`, where n is the length of the input array. We are using a single loop to traverse the array. + +**Space Complexity**: `O(1)`, since we are modifying the array in-place without using any extra space. + +--- +## Conclusion +This solution efficiently removes duplicates from a sorted array in-place using the two-pointer technique. It has a time complexity of `O(n)` and does not require extra space, making it optimal for large inputs. \ No newline at end of file diff --git a/java/Arrays/2.Medium/Kadane's Algorithm.md b/java/Arrays/2.Medium/Kadane's Algorithm.md new file mode 100644 index 000000000..68d24dca3 --- /dev/null +++ b/java/Arrays/2.Medium/Kadane's Algorithm.md @@ -0,0 +1,104 @@ +--- +id: kadanes-algorithm> +title: Kadane's Algorithm- Maximum Subarray Sum +sidebar_label: Maximum Subarray Sum +sidebar_position: 1 +description: Find the maximum sum of a contiguous subarray in an integer array. +tags: [Array, Dynamic Programming, Greedy, DSA] +--- + +# Kadane's Algorithm: Maximum Subarray Sum + +## Problem Statement +Given an integer array `arr`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. + +[LeetCode Problem Link](https://leetcode.com/problems/maximum-subarray/description/) + +## Examples + +**Example 1**: +Input: +`arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]` + +Output: +`6` + +Explanation: +The subarray `[4, -1, 2, 1]` has the largest sum = 6. + +--- + +**Example 2**: +Input: +`arr = [1]` + +Output: +`1` + +Explanation: +Array has only one element, which gives a positive sum of 1. + +--- + +## Intuition +The intuition behind **Kadane's Algorithm** is simple: a subarray with a negative sum will always reduce the sum of the total subarray, so it's better to discard such subarrays and reset the sum to 0 whenever the sum goes below 0. + +### Key Idea +- Iterate through the array and add elements to a running sum. +- If the sum becomes negative at any point, reset it to zero since no subarray with a negative sum is worth considering. +- Track the maximum sum encountered during the iteration. + +## Approach +1. Initialize two variables: `maxi` to store the maximum sum and `sum` to store the current subarray sum. +2. Iterate through the array: + - Add the current element to `sum`. + - If `sum` exceeds `maxi`, update `maxi`. + - If `sum` becomes negative, reset it to `0`. +3. Return `maxi` as the result. + +### Edge Case +In some scenarios, the question may mention that the sum of an empty subarray should be considered. In that case, compare `maxi` with `0` before returning the result, and ensure you return the larger value. + +## Java Implementation + +```java +import java.util.*; + +public class Main { + public static long maxSubarraySum(int[] arr, int n) { + long maxi = Long.MIN_VALUE; // maximum sum + long sum = 0; + + for (int i = 0; i < n; i++) { + sum += arr[i]; + if (sum > maxi) { + maxi = sum; + } + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + return maxi; + } + + public static void main(String args[]) { + int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4}; + int n = arr.length; + long maxSum = maxSubarraySum(arr, n); + System.out.println("The maximum subarray sum is: " + maxSum); + } +} + +``` + +--- +## Time Complexity +The **Time complexity** of Kadane's Algorithm is `O(n)`, where n is the number of elements in the array. This is because we make a single pass through the array to calculate the maximum subarray sum. + +**Space Complexity**: `O(1)` as we are not using any extra space. + +--- +## Conclusion +Kadane's Algorithm efficiently finds the maximum subarray sum in linear time, making it a powerful technique for solving problems related to contiguous subarrays. The algorithm's simplicity and effectiveness make it a staple in competitive programming and interviews. \ No newline at end of file diff --git a/java/Arrays/2.Medium/Longest Subarray with sum K.md b/java/Arrays/2.Medium/Longest Subarray with sum K.md new file mode 100644 index 000000000..8f66e0f22 --- /dev/null +++ b/java/Arrays/2.Medium/Longest Subarray with sum K.md @@ -0,0 +1,122 @@ +--- +id: longest-subarray-sum-k +title: Find Longest Subarray with Sum k +sidebar_label: Longest Subarray with Sum k +sidebar_position: 1 +description: Find the length of the longest subarray whose sum equals k. +tags: [Array, Hashing, DSA] +--- + +# Problem Statement +Given an array `a[]` and an integer `k`, find the length of the longest subarray that sums to `k`. + +[LeetCode Problem Link](https://leetcode.com/problems/subarray-sum-equals-k/) + +## Examples + +**Example 1**: +Input: +`N = 3, k = 5, array[] = {2, 3, 5}` + +Output: +`2` + +Explanation: +The longest subarray with sum `5` is `{2, 3}`. Its length is `2`. + +--- + +**Example 2**: +Input: +`N = 3, k = 1, array[] = {-1, 1, 1}` + +Output: +`3` + +Explanation: +The longest subarray with sum `1` is `{-1, 1, 1}`. Its length is `3`. + +--- + +## Intuition +To solve this problem optimally, we can use the concept of **prefix sum** combined with **hashing**. + +### Key Idea: +- Maintain a map to store the prefix sum and its corresponding index. +- As we iterate through the array, calculate the prefix sum up to each index. +- Check if the prefix sum equals `k`. If yes, update the maximum subarray length. +- Also, check if there is a prefix sum equal to `sum - k` (the remaining sum required to get `k` from the current subarray). If such a sum exists, calculate the length of the subarray and update the maximum length accordingly. +- Store the prefix sum and its earliest occurrence in the map to maximize the subarray length. + +--- + +## Approach +1. Declare a HashMap `preSumMap` to store prefix sums and their corresponding indices. +2. Initialize variables `sum = 0` (to store the running prefix sum) and `maxLen = 0` (to store the length of the longest subarray with sum `k`). +3. Iterate through the array. For each element: + - Add the current element to `sum` (prefix sum up to that index). + - If the sum is equal to `k`, update `maxLen` to `i + 1` (the length from the start). + - Check if `sum - k` exists in the map. If yes, update `maxLen` with the length of the subarray `i - preSumMap[sum - k]`. + - Add the current `sum` to the map if it doesn't already exist (to store the earliest occurrence of the prefix sum). +4. Return `maxLen`, which stores the length of the longest subarray with sum `k`. + +--- + +## Java Implementation + +```java +import java.util.*; + +public class tUf { + public static int getLongestSubarray(int[] a, int k) { + int n = a.length; // size of the array. + Map preSumMap = new HashMap<>(); + int sum = 0; + int maxLen = 0; + + for (int i = 0; i < n; i++) { + // calculate the prefix sum till index i: + sum += a[i]; + + // if the sum = k, update the maxLen: + if (sum == k) { + maxLen = Math.max(maxLen, i + 1); + } + + // calculate the sum of remaining part i.e. x-k: + int rem = sum - k; + + // calculate the length and update maxLen: + if (preSumMap.containsKey(rem)) { + int len = i - preSumMap.get(rem); + maxLen = Math.max(maxLen, len); + } + + // finally, update the map checking the conditions: + if (!preSumMap.containsKey(sum)) { + preSumMap.put(sum, i); + } + } + + return maxLen; + } + + public static void main(String[] args) { + int[] a = {-1, 1, 1}; + int k = 1; + int len = getLongestSubarray(a, k); + System.out.println("The length of the longest subarray is: " + len); + } +} + +``` + +--- +## Time Complexity +**Time Complexity**: `O(N)`, where N is the number of elements in the array. We process each element only once. + +**Space Complexity**: `O(N)`, as we are using a HashMap to store the prefix sums. + +--- +## Conclusion +Using a hash map to store prefix sums allows us to efficiently find the longest subarray with sum k in linear time. \ No newline at end of file diff --git a/java/Arrays/3.Hard/Maximum Product Subarray.md b/java/Arrays/3.Hard/Maximum Product Subarray.md new file mode 100644 index 000000000..92d596ccf --- /dev/null +++ b/java/Arrays/3.Hard/Maximum Product Subarray.md @@ -0,0 +1,85 @@ +--- +id: maximum-product-subarray +title: Maximum Product Subarray in an Array +sidebar_label: Maximum Product Subarray +sidebar_position: 1 +description: Find the maximum product of a contiguous subarray within an array containing both negative and positive integers. +tags: [Dynamic Programming, Array] +--- + +# Problem Statement +Given an array that contains both negative and positive integers, find the maximum product subarray. + +**LeetCode Problem Link**: [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/description/) + +## Examples + +**Example 1**: +Input: +`Nums = [1, 2, 3, 4, 5, 0]` +Output: +`120` +**Explanation**: +In the given array, we can see `1 × 2 × 3 × 4 × 5` gives the maximum product value. + +--- + +**Example 2**: +Input: +`Nums = [1, 2, -3, 0, -4, -5]` +Output: +`20` +**Explanation**: +In the given array, we can see `(-4) × (-5)` gives the maximum product value. + +--- + +## Approach +The following approach is motivated by Kadane’s algorithm. The key insight is that we can obtain the maximum product from the product of two negative numbers as well. + +### Steps: +1. Initially, store the value at the 0th index in `prod1`, `prod2`, and `result`. +2. Traverse the array starting from the 1st index. +3. For each element: + - Update `prod1` to be the maximum of the current element, the product of the current element and `prod1`, and the product of the current element and `prod2`. + - Update `prod2` to be the minimum of the current element, the product of the current element and `prod1`, and the product of the current element and `prod2`. +4. Return the maximum of `result` and `prod1`. + +## Java Implementation + +```java +import java.util.*; + +public class Main { + static int maxProductSubArray(int arr[]) { + int prod1 = arr[0], prod2 = arr[0], result = arr[0]; + + for (int i = 1; i < arr.length; i++) { + int temp = Math.max(arr[i], Math.max(prod1 * arr[i], prod2 * arr[i])); + prod2 = Math.min(arr[i], Math.min(prod1 * arr[i], prod2 * arr[i])); + prod1 = temp; + + result = Math.max(result, prod1); + } + + return result; + } + + public static void main(String[] args) { + int nums[] = {1, 2, -3, 0, -4, -5}; + int answer = maxProductSubArray(nums); + System.out.print("The maximum product subarray is: " + answer); + } +} + +``` + +--- +## Time Complexity +The **Time complexity** of this algorithm is `O(n)`, where n is the number of elements in the input array. We traverse the array once to calculate the maximum product. + +The **Space complexity** is `O(1)` since we are using only a constant amount of space for variables. + +--- +## Conclusion +This approach efficiently finds the maximum product subarray by leveraging the properties of positive and negative integers. It maintains both the maximum and minimum products at each step, allowing it to handle negative values effectively. This solution is optimal in terms of both time and space complexity, making it suitable for large input sizes. \ No newline at end of file diff --git a/java/Arrays/3.Hard/Reverse pairs.md b/java/Arrays/3.Hard/Reverse pairs.md new file mode 100644 index 000000000..828d5c762 --- /dev/null +++ b/java/Arrays/3.Hard/Reverse pairs.md @@ -0,0 +1,139 @@ +--- +id: reverse-pairs +title: Count Reverse Pairs +sidebar_label: Count Reverse Pairs +sidebar_position: 1 +description: Count the number of reverse pairs in an array where i is less than j and the element at index i is greater than twice the element at index j. +tags: [Merge Sort, Array] +--- + +# Problem Statement +Given an array of numbers, return the count of reverse pairs. Reverse Pairs are those pairs where `i < j` and `arr[i] > 2 * arr[j]`. + +**LeetCode Problem Link**: [Reverse Pairs](https://leetcode.com/problems/reverse-pairs/description/) + +## Examples + +### Example 1 +Input: +`N = 5, array[] = {1, 3, 2, 3, 1}` +Output: +`2` +**Explanation**: +The pairs are `(3, 1)` and `(3, 1)` as both satisfy the condition `arr[i] > 2 * arr[j]`. + +### Example 2 +Input: +`N = 4, array[] = {3, 2, 1, 4}` +Output: +`1` +**Explanation**: +There is only 1 pair `(3, 1)` that satisfies the condition `arr[i] > 2 * arr[j]`. + +## Approach + +The problem can be solved using a modified **Merge Sort** approach, similar to the inversion count problem but with a change in the condition. The idea is to: +1. **Merge** the sorted halves. +2. **Count pairs** where `arr[i] > 2 * arr[j]` using two pointers during the merge step. +3. Merge sort ensures that both halves are sorted, making it efficient to count valid pairs. + +### Steps +1. Implement a **modified merge sort** where: + - During the merge process, count valid pairs by iterating through the left and right halves. + - For each element in the left half, count how many elements in the right half satisfy the condition. +2. After counting the pairs, merge the two halves back into the original array. + +## Java Implementation + +```java +import java.util.*; + +public class CountReversePairs { + + // Merges two sorted halves and counts reverse pairs + private static void merge(int[] arr, int low, int mid, int high) { + ArrayList temp = new ArrayList<>(); + int left = low; + int right = mid + 1; + + // Merge two halves in sorted order + while (left <= mid && right <= high) { + if (arr[left] <= arr[right]) { + temp.add(arr[left]); + left++; + } else { + temp.add(arr[right]); + right++; + } + } + + // If there are remaining elements in the left half + while (left <= mid) { + temp.add(arr[left]); + left++; + } + + // If there are remaining elements in the right half + while (right <= high) { + temp.add(arr[right]); + right++; + } + + // Transfer all elements from temp back to arr + for (int i = low; i <= high; i++) { + arr[i] = temp.get(i - low); + } + } + + // Counts pairs where arr[i] > 2 * arr[j] in two sorted halves + public static int countPairs(int[] arr, int low, int mid, int high) { + int right = mid + 1; + int cnt = 0; + for (int i = low; i <= mid; i++) { + while (right <= high && arr[i] > 2 * arr[right]) right++; + cnt += (right - (mid + 1)); + } + return cnt; + } + + // Recursive merge sort with modification to count reverse pairs + public static int mergeSort(int[] arr, int low, int high) { + int cnt = 0; + if (low >= high) return cnt; + int mid = (low + high) / 2 ; + cnt += mergeSort(arr, low, mid); // left half + cnt += mergeSort(arr, mid + 1, high); // right half + cnt += countPairs(arr, low, mid, high); // Count reverse pairs + merge(arr, low, mid, high); // Merge sorted halves + return cnt; + } + + // Main function that triggers the merge sort + public static int reversePairs(int[] arr, int n) { + return mergeSort(arr, 0, n - 1); + } + + public static void main(String[] args) { + int[] array = {4, 1, 2, 3, 1}; + int n = 5; + int count = reversePairs(array, n); + System.out.println("The number of reverse pairs is: " + count); + } +} + +``` + +--- +## Time Complexity +The **Time complexity** is O(N log N), where N is the size of the array. + +**Merge Sort**: Recursively divides the array, which takes O(log N). +**Counting pairs**: For each split, the counting process takes O(N). + +Thus, the total time complexity is `O(N log N)`. + +**Space Complexity**: The space complexity is `O(N)` because of the temporary array used to store the merged elements. + +--- +## Conclusion +This problem is a modification of the inversion count problem, with the condition `arr[i] > 2 * arr[j].` The approach uses merge sort to efficiently count such pairs in `O(N log N)` time. This is optimal for large arrays and ensures that the problem can be solved within reasonable time limits. \ No newline at end of file diff --git a/src/components/DSA/DP/Parsing A Boolean Expression.md b/src/components/DSA/DP/Parsing A Boolean Expression.md new file mode 100644 index 000000000..57e952d23 --- /dev/null +++ b/src/components/DSA/DP/Parsing A Boolean Expression.md @@ -0,0 +1,106 @@ +--- +id: boolean-expression-parser +title: Boolean Expression Parser +sidebar_label: Boolean Expression Parser +sidebar_position: 1 +description: A Java program that parses and evaluates a boolean expression represented as a string, using a stack-based approach to handle operations. +tags: [java, dynamic progrmming, data structure] +--- + +## * Description* +A Java program that parses and evaluates a boolean expression represented as a string, using a stack-based approach to handle operations like AND (&), OR (|), and NOT (!). + +## *Approach* + +- *Steps :* +Initialize Stack: Use a stack to manage characters. +Process Characters: +Ignore commas. +Push all characters except ')' onto the stack. +Evaluate on ')': +Use a temporary buffer stack to gather values until '(' is reached. +Pop '(' and the operator before it from the stack. +Apply Operator: +For &: Set result = true and perform AND on all values in buffer. +For |: Set result = false and perform OR on all values in buffer. +For !: Apply NOT to the single value in buffer. +Push Result: Push the result ('t' or 'f') back onto the stack. +Final Result: Return the top of the stack as the result. + +## *java implementation * + +```java +import java.util.Stack; + +public class BooleanExpressionParser { + public static boolean parseBoolExpr(String expression) { + Stack stack = new Stack<>(); + + for (char ch : expression.toCharArray()) { + if (ch == ',') { + continue; // ignore commas + } else if (ch != ')') { + stack.push(ch); // push any character other than ')' + } else { + // We've encountered ')', start evaluating + Stack buffer = new Stack<>(); + while (stack.peek() != '(') { + buffer.push(stack.pop()); + } + stack.pop(); // Remove '(' + + // The operator before '(' determines what kind of operation to perform + char operator = stack.pop(); + boolean result; + + if (operator == '&') { + result = true; + while (!buffer.isEmpty()) { + result &= buffer.pop() == 't'; + } + } else if (operator == '|') { + result = false; + while (!buffer.isEmpty()) { + result |= buffer.pop() == 't'; + } + } else { // operator == '!' + result = buffer.pop() == 'f'; + } + + // Push result back onto the stack + stack.push(result ? 't' : 'f'); + } + } + + return stack.pop() == 't'; + } + + public static void main(String[] args) { + String expression1 = "&(|(f))"; + System.out.println(parseBoolExpr(expression1)); // Output: false + + String expression2 = "|(f,f,f,t)"; + System.out.println(parseBoolExpr(expression2)); // Output: true + + String expression3 = "!(|(f,t))"; + System.out.println(parseBoolExpr(expression3)); // Output: false + } +} +``` + +Output: + +``` +For expression1 = "&(|(f))", output is false. +For expression2 = "|(f,f,f,t)", output is true. +For expression3 = "!(|(f,t))", output is false. +``` + +### Time Complexity +- $O(n)$, where n is the length of the expression, as each character is processed once. + +### Space Complexity +- $O(n)$, due to the stack usage for storing characters and intermediate results. + +## Conclusion +The parser efficiently evaluates boolean expressions with operators &, |, and ! using stack-based processing for expressions of reasonable length. diff --git a/src/data/problemData.ts b/src/data/problemData.ts index 63b1e3245..9263a1ed4 100644 --- a/src/data/problemData.ts +++ b/src/data/problemData.ts @@ -1,15 +1,15 @@ 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: ` + 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) { @@ -28,7 +28,7 @@ const problemsData = { return result; } };`, - java: ` + java: ` import java.util.HashMap; public class Solution { @@ -47,7 +47,7 @@ const problemsData = { return new int[] {}; } }`, - python: ` + python: ` class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: res = {} @@ -59,20 +59,20 @@ const problemsData = { 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: ` + 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) { @@ -88,7 +88,7 @@ const problemsData = { return area; } };`, - java: ` + java: ` public class Solution { public int maxArea(int[] height) { int left = 0, right = height.length - 1; @@ -108,7 +108,7 @@ const problemsData = { return maxArea; } }`, - python: ` + python: ` class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 @@ -124,19 +124,19 @@ class Solution: 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: ` + 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; @@ -160,7 +160,7 @@ class Solution: return res; } };`, - java: ` + java: ` import java.util.*; public class Solution { public List> threeSum(int[] nums) { @@ -185,7 +185,7 @@ public class Solution { return res; } };`, - python: ` + python: ` class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] @@ -209,22 +209,22 @@ class Solution: 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: ` + 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) { @@ -239,7 +239,7 @@ public: return stk.empty(); } };`, - java: ` + java: ` import java.util.Stack; public class Solution { @@ -254,7 +254,7 @@ public class Solution { return stack.isEmpty(); } };`, - python: ` + python: ` class Solution: def isValid(self, s: str) -> bool: stack = [] @@ -267,20 +267,20 @@ class Solution: 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: ` + 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) { @@ -295,7 +295,7 @@ public: } } };`, - java: ` + java: ` public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; @@ -309,7 +309,7 @@ public class Solution { } } };`, - python: ` + python: ` class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: @@ -322,28 +322,28 @@ class Solution: 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: ` + 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: ` + java: ` import java.util.Arrays; public class Solution { public void nextPermutation(int[] nums) { @@ -370,7 +370,7 @@ public class Solution { } } };`, - python: ` + python: ` class Solution: def nextPermutation(self, nums: List[int]) -> None: i = len(nums) - 2 @@ -382,19 +382,19 @@ class Solution: 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: ` + 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) { @@ -408,7 +408,7 @@ public: return low; } };`, - java: ` + java: ` class Solution { public int searchInsert(int[] nums, int target) { int low = 0, high = nums.length - 1; @@ -421,7 +421,7 @@ class Solution { return low; } };`, - python: ` + python: ` class Solution: def searchInsert(self, nums: List[int], target: int) -> int: low, high = 0, len(nums) - 1 @@ -434,25 +434,25 @@ class Solution: 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: ` + 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) { @@ -470,7 +470,7 @@ class Solution: return true; } };`, - java: ` + java: ` class Solution { public boolean isValidSudoku(char[][] board) { HashSet seen = new HashSet<>(); @@ -486,7 +486,7 @@ class Solution: return true; } };`, - python: ` + 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)] @@ -500,20 +500,20 @@ class Solution: 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: ` + 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) { @@ -528,7 +528,7 @@ class Solution: return n + 1; } };`, - java: ` + java: ` class Solution { public int firstMissingPositive(int[] nums) { int n = nums.length; @@ -542,7 +542,7 @@ class Solution: return n + 1; } };`, - python: ` + python: ` class Solution: def firstMissingPositive(self, nums: List[int]) -> int: n = len(nums) @@ -553,20 +553,20 @@ class Solution: 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: ` + 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) { @@ -578,7 +578,7 @@ class Solution: return max_sum; } };`, - java: ` + java: ` class Solution { public int maxSubArray(int[] nums) { int maxSum = nums[0], currSum = nums[0]; @@ -589,7 +589,7 @@ class Solution: return maxSum; } };`, - python: ` + python: ` class Solution: def maxSubArray(self, nums: List[int]) -> int: max_sum = nums[0] @@ -598,19 +598,19 @@ class Solution: 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: ` + 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) { @@ -627,7 +627,7 @@ public: return res; } };`, - java: ` + java: ` class Solution { public int mySqrt(int x) { if (x < 2) return x; @@ -643,7 +643,7 @@ class Solution { return (int) res; } };`, - python: ` + python: ` class Solution: def mySqrt(self, x: int) -> int: if x < 2: return x @@ -656,22 +656,22 @@ class Solution: 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: ` + 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) { @@ -686,7 +686,7 @@ public: return false; } };`, - java: ` + java: ` class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0) return false; @@ -700,7 +700,7 @@ class Solution { return false; } };`, - python: ` + python: ` class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False @@ -713,19 +713,19 @@ class Solution: 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: ` + 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) { @@ -739,7 +739,7 @@ public: return head; } };`, - java: ` + java: ` class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; @@ -752,7 +752,7 @@ class Solution { return head; } };`, - python: ` + python: ` class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head is None: return None @@ -763,22 +763,22 @@ class Solution: 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: ` + 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) { @@ -790,7 +790,7 @@ public: sort(nums1.begin(), nums1.end()); } };`, - java: ` + java: ` class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = 0; @@ -801,7 +801,7 @@ class Solution { Arrays.sort(nums1); } };`, - python: ` + python: ` class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i = 0 @@ -811,19 +811,19 @@ class Solution: 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: ` + 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; @@ -835,7 +835,7 @@ public: return ans; } };`, - java: ` + java: ` class Solution { public List inorderTraversal(TreeNode root) { List ans = new ArrayList<>(); @@ -849,7 +849,7 @@ class Solution { inorderTraversalHelper(root.right, ans); } };`, - python: ` + python: ` class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: ans = [] @@ -861,19 +861,19 @@ class Solution: 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: ` + 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) { @@ -887,7 +887,7 @@ public: return isSymmetricTest(p->left, q->right) && isSymmetricTest(p->right, q->left); } };`, - java: ` + java: ` class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; @@ -900,7 +900,7 @@ class Solution { return isSymmetricTest(p.left, q.right) && isSymmetricTest(p.right, q.left); } };`, - python: ` + python: ` class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True @@ -911,20 +911,20 @@ class Solution: 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: ` + 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) { @@ -948,7 +948,7 @@ public: return ans; } };`, - java: ` + java: ` class Solution { public List> levelOrder(TreeNode root) { List> ans = new ArrayList<>(); @@ -970,7 +970,7 @@ class Solution { return ans; } };`, - python: ` + python: ` class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: ans = [] @@ -987,19 +987,19 @@ class Solution: 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: ` + 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) { @@ -1009,7 +1009,7 @@ public: return max(leftDepth, rightDepth) + 1; } };`, - java: ` + java: ` class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; @@ -1018,7 +1018,7 @@ class Solution { return Math.max(leftDepth, rightDepth) + 1; } };`, - python: ` + python: ` class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 @@ -1026,18 +1026,18 @@ class Solution: 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: ` + 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) { @@ -1050,7 +1050,7 @@ public: return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } };`, - java: ` + java: ` class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) @@ -1062,7 +1062,7 @@ class Solution { return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } };`, - python: ` + python: ` class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: if not root: @@ -1073,19 +1073,19 @@ class Solution: 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: ` + 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) { @@ -1102,7 +1102,7 @@ public: return res; } };`, - java: ` + java: ` class Solution { public List> generate(int numRows) { List> res = new ArrayList<>(); @@ -1120,7 +1120,7 @@ class Solution { return res; } };`, - python: ` + python: ` class Solution: def generate(self, numRows: int) -> List[List[int]]: res = [] @@ -1133,19 +1133,19 @@ class Solution: 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: ` + 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) { @@ -1159,7 +1159,7 @@ public: return result; } };`, - java: ` + java: ` class Solution { public int maxProfit(int[] prices) { int minm = Integer.MAX_VALUE; @@ -1172,7 +1172,7 @@ class Solution { return result; } };`, - python: ` + python: ` class Solution: def maxProfit(self, prices: List[int]) -> int: minm = float('inf') @@ -1184,20 +1184,20 @@ class Solution: 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: ` + 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) { @@ -1218,7 +1218,7 @@ public: return false; } };`, - java: ` + java: ` class Solution { public boolean hasCycle(ListNode head) { if (head == null || head.next == null) @@ -1238,7 +1238,7 @@ class Solution { return false; } };`, - python: ` + python: ` class Solution: def hasCycle(self, head: ListNode) -> bool: if not head or not head.next: @@ -1256,21 +1256,21 @@ class Solution: 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: ` + 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; @@ -1286,7 +1286,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.*; class Solution { @@ -1304,7 +1304,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: result = [] @@ -1318,22 +1318,22 @@ class Solution: 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: ` + 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; @@ -1349,7 +1349,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.*; class Solution { @@ -1367,7 +1367,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: result = [] @@ -1381,20 +1381,20 @@ class Solution: 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: ` + 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) { @@ -1407,7 +1407,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public ListNode removeElements(ListNode head, int val) { if (head == null) return null; @@ -1417,7 +1417,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if not head: @@ -1427,20 +1427,20 @@ class Solution: 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: ` + 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) { @@ -1460,7 +1460,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public ListNode reverseList(ListNode head) { List values = new ArrayList<>(); @@ -1480,7 +1480,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def reverseList(self, head: ListNode) -> ListNode: values = [] @@ -1496,19 +1496,19 @@ class Solution: 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: ` + 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) { @@ -1517,7 +1517,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.*; class Solution { @@ -1527,26 +1527,26 @@ class Solution: } };`, - python: ` + 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: ` + 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) { @@ -1554,7 +1554,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.*; class Solution { @@ -1567,25 +1567,25 @@ class Solution: } };`, - python: ` + 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: ` + 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) { @@ -1598,7 +1598,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; @@ -1610,7 +1610,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if root is None: @@ -1618,21 +1618,21 @@ class Solution: 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: ` + 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; @@ -1666,7 +1666,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.Stack; class MyQueue { @@ -1701,7 +1701,7 @@ class Solution: } };`, - python: ` + python: ` class MyQueue: def __init__(self): @@ -1724,19 +1724,19 @@ class Solution: 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: ` + 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) { @@ -1759,7 +1759,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; @@ -1772,7 +1772,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): @@ -1784,19 +1784,19 @@ class Solution: 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: ` + 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) { @@ -1811,7 +1811,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public int missingNumber(int[] nums) { int sum = 0, n = nums.length; @@ -1822,26 +1822,26 @@ class Solution: } };`, - python: ` + 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: ` + 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) { @@ -1863,7 +1863,7 @@ class Solution: } };`, - java: ` + java: ` class Solution extends GuessGame { public int guessNumber(int n) { int start = 1, end = n; @@ -1880,7 +1880,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def guessNumber(self, n: int) -> int: start, end = 1, n @@ -1894,19 +1894,19 @@ class Solution: 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: ` + 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) { @@ -1930,7 +1930,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.Arrays; import java.util.ArrayList; @@ -1957,7 +1957,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() @@ -1975,18 +1975,18 @@ class Solution: 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: ` + 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) { @@ -1997,7 +1997,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public int[] runningSum(int[] nums) { for (int i = 1; i < nums.length; i++) { @@ -2007,28 +2007,28 @@ class Solution: } };`, - python: ` + 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: ` + 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) { @@ -2040,7 +2040,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public String restoreString(String s, int[] indices) { char[] res = new char[s.length()]; @@ -2051,7 +2051,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def restoreString(self, s: str, indices: List[int]) -> str: res = [''] * len(s) @@ -2059,16 +2059,16 @@ class Solution: 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: ` + 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) { @@ -2102,7 +2102,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public int maxLevelSum(TreeNode root) { if (root == null) return 0; @@ -2136,7 +2136,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def maxLevelSum(self, root: Optional[TreeNode]) -> int: if not root: @@ -2165,19 +2165,19 @@ class Solution: 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: ` + 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) { @@ -2193,7 +2193,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public String firstAlphabet(String S) { StringBuilder ans = new StringBuilder(); @@ -2209,7 +2209,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def firstAlphabet(self, S: str) -> str: result = S[0] # Start with the first character @@ -2218,17 +2218,17 @@ class Solution: 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: ` + 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; @@ -2237,7 +2237,7 @@ class Solution: return countLeaves(root->left) + countLeaves(root->right); };`, - java: ` + java: ` class Solution { public int countLeaves(Node root) { if (root == null) return 0; @@ -2248,7 +2248,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def countLeaves(self, root: Optional[Node]) -> int: if not root: @@ -2259,19 +2259,19 @@ class Solution: 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: ` + 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; @@ -2287,7 +2287,7 @@ class Solution: return v; };`, - java: ` + java: ` import java.util.*; class Solution { public List generate(int N) { @@ -2305,7 +2305,7 @@ class Solution: } };`, - python: ` + python: ` from collections import deque class Solution: def generate(self, N: int) -> List[str]: @@ -2319,19 +2319,19 @@ class Solution: 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: ` + 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) { @@ -2345,7 +2345,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.*; class Solution { public int minimum_difference(int[] nums) { @@ -2359,7 +2359,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def minimum_difference(self, nums: List[int]) -> int: nums.sort() @@ -2370,19 +2370,19 @@ class Solution: 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: ` + 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) { @@ -2390,31 +2390,31 @@ class Solution: } };`, - java: ` + java: ` class Solution { public int mthHalf(int N, int M) { return (int) (N / Math.pow(2, M - 1)); } };`, - python: ` + 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: ` + 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) { @@ -2431,7 +2431,7 @@ class Solution: } };`, - java: ` + java: ` class Solution { public String removeChars(String string1, String string2) { int[] arr = new int[26]; @@ -2447,7 +2447,7 @@ class Solution: } };`, - python: ` + python: ` class Solution: def removeChars(self, string1: str, string2: str) -> str: arr = [0] * 26 @@ -2461,25 +2461,25 @@ class Solution: 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: ` + 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; @@ -2500,7 +2500,7 @@ class Solution: } };`, - java: ` + java: ` import java.util.*; class Solution { @@ -2519,16 +2519,15 @@ class Solution: } };`, - python: ` + 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: { + 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.", @@ -3304,6 +3303,237 @@ class Solution: `, }, }, + 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 + `, + }, + }, }; export default problemsData;