├── CONTRIBUTING.md ├── LICENSE ├── Problems ├── 4Sum │ ├── README.md │ ├── solution.cpp │ ├── solution.java │ └── solution.py ├── All-Paths-From-Source-to-Target │ ├── README.md │ ├── Solution.cpp │ └── solution.py ├── Binary-Tree-Maximum-Path-Sum │ ├── README.md │ ├── solution.cpp │ └── solution.py ├── Count-Good-Numbers │ ├── README.md │ ├── Solution.py │ └── solution.cpp ├── Decode-String │ ├── README.md │ ├── Solution.cpp │ └── solution.py ├── Evaluate-Reverse-Polish-Notation │ ├── README.md │ ├── solution.cpp │ └── solution.java ├── K-Divisible-Elements-Subarrays │ ├── README.md │ └── solution.cpp ├── K-th-Symbol-in-Grammar │ └── README.md ├── Largest-Number │ ├── README.md │ ├── Solution.cpp │ ├── solution.js │ └── solution.py ├── Number-of-Digit-One │ ├── README.md │ ├── Solution.cpp │ └── Solution.java ├── Number-of-Islands │ ├── README.md │ ├── Solution.java │ ├── solution.cpp │ └── solution.py ├── Odd-Even-Linked-List │ └── README.md ├── Product-of-the-Last-K-Number │ ├── README.md │ └── Solution.cpp ├── Remove-K-Digits │ ├── README.md │ ├── solution.cpp │ └── solution.py ├── Reorder-List │ ├── README.md │ └── Solution.cpp ├── Rotate-List │ └── README.md ├── Sequential-Digits │ ├── README.md │ └── solution.cpp ├── Set-Matrix-Zeroes │ ├── README.md │ ├── Solution.java │ └── solution.cpp ├── Sort-List │ ├── README.md │ └── solution.py ├── Split-Linked-List-in-Parts │ └── README.md ├── Sum-Root-to-Leaf-Numbers │ ├── README.md │ └── solution.py ├── Swap-Nodes-in-Pairs │ ├── README.md │ └── solution.cpp ├── Swapping-Nodes-in-a-Linked-List │ └── README.md ├── Unique-Binary-Search-Trees │ ├── README.md │ └── Solution.cpp ├── Valid-Sudoku │ ├── README.md │ ├── solution.cpp │ ├── solution.java │ └── solution.py └── Wiggle-Sort-II │ ├── README.md │ └── solution.cpp ├── README.md └── images └── Logo.jpg /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributers 2 | 3 | Add your name to tle list of contributers followed by your username. 4 | 5 | ### Template 6 | 7 | ```md 8 | - [Your Name] | [Github username] 9 | ``` 10 | 11 | ### List of Contributers 12 | - Harshit Mehra | djharshit 13 | - Malay Kumar Jain | jainmalaykumar 14 | - Anurika | anurika22 15 | - Prasann Asrani | Prasann707 16 | - Aasit Babele | enc-rypto 17 | - Mustekeem Arsh | MustekeemArsh10 18 | - Atul Singh | Lanceiz 19 | - Raj Kunwar Singh | ra-jkunwar 20 | - Arvind Kumar Ojha | arvind-ojha 21 | - Ishita Modi | Ishitamodi03 22 | - Akash Kumar | erotic-ops 23 | - Klevin Pascal | Klevin05 24 | - Laura Sims | laurasimsdev 25 | - Chahat Gupta | chahat-ji 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 GDSC JEC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Problems/4Sum/README.md: -------------------------------------------------------------------------------- 1 | ## 4Sum 2 | 3 | Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]`such that: 4 | 5 | - `0 <= a, b, c, d < n` 6 | - `a`, `b`, `c`, and `d` are **distinct**. 7 | - `nums[a] + nums[b] + nums[c] + nums[d] == target` 8 | - You may return the answer in **any order**. 9 | 10 | ##### Constraints: 11 | 12 | - `1 <= nums.length <= 200` 13 | - `-109 <= nums[i] <= 109` 14 | - `-109 <= target <= 109` 15 | 16 | ##### Reference: 17 | [4Sum](https://leetcode.com/problems/4sum/) 18 | -------------------------------------------------------------------------------- /Problems/4Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> fourSum(vector &nums, int target) 5 | { 6 | if (nums.size() < 4) 7 | return {}; 8 | 9 | vector> ans; 10 | sort(nums.begin(), nums.end()); 11 | 12 | for (int i = 0; i < nums.size() - 3; increment(nums, i)) 13 | { 14 | for (int j = i + 1; j < nums.size() - 2; increment(nums, j)) 15 | { 16 | int l = j + 1, r = nums.size() - 1; 17 | long sum = 0; 18 | 19 | // two pointer 20 | while (l < r) 21 | { 22 | sum = (long)nums[i] + nums[j] + nums[l] + nums[r]; 23 | 24 | // if a solution is found, add it and change both pointers 25 | if (sum == target) 26 | { 27 | ans.push_back({nums[i], nums[j], nums[l], nums[r]}); 28 | increment(nums, l); 29 | decrement(nums, r); 30 | } 31 | // if sum is lesser, move left pointer to right by 1 32 | else if (sum < target) 33 | increment(nums, l); 34 | // else if sum is greater, move right pointer to left by 1 35 | else 36 | decrement(nums, r); 37 | } 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | 44 | // increment() & decrement() are helper functions to avoid duplicates 45 | // basically, they do i++ or i-- but until a different number is found 46 | 47 | void increment(vector &nums, int &n) 48 | { 49 | do 50 | n++; 51 | while (n < nums.size() && nums[n] == nums[n - 1]); 52 | } 53 | 54 | void decrement(vector &nums, int &n) 55 | { 56 | do 57 | n--; 58 | while (n >= 0 && nums[n] == nums[n + 1]); 59 | } 60 | }; -------------------------------------------------------------------------------- /Problems/4Sum/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> fourSum(int[] nums, int target) { 3 | List> ans = new ArrayList>(); 4 | Arrays.sort(nums); 5 | for(int i = 0; i < nums.length - 3; i++) { 6 | for(int j = i + 1; j < nums.length - 2; j++) { 7 | long res = (nums[i] + nums[j]); 8 | long remSum = target - res; 9 | int front = j + 1, back = nums.length - 1; 10 | while(front < back) { 11 | long twoSum = nums[front] + nums[back]; 12 | if(twoSum < remSum) front++; 13 | else if(twoSum > remSum) back--; 14 | else { 15 | List sum = new ArrayList<>(); 16 | sum.add(nums[i]); 17 | sum.add(nums[j]); 18 | sum.add(nums[front]); 19 | sum.add(nums[back]); 20 | ans.add(sum); 21 | 22 | while(front < back && nums[front] == sum.get(2)) front++; 23 | while(front < back && nums[back] == sum.get(3)) back--; 24 | } 25 | } 26 | while(i < nums.length - 1 && nums[i + 1] == nums[i]) i++; 27 | while(j < nums.length - 1 && nums[j + 1] == nums[j]) j++; 28 | } 29 | } 30 | return ans; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Problems/4Sum/solution.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | class Solution: 4 | def fourSum(self, nums: List[int], target: int) -> List[List[int]]: 5 | res, n = [], len(nums) 6 | nums.sort() 7 | for a in range(n): 8 | for b in range(a+1, n): 9 | c = b+1; d = n-1 10 | while c target: 15 | d -= 1 16 | else: 17 | toappend = [nums[a],nums[b],nums[c],nums[d]] 18 | if toappend not in res: 19 | res.append(toappend) 20 | c +=1 21 | d-=1 22 | return res 23 | -------------------------------------------------------------------------------- /Problems/All-Paths-From-Source-to-Target/README.md: -------------------------------------------------------------------------------- 1 | ## All Paths From Source to Target 2 | 3 | Given a **directed acyclic graph (DAG)** of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**. 4 | 5 | The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`). 6 | 7 | ##### Constraints: 8 | 9 | - `n == graph.length` 10 | - `2 <= n <= 15` 11 | - `0 <= graph[i][j] < n` 12 | - `graph[i][j] != i` (i.e., there will be no self-loops). 13 | - All the elements of `graph[i]` are **unique**. 14 | - The input graph is **guaranteed** to be a **DAG**. 15 | 16 | ##### Reference: 17 | [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/) 18 | -------------------------------------------------------------------------------- /Problems/All-Paths-From-Source-to-Target/Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector path; 5 | 6 | vector indeg0, outdeg0; 7 | 8 | vector > adj; 9 | 10 | vector visited; 11 | 12 | // Recursive function to print all paths 13 | void dfs(int s) 14 | { 15 | 16 | path.push_back(s); 17 | visited[s] = true; 18 | 19 | 20 | if (outdeg0[s] && indeg0[path[0]]) { 21 | for (auto x : path) 22 | cout << x << " "; 23 | cout << '\n'; 24 | } 25 | 26 | for (auto node : adj[s]) { 27 | if (!visited[node]) 28 | dfs(node); 29 | } 30 | 31 | path.pop_back(); 32 | visited[s] = false; 33 | } 34 | 35 | void print_all_paths(int n) 36 | { 37 | for (int i = 0; i < n; i++) { 38 | // for each node with in-degree 0 39 | // print all possible paths 40 | if (indeg0[i] && !adj[i].empty()) { 41 | dfs(i); 42 | } 43 | } 44 | } 45 | 46 | // Driver Code 47 | int main() 48 | { 49 | int n; 50 | n = 6; 51 | 52 | visited = vector(n, false); 53 | 54 | adj = vector >(n); 55 | 56 | indeg0 = vector(n, true); 57 | outdeg0 = vector(n, true); 58 | 59 | vector > edges 60 | = { { 5, 0 }, { 5, 2 }, { 2, 3 }, 61 | { 4, 0 }, { 4, 1 }, { 3, 1 } }; 62 | 63 | for (int i = 0; i < edges.size(); i++) { 64 | int u = edges[i].first; 65 | int v = edges[i].second; 66 | 67 | adj[u].push_back(v); 68 | 69 | indeg0[v] = false; 70 | 71 | outdeg0[u] = false; 72 | } 73 | cout << "All possible paths:\n"; 74 | print_all_paths(n); 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Problems/All-Paths-From-Source-to-Target/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 3 | self.ans = [] 4 | def backtrack(node , path): 5 | path.append(node) 6 | if node == len(graph) - 1: 7 | self.ans.append(list(path)) 8 | 9 | for neigh in graph[node]: 10 | backtrack(neigh,path) 11 | path.pop() 12 | backtrack(0,[]) 13 | return self.ans 14 | -------------------------------------------------------------------------------- /Problems/Binary-Tree-Maximum-Path-Sum/README.md: -------------------------------------------------------------------------------- 1 | ## Binary Tree Maximum Path Sum 2 | 3 | A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. 4 | 5 | The **path sum** of a path is the sum of the node's values in the path. 6 | 7 | _Given the `root` of a binary tree, return the maximum **path sum of any non-empty path**_. 8 | 9 | ##### Constraints: 10 | 11 | - The number of nodes in the tree is in the range `[1, 3 * 104]`. 12 | - `-1000 <= Node.val <= 1000` 13 | 14 | 15 | ##### Reference: 16 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) 17 | -------------------------------------------------------------------------------- /Problems/Binary-Tree-Maximum-Path-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans=-1e8; 4 | int solve(TreeNode* root){ 5 | if(root==NULL){ 6 | return 0; 7 | } 8 | int left= solve(root->left); //traversing left subtree 9 | int right= solve(root->right);//traversing right subtree 10 | 11 | ans= max(ans,max(max(left,right),max(left+right,0))+root->val); //storing max path found 12 | 13 | return root->val + max(0,max(right,left)); 14 | } 15 | int maxPathSum(TreeNode* root) { 16 | solve(root); 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /Problems/Binary-Tree-Maximum-Path-Sum/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPathSum(self, root: TreeNode) -> int: 3 | max_path = float("-inf") 4 | def get_max_gain(node): 5 | nonlocal max_path 6 | if node is None: 7 | return 0 8 | 9 | gain_on_left = max(get_max_gain(node.left), 0) 10 | gain_on_right = max(get_max_gain(node.right), 0) 11 | 12 | current_max_path = node.val + gain_on_left + gain_on_right 13 | max_path = max(max_path, current_max_path) 14 | 15 | return node.val + max(gain_on_left, gain_on_right) 16 | 17 | get_max_gain(root) 18 | return max_path 19 | -------------------------------------------------------------------------------- /Problems/Count-Good-Numbers/README.md: -------------------------------------------------------------------------------- 1 | ## Count Good Numbers 2 | 3 | A digit string is **good** if the digits (0-indexed) at **even** indices are **even** and the digits at **odd** indices are **prime** `(2, 3, 5, or 7)`. 4 | 5 | - For example, `"2582"` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. However, `"3245"` is **not** good because `3` is at an even index but is not even. 6 | 7 | Given an integer `n`, return _the **total** number of good digit strings of length_ `n`. Since the answer may be large, **return it modulo** `10^9 + 7`. 8 | 9 | A **digit string** is a string consisting of digits `0` through `9` that may contain leading zeros. 10 | 11 | 12 | ##### Constraints: 13 | 14 | - 1 <= n <= 10^15 15 | 16 | ##### Reference: 17 | [Count Good Numbers](https://leetcode.com/problems/count-good-numbers/) 18 | -------------------------------------------------------------------------------- /Problems/Count-Good-Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def countGoodNumbers(self, n: int) -> int: 4 | 5 | mod = 10 ** 9 + 7 6 | 7 | return pow(5, (n + 1) // 2, mod) * pow(4, n // 2, mod) % mod 8 | -------------------------------------------------------------------------------- /Problems/Count-Good-Numbers/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int mod = 1000000007; 5 | long long solve(long long val, long long pow) 6 | { // calculatin pow in log(n) time 7 | if (pow == 0) 8 | return 1; 9 | 10 | if (pow % 2 == 0) 11 | { 12 | return solve((val * val) % mod, pow / 2) % mod; 13 | } 14 | else 15 | return (val * solve((val * val) % mod, pow / 2)) % mod; 16 | } 17 | int countGoodNumbers(long long n) 18 | { 19 | // even means 5 options 20 | // odd means 4 option 21 | 22 | long long pow = n / 2; // calculate no of times 5*4 means 20 occurs 23 | 24 | long long ans = solve(20, pow); // calculate power(20,pow) 25 | 26 | if (n % 2 == 0) 27 | { // if n is even then 5 and 4 occur same no of time n/2 28 | return ans; 29 | } 30 | return ((5 * ans) % mod); // if n is odd then 5 occurs n/2+1 times means one extra times so return ans*5 and don't forgot to mod 31 | } 32 | }; -------------------------------------------------------------------------------- /Problems/Decode-String/README.md: -------------------------------------------------------------------------------- 1 | ## Decode String 2 | 3 | Given an encoded string, return its decoded string. 4 | 5 | The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. 6 | 7 | You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. 8 | 9 | The test cases are generated so that the length of the output will never exceed `10^5`. 10 | 11 | ##### Constraints: 12 | 13 | - `1 <= s.length <= 30` 14 | - `s` consists of lowercase English letters, digits, and square brackets `'[]'`. 15 | - `s` is guaranteed to be **a valid** input. 16 | - All the integers in `s` are in the range `[1, 300]`. 17 | 18 | ##### Reference: 19 | [Decode String](https://leetcode.com/problems/decode-string/) 20 | -------------------------------------------------------------------------------- /Problems/Decode-String/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // starting Index of encoding string 4 | int start = 0; 5 | 6 | string Solve(string &s ) 7 | { 8 | // Variable To store our answer 9 | string ans = ""; 10 | 11 | 12 | 13 | while( start < s.length() && s[start] >= 'a' && s[start]<= 'z' && s[start] != ']' ) 14 | ans.push_back(s[start++]); 15 | 16 | if(start >= s.length() || s[start] == ']') 17 | return ans; 18 | 19 | // We have reach the numerical character 20 | string num = ""; 21 | 22 | // store the number to be repeated 23 | while(s[start] != '[' ) 24 | num.push_back(s[start++]); 25 | int n = stoi(num) ; 26 | 27 | start++; 28 | 29 | string repeat = Solve(s ); 30 | 31 | for(int k = 0 ; k< n ; k++) 32 | ans+= repeat; 33 | 34 | start++; 35 | 36 | //Return ans 37 | return ans + Solve(s); 38 | 39 | } 40 | 41 | public: 42 | string decodeString(string s) { 43 | 44 | return Solve(s); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Problems/Decode-String/solution.py: -------------------------------------------------------------------------------- 1 | def decodeString(self, s): 2 | stack = []; curNum = 0; curString = '' 3 | for c in s: 4 | if c == '[': 5 | stack.append(curString) 6 | stack.append(curNum) 7 | curString = '' 8 | curNum = 0 9 | elif c == ']': 10 | num = stack.pop() 11 | prevString = stack.pop() 12 | curString = prevString + num*curString 13 | elif c.isdigit(): 14 | curNum = curNum*10 + int(c) 15 | else: 16 | curString += c 17 | return curString -------------------------------------------------------------------------------- /Problems/Evaluate-Reverse-Polish-Notation/README.md: -------------------------------------------------------------------------------- 1 | ## Evaluate Reverse Polish Notation 2 | 3 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 4 | 5 | Valid operators are `+`, `-`, `*`, and `/`. Each operand may be an integer or another expression. 6 | 7 | **Note** that division between two integers should truncate toward zero. 8 | 9 | It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. 10 | 11 | ##### Constraints: 12 | 13 | - `1 <= tokens.length <= 104` 14 | - `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"`, or `"/"`, or an integer in the range `[-200, 200]`. 15 | 16 | ##### Reference: 17 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) 18 | -------------------------------------------------------------------------------- /Problems/Evaluate-Reverse-Polish-Notation/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isop(string s){ 4 | return (s=="+" or s=="-" or s=="*" or s=="/"); 5 | } 6 | 7 | int evalRPN(vector& tokens) { 8 | stack st; 9 | string ff, ss; 10 | if(tokens.size()==1 and !isop(tokens[0])) return stoi(tokens[0]); 11 | for(auto i=0;i stack = new Stack<>(); 5 | int a,b; 6 | 7 | for(String s: tokens) 8 | { 9 | if(s.equals("+")) 10 | stack.push(stack.pop()+stack.pop()); 11 | 12 | else if(s.equals("-")) 13 | { 14 | a = stack.pop(); 15 | b = stack.pop(); 16 | stack.push(b-a); 17 | } 18 | else if(s.equals("*")) 19 | stack.push(stack.pop() * stack.pop()); 20 | 21 | else if(s.equals("/")) 22 | { 23 | a = stack.pop(); 24 | b = stack.pop(); 25 | stack.push(b/a); 26 | } 27 | else 28 | stack.push(Integer.parseInt(s)); 29 | } 30 | 31 | return stack.pop(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Problems/K-Divisible-Elements-Subarrays/README.md: -------------------------------------------------------------------------------- 1 | ## K Divisible Elements Subarrays 2 | 3 | Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most** k elements divisible by p_. 4 | 5 | Two arrays `nums1` and `nums2` are said to be **distinct** if: 6 | 7 | - They are of **different** lengths, or 8 | - There exists **at least** one index `i` where `nums1[i] != nums2[i]`. 9 | 10 | A **subarray** is defined as a **non-empty** contiguous sequence of elements in an array. 11 | 12 | ##### Constraints: 13 | 14 | - `1 <= nums.length <= 200` 15 | - `1 <= nums[i], p <= 200` 16 | - `1 <= k <= nums.length` 17 | 18 | ##### Reference: 19 | [K Divisible Elements Subarrays](https://leetcode.com/problems/k-divisible-elements-subarrays/) 20 | -------------------------------------------------------------------------------- /Problems/K-Divisible-Elements-Subarrays/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countDistinct(vector& arr, int k, int p) { 4 | int n=arr.size(); 5 | int ans = 0 ,ct=0; 6 | 7 | unordered_map mp; 8 | 9 | for(int i=0;i 5 | using namespace std; 6 | 7 | string largestNumber(vector& nums) { 8 | int x =0 ; 9 | //Checking for zeroes in the array 10 | for(int i=0 ;i s(nums.size()); 20 | for(int i =0 ;i0 ? 1 : 0; 28 | }); 29 | 30 | //empty string 31 | string ans="" ; 32 | for(int i=0 ;i>n; 40 | //InputVector 41 | vector arr(n); 42 | for(int i=0 ;i>arr[i]; 44 | } 45 | 46 | auto res =largestNumber(arr); 47 | cout< parseInt(strB[0]) ? -1 : 1 7 | else { 8 | const fullAB = strA + strB; 9 | const fullBA = strB + strA; 10 | for(let i = 0; i< fullAB.length; i++) { 11 | if(fullAB[i] === fullBA[i]) continue 12 | return fullAB[i] > fullBA[i] ? -1 : 1 13 | } 14 | } 15 | return 0 16 | }) 17 | return nums[0] === 0 ? "0" : nums.join("") 18 | } 19 | -------------------------------------------------------------------------------- /Problems/Largest-Number/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestNumber(self, nums: List[int]) -> str: 3 | for i,n in enumerate(nums): 4 | nums[i]=str(n) 5 | def comparison(n,m): 6 | if n+m>m+n: 7 | return -1 8 | else: 9 | return 1 10 | nums=sorted(nums, key=cmp_to_key(comparison)) 11 | return str(int("".join(nums))) 12 | -------------------------------------------------------------------------------- /Problems/Number-of-Digit-One/README.md: -------------------------------------------------------------------------------- 1 | ## Number of Digit One 2 | 3 | Given an integer `n`, count _the total number of digit `1` appearing in all non-negative integers less than or equal to `n`_. 4 | 5 | ##### Constraints: 6 | 7 | - `0 <= n <= 109` 8 | 9 | ##### Reference: 10 | [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) 11 | -------------------------------------------------------------------------------- /Problems/Number-of-Digit-One/Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int countDigitOne(int n) 5 | { 6 | int ones = 0; 7 | for (long long m = 1; m <= n; m *= 10) 8 | ones += (n/m + 8) / 10 * m + (n/m % 10 == 1) * (n%m + 1); 9 | return ones; 10 | } 11 | 12 | int main() 13 | { 14 | int n; 15 | cin>>n; 16 | int x= countDigitOne(n); 17 | cout<<"Number of ones: "<= grid.length || j >= grid[i].length || grid[i][j] == '0') return; 18 | 19 | grid[i][j] = '0'; 20 | clearRestOfLand(grid, i+1, j); 21 | clearRestOfLand(grid, i-1, j); 22 | clearRestOfLand(grid, i, j+1); 23 | clearRestOfLand(grid, i, j-1); 24 | return; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Problems/Number-of-Islands/solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | void bfs(int r, int c, vector> &vis, vector> grid) 3 | { 4 | int n = grid.size(); 5 | int m = grid[0].size(); 6 | vis[r][c] = 1; 7 | queue> q; 8 | q.push({r, c}); 9 | while (!q.empty()) 10 | { 11 | r = q.front().first; 12 | c = q.front().second; 13 | q.pop(); 14 | for (int i = -1; i <= 1; i++) 15 | { 16 | for (int j = -1; j <= 1; j++) 17 | { 18 | if (abs(i) == abs(j)) 19 | { 20 | continue; 21 | } 22 | int newr = r + i; 23 | int newc = c + j; 24 | if (newr >= 0 && newr < n && newc >= 0 && newc < m && 25 | grid[newr][newc] == '1' && vis[newr][newc] == 0) 26 | { 27 | q.push({newr, newc}); 28 | vis[newr][newc] = 1; 29 | } 30 | } 31 | } 32 | } 33 | } 34 | 35 | int numIslands(vector> &grid) 36 | { 37 | int n = grid.size(); 38 | int m = grid[0].size(); 39 | vector> vis(n, vector(m, 0)); 40 | int ans = 0; 41 | for (int i = 0; i < n; i++) 42 | { 43 | for (int j = 0; j < m; j++) 44 | { 45 | if (grid[i][j] == '1' && vis[i][j] == 0) 46 | { 47 | ans++; 48 | bfs(i, j, vis, grid); 49 | } 50 | } 51 | } 52 | return ans; 53 | } 54 | -------------------------------------------------------------------------------- /Problems/Number-of-Islands/solution.py: -------------------------------------------------------------------------------- 1 | def numIslands(self, grid): 2 | def dfs(x, y): 3 | if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or grid[x][y] != '1': 4 | return 5 | grid[x][y] = '0' 6 | for i, j in [(x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)]: 7 | dfs(i, j) 8 | 9 | if not grid or not grid[0]: 10 | return 0 11 | res = 0 12 | for i in range(len(grid)): 13 | for j in range(len(grid[0])): 14 | if grid[i][j] == '1': 15 | dfs(i, j) 16 | res += 1 17 | return res 18 | -------------------------------------------------------------------------------- /Problems/Odd-Even-Linked-List/README.md: -------------------------------------------------------------------------------- 1 | ## Odd Even Linked List 2 | 3 | Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. 4 | 5 | The **first** node is considered **odd**, and the **second** node is **even**, and so on. 6 | 7 | Note that the relative order inside both the even and odd groups should remain as it was in the input. 8 | 9 | ##### Constraints: 10 | 11 | - The number of nodes in the list is in the range `[0, 10^4]`. 12 | - `-10^6 <= Node.val <= 10^6` 13 | 14 | ##### Reference: 15 | [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) 16 | -------------------------------------------------------------------------------- /Problems/Product-of-the-Last-K-Number/README.md: -------------------------------------------------------------------------------- 1 | ## Product of the Last k Numbers 2 | 3 | Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. 4 | 5 | Implement the `ProductOfNumbers` class: 6 | 7 | - `ProductOfNumbers()` Initializes the object with an empty stream. 8 | - `void add(int num)` Appends the integer num to the stream. 9 | - `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers. 10 | 11 | The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. 12 | 13 | ##### Constraints: 14 | 15 | - `0 <= num <= 100` 16 | - `1 <= `k` <= 4 * 104` 17 | - At most `4 * 10^4` calls will be made to `add` and `getProduct`. 18 | - The product of the stream at any point in time will fit in a **32-bit** integer. 19 | 20 | ##### Reference 21 | [Product of the Last `k` Numbers](https://leetcode.com/problems/product-of-the-last-k-numbers/) 22 | -------------------------------------------------------------------------------- /Problems/Product-of-the-Last-K-Number/Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class product { 4 | public: 5 | vector a; 6 | product() { 7 | a.push_back(1); 8 | } 9 | void add(int num) { 10 | if(num == 0){ 11 | a.clear(); 12 | a.push_back(1); 13 | } 14 | else{ 15 | a.push_back(a.back() * num); 16 | } 17 | } 18 | int Product(int k) { 19 | int n = (int)a.size(); 20 | return k > n - 1? 0 : a[n - 1] / a[n - k - 1]; 21 | } 22 | }; 23 | main(){ 24 | product s; 25 | (s.add(3)); 26 | (s.add(0)); 27 | (s.add(2)); 28 | (s.add(5)); 29 | (s.add(4)); 30 | cout << (s.Product(2)) << endl; 31 | cout << (s.Product(3)) << endl; 32 | cout << (s.Product(4)) << endl; 33 | (s.add(8)); 34 | cout << (s.Product(2)) << endl; 35 | } 36 | -------------------------------------------------------------------------------- /Problems/Remove-K-Digits/README.md: -------------------------------------------------------------------------------- 1 | ## Remove K Digits 2 | 3 | Given string `num` representing a non-negative integer `num`, and an integer `k`, return the _smallest possible integer after removing k digits from `num`_. 4 | 5 | ##### Constraints: 6 | 7 | - `1 <= k <= num.length <= 105` 8 | - `num` consists of only digits. 9 | - `num` does not have any leading zeros except for the zero itself. 10 | 11 | ##### Reference: 12 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) 13 | -------------------------------------------------------------------------------- /Problems/Remove-K-Digits/solution.cpp: -------------------------------------------------------------------------------- 1 | // 1. Deleting k digits means keeping n - k digits, where n is the total number of digits. 2 | 3 | // 2. Use a stack that you keep sorted ascendingly. You remove elements from it as long as you can still make it to n - k digits, 4 | // and your current element is smaller than the top of the stack: 5 | 6 | // push(2) => 2 7 | // push(4) because 2 < 4 => 24 8 | // push(6) because 4 < 6 => 246 9 | // pop() because 3 < 6 and we can still end up with 2 digits => 24 10 | // pop() for the same reason => 2 11 | // push(3) => 23 12 | // push(5) => 235 13 | // Then just take the first k digits => 23. Or you can make sure never to push more than k digits, and then the final stack is your solution. 14 | 15 | // 3. Note that you cannot pop elements if that means you will not be able to build a solution of k digits. 16 | // For this, you need to check the current number of elements in the stack and the number of digits to the right of your current position on the input number. 17 | 18 | 19 | #include 20 | using namespace std; 21 | 22 | string rmvKdigits(string num, int k) { 23 | // number of operation greater than length we return an empty string 24 | if(num.length() <= k) 25 | return "0"; 26 | 27 | // k is 0 , no need of removing / preforming any operation 28 | if(k == 0) 29 | return num; 30 | 31 | string res = "";// result string 32 | stack s; // char stack 33 | 34 | s.push(num[0]); // pushing first character into stack 35 | 36 | for(int i = 1; i 0 && !s.empty() && num[i] < s.top()) 39 | { 40 | // if k greater than 0 and our stack is not empty and the upcoming digit, 41 | // is less than the current top than we will pop the stack top 42 | --k; 43 | s.pop(); 44 | } 45 | 46 | s.push(num[i]); 47 | 48 | // popping preceding zeroes 49 | if(s.size() == 1 && num[i] == '0') 50 | s.pop(); 51 | } 52 | 53 | while(k && !s.empty()) 54 | { 55 | // for cases like "456" where every num[i] > num.top() 56 | --k; 57 | s.pop(); 58 | } 59 | 60 | while(!s.empty()) 61 | { 62 | res.push_back(s.top()); // pushing stack top to string 63 | s.pop(); // pop the top element 64 | } 65 | 66 | reverse(res.begin(),res.end()); // reverse the string 67 | 68 | if(res.length() == 0) 69 | return "0"; 70 | 71 | return res; 72 | 73 | 74 | } 75 | 76 | int main(){ 77 | // we need to take two inputs; 78 | //num = string of non-negative integers 79 | //k = number of allowed removals; 80 | 81 | int k; 82 | string num; 83 | cin>>num>>k; 84 | cout< str: 3 | stack = [] 4 | for n in num: 5 | while( stack and int(stack[-1]) > int(n) and k): 6 | stack.pop() 7 | k -= 1 8 | stack.append(str(n)) 9 | 10 | # If no elements are removed, pop last elements, (increasing order) 11 | while(k): 12 | stack.pop() 13 | k -= 1 14 | 15 | # removing leading zeros 16 | i = 0 17 | while( i 0) else "0" 21 | -------------------------------------------------------------------------------- /Problems/Reorder-List/README.md: -------------------------------------------------------------------------------- 1 | ## Reorder List 2 | 3 | You are given the head of a singly linked-list. The list can be represented as: 4 | 5 | `L0 → L1 → … → Ln - 1 → Ln` 6 | _Reorder the list to be on the following form:_ 7 | 8 | `L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …` 9 | You may not modify the values in the list's nodes. Only nodes themselves may be changed. 10 | 11 | ##### Constraints: 12 | 13 | - The number of nodes in the list is in the range `[1, 5 * 104]`. 14 | - `1 <= Node.val <= 1000` 15 | 16 | ##### Reference: 17 | [Reorder List](https://leetcode.com/problems/reorder-list/) 18 | -------------------------------------------------------------------------------- /Problems/Reorder-List/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reorderList(ListNode* head) { 4 | if ((!head) || (!head->next) || (!head->next->next)) return; // Edge cases 5 | 6 | stack my_stack; 7 | ListNode* ptr = head; 8 | int size = 0; 9 | while (ptr != NULL) // Put all nodes in stack 10 | { 11 | my_stack.push(ptr); 12 | size++; 13 | ptr = ptr->next; 14 | } 15 | 16 | ListNode* pptr = head; 17 | for (int j=0; jnext = pptr->next; 22 | pptr->next = element; 23 | pptr = pptr->next->next; 24 | } 25 | pptr->next = NULL; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Problems/Rotate-List/README.md: -------------------------------------------------------------------------------- 1 | ## Rotate List 2 | 3 | Given the `head` of a linked list, rotate the list to the right by `k` places. 4 | 5 | ##### Constraints: 6 | 7 | - The number of nodes in the list is in the range `[0, 500].` 8 | - `-100 <= Node.val <= 100` 9 | - `0 <= k <= 2 * 10^9` 10 | 11 | ##### Reference: 12 | [Rotate List](https://leetcode.com/problems/rotate-list/) 13 | -------------------------------------------------------------------------------- /Problems/Sequential-Digits/README.md: -------------------------------------------------------------------------------- 1 | ## Sequential Digits 2 | 3 | An integer has _sequential digits_ if and only if each digit in the number is one more than the previous digit. 4 | 5 | Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits. 6 | 7 | ##### Constraints: 8 | 9 | - `10 <= low <= high <= 10^9` 10 | 11 | ##### Reference: 12 | [Sequential Digits](https://leetcode.com/problems/sequential-digits/) 13 | -------------------------------------------------------------------------------- /Problems/Sequential-Digits/solution.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Approach : 3 | Intution 1 : At first I thought, i should try checking every element between low and high , then check. 4 | But after seeing the constraints, I found it would not be the right solution. Constraints ae very high, so its approach would be very simpler that it seems. 5 | 6 | Intution 2: All the elements would contain only 1 to 9 numbers. Then I thought instead of searching I would create the nos in sequential order and then will check the bounds. Then, my friends this approach worked. 7 | 8 | Time Complexity : O(1) 9 | Space Complexity : O(n) , where n is no. of sequential digits between the bound. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | vector sequentialDigits(int low, int high) { 15 | vector result; 16 | int num = 0; 17 | for(int i = 1; i<10 ; i++) 18 | { 19 | num = i; 20 | for(int j = i+1;j<10;j++) 21 | { 22 | num = num*10 + j; 23 | if(num >= low && num <= high) 24 | { 25 | result.push_back(num); 26 | } 27 | } 28 | } 29 | sort(result.begin(), result.end()); 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Problems/Set-Matrix-Zeroes/README.md: -------------------------------------------------------------------------------- 1 | ## Set Matrix Zeroes 2 | 3 | Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. 4 | 5 | You must do it in place. 6 | 7 | ##### Constraints: 8 | 9 | - ` m == matrix.length` 10 | - ` n == matrix[0].length` 11 | - ` 1 <= m, n <= 200` 12 | - ` -231 <= matrix[i][j] <= 231 - 1` 13 | 14 | ##### Reference: 15 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) 16 | -------------------------------------------------------------------------------- /Problems/Set-Matrix-Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | int m[][]=new int[matrix.length][matrix[0].length]; //This temporary matrix(m) will keep record of matrix, i.e. at what place zero's occurs in matrix 4 | 5 | //Traversing matrix 6 | for(int i=0;i>& matrix) { 16 | bool RowZero = false; 17 | bool ColZero = false; 18 | for (int i = 0; i < matrix[0].size(); i++) //check the first row 19 | { 20 | if (matrix[0][i] == 0) 21 | { 22 | RowZero = true; 23 | break; 24 | } 25 | } 26 | for (int i = 0; i < matrix.size(); i++) //check the first column 27 | { 28 | if (matrix[i][0] == 0) 29 | { 30 | ColZero = true; 31 | break; 32 | } 33 | } 34 | for (int i = 1; i < matrix.size(); i++) //check except the first row and column 35 | { 36 | for (int j = 1; j < matrix[0].size(); j++) 37 | { 38 | if (matrix[i][j] == 0) 39 | { 40 | matrix[i][0] = 0; 41 | matrix[0][j] = 0; 42 | } 43 | } 44 | } 45 | for (int i = 1; i < matrix.size(); i++) //process except the first row and column 46 | { 47 | for (int j = 1; j < matrix[0].size(); j++) 48 | { 49 | if (matrix[i][0] == 0 || matrix[0][j] == 0) 50 | { 51 | matrix[i][j] = 0; 52 | 53 | } 54 | } 55 | } 56 | if(RowZero) //handle the first row 57 | { 58 | for (int i = 0; i < matrix[0].size(); i++) 59 | { 60 | matrix[0][i] = 0; 61 | } 62 | } 63 | if (ColZero) //handle the first column 64 | { 65 | for (int i = 0; i < matrix.size(); i++) 66 | { 67 | matrix[i][0] = 0; 68 | } 69 | } 70 | } 71 | }; -------------------------------------------------------------------------------- /Problems/Sort-List/README.md: -------------------------------------------------------------------------------- 1 | ## Sort List 2 | 3 | Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. 4 | 5 | ##### Constraints: 6 | 7 | - The number of nodes in the list is in the range `[0, 5 * 10^4]`. 8 | - `-10^5 <= Node.val <= 10^5` 9 | 10 | ##### Reference: 11 | [Sort List](https://leetcode.com/problems/sort-list/) 12 | -------------------------------------------------------------------------------- /Problems/Sort-List/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | if head is None: 4 | return 5 | arr=[] 6 | while head: 7 | arr.append(head.val) 8 | head=head.next 9 | arr.sort() 10 | dummy=curr=ListNode(0) 11 | for i in arr: 12 | temp=ListNode(i) 13 | curr.next=temp 14 | curr=curr.next 15 | return dummy.next 16 | -------------------------------------------------------------------------------- /Problems/Split-Linked-List-in-Parts/README.md: -------------------------------------------------------------------------------- 1 | ## Split Linked List in Parts 2 | 3 | Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. 4 | 5 | The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. 6 | 7 | The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. 8 | 9 | Return _an array of the `k` parts_. 10 | 11 | ##### Constraints: 12 | 13 | - The number of nodes in the list is in the range `[0, 1000].` 14 | - `0 <= Node.val <= 1000` 15 | - `1 <= k <= 50` 16 | 17 | ##### Reference: 18 | [Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/) 19 | -------------------------------------------------------------------------------- /Problems/Sum-Root-to-Leaf-Numbers/README.md: -------------------------------------------------------------------------------- 1 | ## Sum Root to Leaf Numbers 2 | 3 | You are given the `root` of a binary tree containing digits from `0` to `9` only. 4 | 5 | Each root-to-leaf path in the tree represents a number. 6 | 7 | - For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. 8 | Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. 9 | 10 | A **leaf** node is a node with no children. 11 | 12 | ##### Constraints: 13 | 14 | - The number of nodes in the tree is in the range `[1, 1000]`. 15 | - `0 <= Node.val <= 9` 16 | - The depth of the tree will not exceed `10`. 17 | 18 | ##### Reference: 19 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) 20 | -------------------------------------------------------------------------------- /Problems/Sum-Root-to-Leaf-Numbers/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumNumbers1(self, root): # DFS recursively 3 | self.res = 0 4 | self.dfs(root, 0) 5 | return self.res 6 | 7 | def dfs(self, root, path): 8 | if root: 9 | if not root.left and not root.right: 10 | path = path*10 + root.val 11 | self.res += path 12 | self.dfs(root.left, path*10+root.val) 13 | self.dfs(root.right, path*10+root.val) 14 | 15 | def sumNumbers2(self, root): # BFS with queue 16 | deque, res = collections.deque(), 0 17 | if root: 18 | deque.append(root) 19 | while deque: 20 | node = deque.popleft() 21 | if not node.left and not node.right: 22 | res += node.val 23 | if node.left: 24 | node.left.val += node.val*10 25 | deque.append(node.left) 26 | if node.right: 27 | node.right.val += node.val*10 28 | deque.append(node.right) 29 | return res 30 | 31 | def sumNumbers(self, root): # DFS with stack 32 | stack, res = [], 0 33 | if root: 34 | stack.append(root) 35 | while stack: 36 | node = stack.pop() 37 | if not node.left and not node.right: 38 | res += node.val 39 | if node.right: 40 | node.right.val += node.val*10 41 | stack.append(node.right) 42 | if node.left: 43 | node.left.val += node.val*10 44 | stack.append(node.left) 45 | return res 46 | -------------------------------------------------------------------------------- /Problems/Swap-Nodes-in-Pairs/README.md: -------------------------------------------------------------------------------- 1 | ## Swap Nodes in Pairs 2 | 3 | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 4 | 5 | ##### Constraints: 6 | 7 | - The number of nodes in the list is in the range `[0, 100]`. 8 | - `0 <= Node.val <= 100` 9 | 10 | ##### Reference: 11 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) 12 | -------------------------------------------------------------------------------- /Problems/Swap-Nodes-in-Pairs/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* swapPairs(ListNode* head) 4 | { 5 | ListNode* curr=head; 6 | while(curr!=NULL&&curr->next!=NULL) 7 | { 8 | swap(curr->val,curr->next->val); 9 | curr=curr->next->next; 10 | } 11 | return head; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Problems/Swapping-Nodes-in-a-Linked-List/README.md: -------------------------------------------------------------------------------- 1 | ## Swapping Nodes in a Linked List 2 | 3 | You are given the `head` of a linked list, and an integer `k`. 4 | 5 | Return _the head of the linked list after **swapping** the values of the `kth` node from the beginning and the `kth` node from the end (the list is **1-indexed**)_. 6 | 7 | ##### Constraints: 8 | 9 | - The number of nodes in the list is `n`. 10 | - `1 <= k <= n <= 10^5` 11 | - `0 <= Node.val <= 100` 12 | 13 | ##### Reference: 14 | [Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) 15 | -------------------------------------------------------------------------------- /Problems/Unique-Binary-Search-Trees/README.md: -------------------------------------------------------------------------------- 1 | ## Unique Binary Search Trees 2 | 3 | Given an integer `n`, _return the number of structurally unique **BST's** (binary search trees) which has exactly `n` nodes of unique values from `1` to `n`_. 4 | 5 | ##### Constraints: 6 | 7 | - `1 <= n <= 19` 8 | 9 | ##### Reference: 10 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) 11 | -------------------------------------------------------------------------------- /Problems/Unique-Binary-Search-Trees/Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int numberOfBST(int n) 6 | { 7 | 8 | 9 | int dp[n + 1]; 10 | fill_n(dp, n + 1, 0); 11 | 12 | // Base case 13 | dp[0] = 1; 14 | dp[1] = 1; 15 | 16 | 17 | for (int i = 2; i <= n; i++) { 18 | for (int j = 1; j <= i; j++) { 19 | 20 | // n-i in right * i-1 in left 21 | dp[i] = dp[i] + (dp[i - j] * dp[j - 1]); 22 | } 23 | } 24 | 25 | return dp[n]; 26 | } 27 | 28 | // Driver Code 29 | int main() 30 | { 31 | int N = 3; 32 | 33 | cout << "Number of structurally Unique BST with " << N 34 | << " keys are : " << numberOfBST(N) << "\n"; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Problems/Valid-Sudoku/README.md: -------------------------------------------------------------------------------- 1 | ## Valid Sudoku 2 | 3 | Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 4 | 5 | Each row must contain the digits `1-9` without repetition. 6 | Each column must contain the digits `1-9` without repetition. 7 | Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. 8 | 9 | **Note**: 10 | - A Sudoku board (partially filled) could be valid but is not necessarily solvable. 11 | - Only the filled cells need to be validated according to the mentioned rules. 12 | 13 | ##### Constraints: 14 | 15 | - `board.length == 9` 16 | - `board[i].length == 9` 17 | - `board[i][j]` is a digit `1-9` or '.'. 18 | 19 | ##### Reference: 20 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) 21 | -------------------------------------------------------------------------------- /Problems/Valid-Sudoku/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | bool notInRow(char arr[][9], int row) 6 | { 7 | set st; 8 | 9 | for (int i = 0; i < 9; i++) { 10 | 11 | if (st.find(arr[row][i]) != st.end()) 12 | return false; 13 | 14 | 15 | if (arr[row][i] != '.') 16 | st.insert(arr[row][i]); 17 | } 18 | return true; 19 | } 20 | 21 | 22 | bool notInCol(char arr[][9], int col) 23 | { 24 | set st; 25 | 26 | for (int i = 0; i < 9; i++) { 27 | 28 | if (st.find(arr[i][col]) != st.end()) 29 | return false; 30 | 31 | 32 | if (arr[i][col] != '.') 33 | st.insert(arr[i][col]); 34 | } 35 | return true; 36 | } 37 | 38 | 39 | bool notInBox(char arr[][9], int startRow, int startCol) 40 | { 41 | set st; 42 | 43 | for (int row = 0; row < 3; row++) { 44 | for (int col = 0; col < 3; col++) { 45 | char curr = arr[row + startRow][col + startCol]; 46 | 47 | if (st.find(curr) != st.end()) 48 | return false; 49 | 50 | 51 | if (curr != '.') 52 | st.insert(curr); 53 | } 54 | } 55 | return true; 56 | } 57 | 58 | 59 | bool isValid(char arr[][9], int row, int col) 60 | { 61 | return notInRow(arr, row) && notInCol(arr, col) 62 | && notInBox(arr, row - row % 3, col - col % 3); 63 | } 64 | 65 | bool isValidConfig(char arr[][9], int n) 66 | { 67 | for (int i = 0; i < n; i++) { 68 | for (int j = 0; j < n; j++) { 69 | 70 | 71 | if (!isValid(arr, i, j)) 72 | return false; 73 | } 74 | } 75 | return true; 76 | } 77 | 78 | int main() 79 | { 80 | char board[9][9] 81 | = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, 82 | { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, 83 | { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, 84 | { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, 85 | { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, 86 | { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, 87 | { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, 88 | { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, 89 | { '.', '.', '.', '.', '8', '.', '.', '7', 90 | '9' } }; 91 | 92 | cout << (isValidConfig(board, 9) ? "YES\n" : "NO\n"); 93 | return 0; 94 | } -------------------------------------------------------------------------------- /Problems/Valid-Sudoku/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | byte[] arr = new byte[10]; 4 | for (int row = 0; row < 9; row++) { 5 | for (int col = 0; col < 9; col++) { 6 | char c = board[row][col]; 7 | if (c == '.') continue; 8 | if (arr[c - '0'] > 0) { 9 | return false; 10 | } else { 11 | arr[c - '0']++; 12 | } 13 | } 14 | clearArray(arr); 15 | } 16 | for (int col = 0; col < 9; col++) { 17 | for (int row = 0; row < 9; row++) { 18 | char c = board[row][col]; 19 | if (c == '.') continue; 20 | if (arr[c - '0'] > 0) { 21 | return false; 22 | } else { 23 | arr[c - '0']++; 24 | } 25 | } 26 | clearArray(arr); 27 | } 28 | for (int row = 0; row < 9; row += 3) { 29 | for (int col = 0; col < 9; col += 3) { 30 | for (int r = 0; r < 3; r++) { 31 | for (int c = 0; c < 3; c++) { 32 | char ch = board[row + r][col + c]; 33 | if (ch == '.') continue; 34 | if (arr[ch - '0'] > 0) { 35 | return false; 36 | } else { 37 | arr[ch - '0']++; 38 | } 39 | } 40 | } 41 | clearArray(arr); 42 | } 43 | } 44 | return true; 45 | } 46 | 47 | private void clearArray(byte[] arr) { 48 | for (int i = 0; i < arr.length; i++) { 49 | arr[i] = 0; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Problems/Valid-Sudoku/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board: List[List[str]]) -> bool: 3 | rows = [{} for i in range(9)] 4 | columns = [{} for i in range(9)] 5 | boxes = [{} for i in range(9)] 6 | 7 | for i in range(9): 8 | for j in range(9): 9 | num = board[i][j] 10 | if num != '.': 11 | box_index = (i // 3) * 3 + j // 3 12 | 13 | rows[i][num] = rows[i].get(num, 0) + 1 14 | columns[j][num] = columns[j].get(num, 0) + 1 15 | boxes[box_index][num] = boxes[box_index].get(num, 0) + 1 16 | 17 | if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1: 18 | return False 19 | return True 20 | -------------------------------------------------------------------------------- /Problems/Wiggle-Sort-II/README.md: -------------------------------------------------------------------------------- 1 | ## Wiggle Sort II 2 | 3 | Given an integer array `nums`, reorder it such that `nums[0] < nums[1] > nums[2] < nums[3]....` 4 | 5 | You may assume the input array always has a valid answer. 6 | 7 | ##### Constraints: 8 | 9 | - `1 <= nums.length <= 5 * 104` 10 | - `0 <= nums[i] <= 5000` 11 | - It is guaranteed that there will be an answer for the given input `nums.` 12 | 13 | ##### Reference: 14 | [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) 15 | -------------------------------------------------------------------------------- /Problems/Wiggle-Sort-II/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void wiggleSort(vector& nums) { 5 | int n=nums.size(); 6 | sort(nums.begin(),nums.end()); 7 | vectorans(n,0); 8 | int k=1; 9 | int i=n-1; 10 | while(k>n; 31 | vector arr(n); //arr to store input; 32 | for(int i=0;i>arr[i]; 33 | wiggleSort(arr); 34 | for(int i=0;ithis repository. 34 | 35 | 1. Fork this repository. 36 | 37 | 2. Clone the forked repository. 38 | 39 | ```bash 40 | git clone https://github.com//dsa-problems 41 | ``` 42 | 43 | 3. Navigate to the project directory. 44 | 45 | ```bash 46 | cd dsa-problems 47 | ``` 48 | 49 | 4. Create a new branch. 50 | 51 | ```bash 52 | git checkout -b 53 | ``` 54 | 55 | 5. Make changes. 56 | 57 | 6. Add your name and username to the [List of contributer](contributers/README.md).
58 | 59 | ```md 60 | - [Your Name] | [Github username] 61 | ``` 62 | 63 | 7. Stage your changes and commit 64 | 65 | ```bash 66 | git add -A 67 | 68 | git commit -m "" 69 | ``` 70 | 71 | 8. Push your local commits to the remote repo. 72 | 73 | ```bash 74 | git push -u origin 75 | ``` 76 | 77 | 9. Create a Pull Request. 78 | 79 | 10. Congratulations! 🎉 you've made your contribution. 80 | 81 | --- 82 | -------------------------------------------------------------------------------- /images/Logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gdscjec/Data-Structure-Problems/adb140d5366a7dde3ef8b2f748aae9ad869d8c14/images/Logo.jpg --------------------------------------------------------------------------------