├── .gitignore ├── .markdownlint.json ├── .vscode └── qa-template.code-snippets ├── Cpp └── README.md ├── Java ├── 0001-two-sum │ ├── q-two-sum.md │ └── two-sum.md ├── 0217-contains-duplicate │ ├── contains-duplicate.md │ └── q-contains-duplicate.md ├── 0242-valid-anagram │ ├── q-valid-anagram.md │ └── valid-anagram.md └── README.md ├── Javascript ├── 0001-two-sum │ ├── q-two-sum.md │ ├── two-sum-hash.md │ └── two-sum.md ├── 0049-group-anagram │ ├── group-anagram.md │ └── q-group-anagram.md ├── 0217-contains-duplicate │ ├── contains-duplicate.md │ └── q-contains-duplicate.md ├── 0242-valid-anagram │ ├── q-valid-anagram.md │ └── valid-anagram.md └── README.md ├── LICENSE ├── Python ├── 0000-template │ ├── 1-answer.md │ └── question.md ├── 0001-two-sum │ ├── 1-answer.md │ ├── 2-answer.md │ └── question.md ├── 0020-valid-parentheses │ ├── 1-answer.md │ └── question.md ├── 0021-merge-two-sorted-lists │ ├── 1-answer.md │ ├── img │ │ └── merge_ex1.jpg │ └── question.md ├── 0049-group-anagram │ ├── 1-answer.md │ └── question.md ├── 0121-best-time-to-buy-and-sell-stock │ ├── 1-answer.md │ ├── 2-answer.md │ └── question.md ├── 0125-valid-palindrome │ ├── 1-answer.md │ └── question.md ├── 0155-min-stack │ ├── 1-answer.md │ └── question.md ├── 0167-two-sum-2 │ ├── 1-answer.md │ └── question.md ├── 0206-reverse-linked-list │ ├── 1-answer.md │ ├── 2-answer.md │ ├── img │ │ ├── rev1ex1.jpg │ │ └── rev1ex2.jpg │ └── question.md ├── 0217-contains-duplicate │ ├── 1-answer.md │ └── question.md ├── 0238-product-of-array-except-self │ ├── 1-answer.md │ └── question.md ├── 0242-valid-anagram │ ├── 1-answer.md │ └── question.md ├── 0347-top-k-frequent-elements │ ├── 1-answer.md │ └── question.md ├── 0704-binary-search │ ├── 1-answer.md │ └── question.md └── README.md ├── README.md └── Rust ├── 0001-two-sum ├── question.md └── two-sum.md ├── 0020-valid-parentheses ├── 1-answer.md └── question.md ├── 0049-group-anagram ├── group-anagram.md └── question.md ├── 0121-best-time-to-buy-and-sell-stock ├── 1-answer.md └── question.md ├── 0125-valid-palindrome ├── 1-answer.md └── question.md ├── 0155-min-stack ├── 1-answer.md ├── 2-answer.md └── question.md ├── 0167-two-sum-2 ├── 1-answer.md └── question.md ├── 0206-reverse-linked-list ├── 1-answer.md ├── img │ ├── rev1ex1.jpg │ └── rev1ex2.jpg └── question.md ├── 0217-contains-duplicate ├── 1-answer.md └── question.md ├── 0238-product-of-array-except-self ├── 1-answer.md └── question.md ├── 0242-valid-anagram ├── question.md └── valid-anagram.md ├── 0347-top-k-frequent-elements ├── 1-answer.md └── question.md ├── 0704-binary-search ├── 1-answer.md └── question.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | 3 | turkce-cevap.md 4 | turkce-soru.md 5 | -------------------------------------------------------------------------------- /.markdownlint.json: -------------------------------------------------------------------------------- 1 | { 2 | "default": true, 3 | "MD013": false, 4 | "MD033": false 5 | } -------------------------------------------------------------------------------- /.vscode/qa-template.code-snippets: -------------------------------------------------------------------------------- 1 | { 2 | "Leetcode Problem Template": { 3 | "prefix": "mdproblem", 4 | "body": [ 5 | "# [${6:Header}](${7:Link})", 6 | "", 7 | "## 🚨 Problem", 8 | "", 9 | "${1:Explain the problem}", 10 | "", 11 | "**Example 1:**", 12 | "", 13 | "", 14 | ">**Input:** ${2}
", 15 | "**Output:** ${3}
", 16 | "**Explanation:** ${4} ", 17 | "", 18 | "**Constraints:**", 19 | "", 20 | "- ${5}", 21 | "", 22 | "**Follow-up:** ", 23 | "", 24 | "", 25 | "## 🔐 Solutions", 26 | "", 27 | "", 28 | "| ID | METHOD |", 29 | "| :-- | :--------------------: |", 30 | "| 1 | [example](1-answer.md) |", 31 | "" 32 | ], 33 | "description": "It creates a problem template for leetcode" 34 | }, 35 | "Leetcode Solution Template": { 36 | "prefix": "mdsolution", 37 | "body": [ 38 | "# [${6:Header}](${7:link})", 39 | "", 40 | "## 🧑🏻‍💻 Approach", 41 | "", 42 | "${1:Explain the approach}", 43 | "", 44 | "## 🔐 Code", 45 | "", 46 | "``` ${2:Programming language}", 47 | "${3:printf(\"Hello World\");}", 48 | "```", 49 | "", 50 | "## 🧩 Complexity", 51 | "", 52 | "- Time complexity:", 53 | "", 54 | "${4:Time Complexity}", 55 | "", 56 | "- Space complexity:", 57 | "", 58 | "${5:Space Complexity}", 59 | "" 60 | ], 61 | "description": "It creates a solution template for leetcode problem" 62 | }, 63 | "Leetcode Example Template": { 64 | "prefix": "mdexample", 65 | "body": [ 66 | "**Example ${1}:**", 67 | "", 68 | "", 69 | ">**Input:** ${2}
", 70 | "**Output:** ${3}
", 71 | ], 72 | "description": "It creates a example template for leetcode problem" 73 | }, 74 | "Leetcode Example Template w/ Explanation": { 75 | "prefix": "mdexamplewithexplanation", 76 | "body": [ 77 | "**Example ${1}:**", 78 | "", 79 | "", 80 | ">**Input:** ${2}
", 81 | "**Output:** ${3}
", 82 | "**Explanation:** ${4} ", 83 | "" 84 | ], 85 | "description": "It creates a example template with explanation for leetcode problem" 86 | }, 87 | "Leetcode Heading Template for Solution": { 88 | "prefix": "mdheading", 89 | "body": [ 90 | "✅ ${1:Method} to solve the 🧑🏻‍💻 ${2:Question Name} Problem on 🐍 ${3:Language Name}" 91 | ], 92 | "description": "It creates a heading for leetcode solution" 93 | } 94 | } -------------------------------------------------------------------------------- /Cpp/README.md: -------------------------------------------------------------------------------- 1 |
2 |

Awesome Leetcode Algorithms Solututions With C++

3 | 4 | 5 | 6 | 7 | Twitter Follow 8 | 9 | 10 | Author: 11 | Samet Aydın
12 | June, 2023 13 |
14 |
15 | 16 | ## Introduction 17 | 18 | Welcome to the solutions of leetcode algorithms with C++. 19 | 20 | ## How to Use It? 21 | 22 | I suggest cloning the repository locally to work with it, but you can easily look at any solution you want without cloning it. Simply press `Ctrl + F` and type the name of the question or its ID. Each folder includes an .md file that you can click on to go to the Leetcode website. There are two parts of questions: 23 | 24 | 1. Problem:
This part includes the definition of the problem, example cases, input and output examples, constraints, and follow-up information. 25 | 2. Solution:
This part includes a table to navigate to the solutions. 26 | 27 | ## Solutions 28 | 29 | Each .md file for a solution includes: 30 | 31 | - Header (that navigates to the online explanation of the solution) 32 | - Approach (describing the approach to solving the problem) 33 | - Complexity (determining the time and space complexity of the solution) 34 | - Code (the actual solution to the problem) 35 | 36 | | ID | Question Name | 37 | |:-----|:------------------------------------------------------------------:| 38 | | 0001 | [Two Sum](0001-two-sum/q-two-sum.md) | 39 | | 0217 | [Duplicate Array](0217-contains-duplicate/q-contains-duplicate.md) | 40 | | 0242 | [Valid Anagram](0242-valid-anagram/q-valid-anagram.md) | -------------------------------------------------------------------------------- /Java/0001-two-sum/q-two-sum.md: -------------------------------------------------------------------------------- 1 | # [1. Two Sum](https://leetcode.com/problems/two-sum) 2 | 3 | ## Problem 4 | 5 | Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. 6 | 7 | You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. 8 | 9 | You can return the answer in any order. 10 | 11 | **Example 1:** 12 | 13 | >**Input:** nums = \[2,7,11,15\], target = 9
14 | **Output:** \[0,1\]
15 | **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. 16 | 17 | **Example 2:** 18 | 19 | >**Input:** nums = \[3,2,4\], target = 6
20 | **Output:** \[1,2\] 21 | 22 | **Example 3:** 23 | 24 | >**Input:** nums = \[3,3\], target = 6
25 | **Output:** \[0,1\] 26 | 27 | **Constraints:** 28 | 29 | - $2 <= nums.length <= 10^4$ 30 | - $-10^9 <= nums[i] <= 10^9$ 31 | - $-10^9 <= target <= 10^9$ 32 | - **Only one valid answer exists.** 33 | 34 | **Follow-up:** Can you come up with an algorithm that is less than $O(n^2)$ time complexity? 35 | 36 | ## Solutions 37 | 38 | | ID | METHOD | LINK | 39 | | :-- | :---------: | :--------------------------------- | 40 | | 1 | Brute Force | [two-sum.md](two-sum.md) | -------------------------------------------------------------------------------- /Java/0001-two-sum/two-sum.md: -------------------------------------------------------------------------------- 1 | # [Brute Force to solve the Two-Sum Problem on Java language](https://leetcode.com/problems/two-sum/solutions/3576463/less-than-o-n-2-time-complexity-in-java) 2 | 3 | ## Approach 4 | The brute-force approach to solving the two-sum problem involves checking every possible pair of elements in the array and comparing their sum to the target. This can be achieved by using two nested loops, where each loop iterates through all the elements in the array. In each iteration, the current pair of elements is checked to see if their sum is equal to the target. If a match is found, the indices of the elements are stored and returned as the solution. The idea is to go through all the possible combinations of elements and check if any of them add up to the target. It's a straightforward approach that doesn't require any complex algorithms or data structures, making it easy to understand and implement. 5 | 6 | ## Complexity 7 | 8 | - Time complexity: O(n) 9 | - Space complexity: O(1) 10 | ## Code 11 | 12 | ``` java 13 | class Solution { 14 | public int[] twoSum(int[] nums, int target) { 15 | int tempNumber = target - nums[0]; 16 | for(int i = 1, k = 0; i <= nums.length - 1;){ 17 | if(tempNumber == nums[i]) { 18 | return new int[]{k, i}; 19 | } 20 | if(i == nums.length - 1) { 21 | k++; 22 | i = k; 23 | tempNumber = target - nums[k]; 24 | } 25 | i++; 26 | } 27 | return null; 28 | } 29 | } 30 | ``` 31 | -------------------------------------------------------------------------------- /Java/0217-contains-duplicate/contains-duplicate.md: -------------------------------------------------------------------------------- 1 | # [HashMap Duplicate Array problem solution in Java language](https://leetcode.com/problems/contains-duplicate/solutions/3579963/hashmap-o-n-time-complexity-solution-in-java/) 2 | 3 | ## Intuition 4 | Firstly, I have an idea which is iterated array with loop. I prefer foreach loop to visit every element of array. And then, i choose a data structure for hold a value with key of the array index. Hashmap or HashSet is good choice for time complexity and space complexity. 5 | 6 | ## Approach 7 | I choose a Hashmap Data structure for hold array value to key of Hashmap. Because, it good at control to duplicate array value. What is the good at? It means that Hashmap hold key value pairs. If key added before, return **true**, if not return **false**. 8 | ## Complexity 9 | 10 | - Time complexity: O(n) 11 | - Space complexity: O(1) 12 | ## Code 13 | 14 | ``` java 15 | class Solution { 16 | public boolean containsDuplicate(int[] nums) { 17 | HashMap duplicate = new HashMap(); 18 | for(int num : nums) { 19 | if(duplicate.containsKey(num)){ 20 | return true; 21 | } 22 | duplicate.put(num, 1); 23 | } 24 | return false; 25 | } 26 | } 27 | ``` 28 | -------------------------------------------------------------------------------- /Java/0217-contains-duplicate/q-contains-duplicate.md: -------------------------------------------------------------------------------- 1 | # [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) 2 | 3 | ## Problem 4 | 5 | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:** nums = \[1,2,3,1\]
11 | **Output:** true
12 | 13 | **Constraints:** 14 | 15 | - $1 <= nums.length <= 10^5$ 16 | - $-10^9 <= nums[i] <= 10^9$ 17 | 18 | ## Solutions 19 | 20 | 21 | | ID | METHOD | LINK | 22 | | :-- |:-------:|:--------------------------------------------| 23 | | 1 | HashMap | [contains-duplicate](contains-duplicate.md) | 24 | -------------------------------------------------------------------------------- /Java/0242-valid-anagram/q-valid-anagram.md: -------------------------------------------------------------------------------- 1 | # [Valid Anagram](https://leetcode.com/problems/valid-anagram/) 2 | 3 | ## Problem 4 | 5 | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** s = "anagram", t = "nagaram"
13 | **Output:** true
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** s = "rat", t = "car"
19 | **Output:** false
20 | 21 | **Constraints:** 22 | 23 | - $1 <= s.length, t.length <= 5 * 10^4$ 24 | - `s` and `t` consist of lowercase English letters. 25 | 26 | **Follow-up:** 27 | 28 | What if the inputs contain Unicode characters? How would you adapt your solution to such a case? 29 | 30 | ## Solutions 31 | 32 | 33 | | ID | METHOD | LINK | 34 | | :-- |:------------------------------:| :----------------------------------- | 35 | | 1 | Sort, Split and Equality Check | [valid-anagram.md](valid-anagram.md) | 36 | -------------------------------------------------------------------------------- /Java/0242-valid-anagram/valid-anagram.md: -------------------------------------------------------------------------------- 1 | # Intuition 2 | First of all, i need char sequence of two strings. And then, they are not sorting by any kind of method. This method needs sorting function about how to sort character array. At the end of the process, equality check is the main operation between two array. 3 | 4 | # Approach 5 | The main process is that we have to split all strings. We have just only two string -> s and t. So, String to character array is completed by toCharArray() built-in method. And then check the length of character arrays. If not equal length of whole array, return false situation. And then if equal, sort each character arrays and equality check between t char array to s char array. 6 | 7 | # Complexity 8 | - Time complexity: O(nlogn) 9 | 10 | - Space complexity: O(n) 11 | 12 | # Code 13 | ```java 14 | class Solution { 15 | public boolean isAnagram(String s, String t) { 16 | char[] tmpS = s.toCharArray(); 17 | char[] tmpT = t.toCharArray(); 18 | if(tmpS.length != tmpT.length) { 19 | return false; 20 | } 21 | Arrays.sort(tmpS); 22 | Arrays.sort(tmpT); 23 | return Arrays.equals(tmpS,tmpT); 24 | } 25 | } 26 | ``` -------------------------------------------------------------------------------- /Java/README.md: -------------------------------------------------------------------------------- 1 |
2 |

Awesome Leetcode Algorithms Solututions With Java

3 | 4 | 5 | 6 | 7 | Twitter Follow 8 | 9 | 10 | Author: 11 | Hanifi Çağrı Demirtaş
12 | February, 2023 13 |
14 |
15 | 16 | ## Introduction 17 | 18 | Welcome to the solutions of leetcode algorithms with Java. 19 | 20 | ## How to Use It? 21 | 22 | I suggest cloning the repository locally to work with it, but you can easily look at any solution you want without cloning it. Simply press `Ctrl + F` and type the name of the question or its ID. Each folder includes an .md file that you can click on to go to the Leetcode website. There are two parts of questions: 23 | 24 | 1. Problem:
This part includes the definition of the problem, example cases, input and output examples, constraints, and follow-up information. 25 | 2. Solution:
This part includes a table to navigate to the solutions. 26 | 27 | ## Solutions 28 | 29 | Each .md file for a solution includes: 30 | 31 | - Header (that navigates to the online explanation of the solution) 32 | - Approach (describing the approach to solving the problem) 33 | - Complexity (determining the time and space complexity of the solution) 34 | - Code (the actual solution to the problem) 35 | 36 | | ID | Question Name | 37 | |:-----|:------------------------------------------------------------------:| 38 | | 0001 | [Two Sum](0001-two-sum/q-two-sum.md) | 39 | | 0217 | [Duplicate Array](0217-contains-duplicate/q-contains-duplicate.md) | 40 | | 0242 | [Valid Anagram](0242-valid-anagram/q-valid-anagram.md) | -------------------------------------------------------------------------------- /Javascript/0001-two-sum/q-two-sum.md: -------------------------------------------------------------------------------- 1 | # [1. Two Sum](https://leetcode.com/problems/two-sum) 2 | 3 | ## Problem 4 | 5 | Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. 6 | 7 | You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. 8 | 9 | You can return the answer in any order. 10 | 11 | **Example 1:** 12 | 13 | >**Input:** nums = \[2,7,11,15\], target = 9
14 | **Output:** \[0,1\]
15 | **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. 16 | 17 | **Example 2:** 18 | 19 | >**Input:** nums = \[3,2,4\], target = 6
20 | **Output:** \[1,2\] 21 | 22 | **Example 3:** 23 | 24 | >**Input:** nums = \[3,3\], target = 6
25 | **Output:** \[0,1\] 26 | 27 | **Constraints:** 28 | 29 | - $2 <= nums.length <= 10^4$ 30 | - $-10^9 <= nums[i] <= 10^9$ 31 | - $-10^9 <= target <= 10^9$ 32 | - **Only one valid answer exists.** 33 | 34 | **Follow-up:** Can you come up with an algorithm that is less than $O(n^2)$ time complexity? 35 | 36 | ## Solutions 37 | 38 | | ID | METHOD | LINK | 39 | | :-- | :---------: | :--------------------------------- | 40 | | 1 | Brute Force | [two-sum.md](two-sum.md) | 41 | | 2 | Hash Table | [two-sum-hash.md](two-sum-hash.md) | -------------------------------------------------------------------------------- /Javascript/0001-two-sum/two-sum-hash.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cukurovablock/awesome-leetcode-algorithms-solutions/5bc0ac7aad4074968d39cee125ab49707f6e6d4b/Javascript/0001-two-sum/two-sum-hash.md -------------------------------------------------------------------------------- /Javascript/0001-two-sum/two-sum.md: -------------------------------------------------------------------------------- 1 | # [Solving the Two Sums Problem in JavaScript](https://leetcode.com/problems/two-sum/solutions/3576742/solving-the-two-sums-problem-in-javascript/) 2 | 3 | ## Approach 4 | 5 | The brute-force approach to solving the two-sum problem involves checking every possible pair of elements in the array and comparing their sum to the target. This can be achieved by using two nested loops, where each loop iterates through all the elements in the array. In each iteration, the current pair of elements is checked to see if their sum is equal to the target. If a match is found, the indices of the elements are stored and returned as the solution. The idea is to go through all the possible combinations of elements and check if any of them add up to the target. It's a straightforward approach that doesn't require any complex algorithms or data structures, making it easy to understand and implement. 6 | 7 | ## Complexity 8 | 9 | - Time complexity:O(n^2) 10 | 11 | The time complexity of the brute-force approach for solving the two-sum problem is $O(n^2)$, where n is the size of the input array. This means that the algorithm's performance will be proportional to the square of the size of the array. 12 | 13 | In each iteration of the outer loop, the inner loop will also iterate through all the elements in the array. So, the number of operations performed by the algorithm is proportional to the product of the number of iterations of the outer loop and the inner loop. The outer loop iterates n times, and the inner loop iterates $n-1$ times on the first iteration, $n-2$ times on the second iteration, and so on. So, the total number of iterations is $n * (n-1) / 2$, which is equivalent to $n^2/2 - n/2$. This results in a time complexity of $O(n^2)$. 14 | 15 | This means that as the size of the array grows, the number of operations performed by the algorithm will increase rapidly, making it inefficient for large arrays. 16 | 17 | - Space complexity:O(1) 18 | 19 | The space complexity of the brute-force approach for solving the two-sum problem is $O(1)$. This means that the amount of memory used by the algorithm is constant and does not depend on the size of the input array. 20 | 21 | In this approach, we use two integer variables, `i` and `j`, to store the indices of the elements in the array. These variables are used as pointers to access the elements in the array and do not increase in size as the size of the array grows. 22 | 23 | We also use a constant amount of memory to store the answer, which is an array of two integers. This array is dynamically allocated using malloc, and its size does not depend on the size of the input array. 24 | 25 | Therefore, the space complexity of the algorithm is $O(1)$, which means that it uses a constant amount of memory, regardless of the size of the input array. 26 | 27 | ## Code 28 | 29 | ``` javascript 30 | var twoSum = function(nums, target) { 31 | for(let i = 0; i < nums.length; i++) { 32 | for(let j = i + 1; j < nums.length; j++) { 33 | if (nums[i] + nums[j] === target) { 34 | return [i, j]; 35 | } 36 | } 37 | } 38 | }; 39 | ``` 40 | -------------------------------------------------------------------------------- /Javascript/0049-group-anagram/group-anagram.md: -------------------------------------------------------------------------------- 1 | # [🔥🔠 Anagram Grouping: Explore the Shortest Path with JavaScript! 🧩🔎✨](https://leetcode.com/problems/group-anagrams/solutions/3586360/anagram-grouping-explore-the-shortest-path-with-javascript/) 2 | 3 | 4 | ## Approach 5 | The code follows the following approach to group anagrams: 6 | 7 | 1- Create an empty object anagramGroups. This object will be used to store the anagram groups. 8 | 9 | 2- Iterate through each string `(str)` in the input array `(strs)`. 10 | 11 | 3- Sort the characters of the string `(str)` in alphabetical order. This will ensure that all anagrams have the same sorted string representation. Convert the sorted string back to its original form using `.join('')`. 12 | 13 | 4- Check if the sorted string exists as a key in the `anagramGroups` object. If it exists, push the original string `(str)` to the corresponding group array. If it doesn't exist, create a new `key-value` pair in the anagramGroups object, with the sorted string as the key and an array containing the original string as the value. 14 | 15 | 5- After iterating through all strings, convert the values of the anagramGroups object into an array using Object.values`(anagramGroups)`. This will give an array of arrays, where each inner array represents an anagram group. 16 | 17 | 6- Sort the resulting array of anagram groups based on their lengths using the `.sort()` method. The comparison function `(a, b) => a.length - b.length` compares the lengths of the inner arrays and sorts them in ascending order. 18 | 19 | 7- Return the sorted array of anagram groups. 20 | 21 | This approach uses the sorted string representation of each string to group anagrams together. By comparing the sorted strings, we can identify which strings belong to the same anagram group. 22 | ## Complexity 23 | 24 | - Time complexity:O(n∗(mlogm))+O(nlogn) 25 | 26 | The time complexity of this code can be analyzed as follows: 27 | 28 | Loop (for...of): This loop iterates over the strs array, so the complexity is `O(n)`, where n is the length of the strs array. 29 | 30 | String Operations: In each iteration of the loop, the following operations are performed on the current string str: 31 | 32 | .split(''): Converting the string into an array of characters. This operation has a complexity of `O(m)`, where m is the length of the string. 33 | .sort(): Sorting the array of characters. The sorting algorithm used can vary depending on the JavaScript engine, but typically a fast sorting algorithm like quicksort is used, which has an average complexity of `O(mlogm)`. 34 | `.join('')`: Converting the sorted array of characters back into a string. This operation also has a complexity of `O(m)`, where m is the length of the string. 35 | Adding to the Object: In each iteration of the loop, the sorted string (sortedStr) is used to access the groupAnagram object and add the string to the corresponding array. This operation has a complexity of `O(1)`. 36 | 37 | Result Creation and Sorting: After the loop is completed, the values of the groupAnagram object are converted into an array using `Object.values()`. This operation has a complexity of `O(n)`. Then, the array is sorted based on the lengths of the groups using `.sort()`. The sorting operation has an average complexity of `O(nlogn)` using a fast sorting algorithm like quicksort. 38 | 39 | Therefore, the overall time complexity of the code is `O(n∗(mlogm))+O(nlogn)`, where n is the length of the strs array and m is the average length of the strings. 40 | 41 | - Space complexity: O(n∗m) 42 | 43 | The space complexity of the given code is `O(n∗m)`, where n is the length of the strs array and m is the average length of the strings. 44 | 45 | In the code, a groupAnagram object is used to store the groups of anagrams. The space required by this object depends on the number of distinct anagram groups. In the worst case scenario, where there are no anagrams and all strings are distinct, each string will be considered as a separate group, resulting in n distinct groups. Therefore, the space required by the groupAnagram object is proportional to the number of strings, which is `O(n)`. 46 | 47 | Additionally, the result array is created to store the grouped anagrams. The number of elements in this array is equal to the number of anagram groups, which can be at most n in the worst case scenario. Hence, the space required by the result array is also `O(n)`. 48 | 49 | Overall, the space complexity is `O(n∗m)` due to the groupAnagram object and the result array. 50 | ## Code 51 | 52 | ``` Javascript 53 | var groupAnagrams = function(strs) { 54 | let groupAnagram = {}; 55 | 56 | for (let str of strs) { 57 | let sortedStr = str.split('').sort().join(''); 58 | 59 | if (groupAnagram[sortedStr]) groupAnagram[sortedStr].push(str); 60 | 61 | else groupAnagram[sortedStr] = [str]; 62 | } 63 | 64 | let result = Object.values(groupAnagram); 65 | 66 | result.sort((a, b) => a.length - b.length); 67 | 68 | return result; 69 | 70 | }; 71 | ``` 72 | -------------------------------------------------------------------------------- /Javascript/0049-group-anagram/q-group-anagram.md: -------------------------------------------------------------------------------- 1 | # [Group Anagrams](https://leetcode.com/problems/group-anagrams/) 2 | 3 | ## Problem 4 | 5 | Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
13 | **Output:** \[\["bat"\], \["nat", "tan"\], \["ate", "eat", "tea"\]\]
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** strs = \[""\]
19 | **Output:** \[\[""\]\]
20 | 21 | **Example 3:** 22 | 23 | 24 | >**Input:** strs = \["a"\]
25 | **Output:** \[\["a"\]\]
26 | 27 | **Constraints:** 28 | 29 | - $1 <= strs.length <= 10^4$ 30 | - $0 <= strs[i].length <= 100$ 31 | - $strs[i]$ consists of lowercase English letters. 32 | 33 | ## Solutions 34 | 35 | 36 | | ID | METHOD | LINK | 37 | | :-- | :-----: | :----------------------- | 38 | | 1 | Object | [link](group-anagram.md) | 39 | -------------------------------------------------------------------------------- /Javascript/0217-contains-duplicate/contains-duplicate.md: -------------------------------------------------------------------------------- 1 | # [Basic JavaScript Solution of "Contains Duplicate"](https://leetcode.com/problems/contains-duplicate/solutions/3580102/basic-javascript-solution-of-contains-duplicate/) 2 | 3 | 4 | ## Approach 5 | The code snippet you provided uses a sorting-based approach to check for duplicates in the given array. It does not utilize a hash map or brute force method. 6 | 7 | Here's an explanation of the approach used in the code: 8 | 9 | 1. The code starts by sorting the array `nums` using the `sort()` method. Sorting the array allows duplicate elements to be adjacent to each other. 10 | 2. Then, the code iterates through the sorted array from index 0 to `nums.length - 1` (excluding the last element). 11 | 3. Within the loop, it compares the current element `nums[i]` with the next element `nums[i + 1]`. 12 | 4. If the current element is equal to the next element, it means there is a duplicate present. In this case, the code returns `true` to indicate the presence of duplicates. 13 | 5. If no duplicates are found after iterating through the entire array, the code returns `false` to indicate that there are no duplicates. 14 | 15 | In summary, the provided code uses a sorting-based approach to check for duplicates. It sorts the array and then compares adjacent elements to identify duplicates. It does not use a hash map or brute force method to solve the problem. 16 | ## Complexity 17 | 18 | - Time complexity: O(n log n) 19 | - Space complexity: O(1) 20 | ## Code 21 | 22 | ``` Javascript 23 | var containsDuplicate = function(nums) { 24 | nums.sort(); 25 | for (let i = 0; i < nums.length - 1; i++) { 26 | if (nums[i] === nums[i + 1]) { 27 | return true; 28 | } 29 | } 30 | return false; 31 | }; 32 | ``` 33 | -------------------------------------------------------------------------------- /Javascript/0217-contains-duplicate/q-contains-duplicate.md: -------------------------------------------------------------------------------- 1 | # [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) 2 | 3 | ## Problem 4 | 5 | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:** nums = \[1,2,3,1\]
11 | **Output:** true
12 | 13 | **Constraints:** 14 | 15 | - $1 <= nums.length <= 10^5$ 16 | - $-10^9 <= nums[i] <= 10^9$ 17 | 18 | ## Solutions 19 | 20 | 21 | | ID | METHOD | LINK | 22 | | :-- | :-----: | :--- | 23 | | 1 |Sorting Base Approach |[contains-duplicate.md](contains-duplicate.md) | 24 | -------------------------------------------------------------------------------- /Javascript/0242-valid-anagram/q-valid-anagram.md: -------------------------------------------------------------------------------- 1 | # [Valid Anagram](https://leetcode.com/problems/valid-anagram/) 2 | 3 | ## Problem 4 | 5 | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** s = "anagram", t = "nagaram"
13 | **Output:** true
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** s = "rat", t = "car"
19 | **Output:** false
20 | 21 | **Constraints:** 22 | 23 | - $1 <= s.length, t.length <= 5 * 10^4$ 24 | - `s` and `t` consist of lowercase English letters. 25 | 26 | **Follow-up:** 27 | 28 | What if the inputs contain Unicode characters? How would you adapt your solution to such a case? 29 | 30 | ## Solutions 31 | 32 | 33 | | ID | METHOD | LINK | 34 | | :-- | :--------------------: | :----------------------------------- | 35 | | 1 | Split and Sort | [valid-anagram.md](valid-anagram.md) | 36 | -------------------------------------------------------------------------------- /Javascript/0242-valid-anagram/valid-anagram.md: -------------------------------------------------------------------------------- 1 | # [👨‍🏫Simple "Valid Anagram" Solution in Javascript 👌](https://leetcode.com/problems/valid-anagram/solutions/3583388/simple-valid-anagram-solution-in-javascript/) 2 | 3 | ## Approach 4 | 5 | This code snippet contains a function that checks if two given strings are anagrams of each other. Here's how it works: 6 | 7 | 1-First, if the lengths of the two strings are different, meaning they are not of the same length, the function returns `false`. 8 | 9 | 2-Then, both strings are converted into arrays of characters using the `split('')` method, and each array is sorted alphabetically using the `sort()` method. This gives us the sorted versions of both strings. 10 | 11 | 3-Next, a loop is initiated for each element in the ``sorted_T`` array, and each element is compared with the corresponding element in the `sorted_S` array. 12 | 13 | 4-If any element doesn't match during the comparison (meaning the characters at the respective indexes in the sorted arrays are different), the function returns `false`. 14 | 15 | 5-If all elements match until the end of the loop (meaning both strings have the same characters), the function returns `true`. 16 | 17 | ## Complexity 18 | 19 | - Time complexity:O(n log n) 20 | 21 | 22 | 23 | - Space complexity:O(1) 24 | 25 | 26 | 27 | ## Code 28 | 29 | ``` javascript 30 | var isAnagram = function(s, t) { 31 | 32 | if (s.length !== t.length) return false; 33 | 34 | const sorted_S = s.split('').sort(); 35 | const sorted_T = t.split('').sort(); 36 | 37 | for (let i = 0; i < sorted_T.length; i++) { 38 | 39 | if (sorted_S[i] !== sorted_T[i]) return false; 40 | 41 | } 42 | 43 | return true; 44 | 45 | 46 | }; 47 | ``` -------------------------------------------------------------------------------- /Javascript/README.md: -------------------------------------------------------------------------------- 1 | # Awesome Leetcode Algorithms Solututions With JavaScript 2 | 3 | | ID | Question Name | 4 | | :--- | :-------------------------------------: | 5 | | 0001 | [Two Sum](0001-two-sum/q-two-sum.md) | 6 | | 0217 | [Duplicate Array](0217-contains-duplicate/q-contains-duplicate.md) | 7 | | 0242 | [Valid Anagram](0242-valid-anagram/q-valid-anagram.md) | 8 | | 0049 | [Group Anagram](0049-group-anagram/q-group-anagram.md) | 9 | 10 |
11 |

Awesome Leetcode Algorithms Solututions With JavaScript

12 | 13 | 14 | 15 | 16 | Twitter Follow 17 | 18 | 19 | Author: 20 | Kaan Çavdar
21 | February, 2023 22 |
23 |
24 | 25 | ## Introduction 26 | 27 | Welcome to the solutions of leetcode algorithms with JavaScript. 28 | 29 | ## How to Use It? 30 | 31 | I suggest cloning the repository locally to work with it, but you can easily look at any solution you want without cloning it. Simply press `Ctrl + F` and type the name of the question or its ID. Each folder includes an .md file that you can click on to go to the Leetcode website. There are two parts of questions: 32 | 33 | 1. Problem:
This part includes the definition of the problem, example cases, input and output examples, constraints, and follow-up information. 34 | 2. Solution:
This part includes a table to navigate to the solutions. 35 | 36 | ## Solutions 37 | 38 | Each .md file for a solution includes: 39 | 40 | - Header (that navigates to the online explanation of the solution) 41 | - Approach (describing the approach to solving the problem) 42 | - Complexity (determining the time and space complexity of the solution) 43 | - Code (the actual solution to the problem) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Çukurova Blockchain 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 | -------------------------------------------------------------------------------- /Python/0000-template/1-answer.md: -------------------------------------------------------------------------------- 1 | # [Header](link) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | Explain the approach 6 | 7 | ## 🔐 Code 8 | 9 | ``` Programming language 10 | printf("Hello World"); 11 | ``` 12 | 13 | ## 🧩 Complexity 14 | 15 | - Time complexity: 16 | 17 | Time Complexity 18 | 19 | - Space complexity: 20 | 21 | Space Complexity 22 | -------------------------------------------------------------------------------- /Python/0000-template/question.md: -------------------------------------------------------------------------------- 1 | # [Header](Link) 2 | 3 | ## 🚨 Problem 4 | 5 | Explain the problem 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:**
11 | **Output:**
12 | **Explanation:** 13 | 14 | **Constraints:** 15 | 16 | - example 17 | 18 | **Follow-up:** 19 | 20 | 21 | ## 🔐 Solutions 22 | 23 | 24 | | ID | METHOD | 25 | | :-- | :--------------------: | 26 | | 1 | [example](1-answer.md) | 27 | -------------------------------------------------------------------------------- /Python/0001-two-sum/1-answer.md: -------------------------------------------------------------------------------- 1 | # [Brute Force to solve the Two-Sum Problem on Python language](https://leetcode.com/problems/two-sum/solutions/3576423/brute-force-to-solve-the-two-sum-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The brute-force approach to solving the two-sum problem involves checking every possible pair of elements in the array and comparing their sum to the target. This can be achieved by using two nested loops, where each loop iterates through all the elements in the array. In each iteration, the current pair of elements is checked to see if their sum is equal to the target. If a match is found, the indices of the elements are stored and returned as the solution. The idea is to go through all the possible combinations of elements and check if any of them add up to the target. It's a straightforward approach that doesn't require any complex algorithms or data structures, making it easy to understand and implement. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def twoSum(self, nums: List[int], target: int) -> List[int]: 12 | for i in range(len(nums)): 13 | for j in range(i+1, len(nums)): 14 | if nums[i] + nums[j] == target: 15 | return [i,j] 16 | ``` 17 | 18 | ## 🧩 Complexity 19 | 20 | - Time complexity: 21 | 22 | The time complexity of the brute-force approach for solving the two-sum problem is $O(n^2)$, where n is the size of the input array. This means that the algorithm's performance will be proportional to the square of the size of the array. 23 | 24 | In each iteration of the outer loop, the inner loop will also iterate through all the elements in the array. So, the number of operations performed by the algorithm is proportional to the product of the number of iterations of the outer loop and the inner loop. The outer loop iterates n times, and the inner loop iterates $n-1$ times on the first iteration, $n-2$ times on the second iteration, and so on. So, the total number of iterations is $n * (n-1) / 2$, which is equivalent to $n^2/2 - n/2$. This results in a time complexity of $O(n^2)$. 25 | 26 | This means that as the size of the array grows, the number of operations performed by the algorithm will increase rapidly, making it inefficient for large arrays. 27 | 28 | - Space complexity: 29 | 30 | The space complexity of the brute-force approach for solving the two-sum problem is $O(1)$. This means that the amount of memory used by the algorithm is constant and does not depend on the size of the input array. 31 | 32 | In this approach, we use two integer variables, `i` and `j`, to store the indices of the elements in the array. These variables are used as pointers to access the elements in the array and do not increase in size as the size of the array grows. 33 | 34 | We also use a constant amount of memory to store the answer, which is an array of two integers. This array is dynamically allocated using malloc, and its size does not depend on the size of the input array. 35 | 36 | Therefore, the space complexity of the algorithm is $O(1)$, which means that it uses a constant amount of memory, regardless of the size of the input array. 37 | -------------------------------------------------------------------------------- /Python/0001-two-sum/2-answer.md: -------------------------------------------------------------------------------- 1 | # [Hash Table to solve the Two-Sum Problem on Python language](https://leetcode.com/problems/two-sum/solutions/3577066/hash-table-to-solve-the-two-sum-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The approach to solve the two-sum problem in Python involves using a dictionary (hash map) to store the previously encountered numbers and their indices. 6 | 7 | We iterate through the given list of numbers using the `enumerate()` function to access both the index and the value of each number. For every number, we calculate the difference between the target and the current number. 8 | 9 | If the difference is already present in the dictionary, it means we have found a pair of numbers whose sum is equal to the target. We can retrieve the index of the previously encountered number from the dictionary and return it along with the current index. 10 | 11 | If the difference is not in the dictionary, we add the current number and its index to the dictionary. This way, if a subsequent number complements the current number to reach the target, we can easily retrieve the indices of the two numbers. 12 | 13 | ## 🔐 Code 14 | 15 | ``` python 16 | class Solution: 17 | def twoSum(self, nums: List[int], target: int) -> List[int]: 18 | prevMap = {} # key -> value 19 | 20 | for i, n in enumerate(nums): 21 | diff = target - n 22 | if diff in prevMap: 23 | return [prevMap[diff], i] 24 | prevMap[n] = i 25 | ``` 26 | 27 | ## 🧩 Complexity 28 | 29 | - Time Complexity: 30 | 31 | The time complexity of this approach is O(n), where n is the size of the input list. We iterate through the list once, performing constant time operations for each element. 32 | 33 | - Space Complexity: 34 | 35 | The space complexity is also O(n) because, in the worst case, we might need to store all the numbers in the dictionary. 36 | -------------------------------------------------------------------------------- /Python/0001-two-sum/question.md: -------------------------------------------------------------------------------- 1 | # [1. Two Sum](https://leetcode.com/problems/two-sum) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. 6 | 7 | You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. 8 | 9 | You can return the answer in any order. 10 | 11 | **Example 1:** 12 | 13 | >**Input:** nums = \[2,7,11,15\], target = 9
14 | **Output:** \[0,1\]
15 | **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. 16 | 17 | **Example 2:** 18 | 19 | >**Input:** nums = \[3,2,4\], target = 6
20 | **Output:** \[1,2\] 21 | 22 | **Example 3:** 23 | 24 | >**Input:** nums = \[3,3\], target = 6
25 | **Output:** \[0,1\] 26 | 27 | **Constraints:** 28 | 29 | - $2 <= nums.length <= 10^4$ 30 | - $-10^9 <= nums[i] <= 10^9$ 31 | - $-10^9 <= target <= 10^9$ 32 | - **Only one valid answer exists.** 33 | 34 | **Follow-up:** Can you come up with an algorithm that is less than $O(n^2)$ time complexity? 35 | 36 | ## 🔐 Solutions 37 | 38 | | ID | METHOD | 39 | | :-- | :------------------------: | 40 | | 1 | [Brute Force](1-answer.md) | 41 | | 2 | [Hash Table](2-answer.md) | 42 | -------------------------------------------------------------------------------- /Python/0020-valid-parentheses/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Stack and Map to solve the 🧑🏻‍💻 Valid Parentheses on 🐍 Python language](https://leetcode.com/problems/valid-parentheses/solutions/3598423/stack-and-map-to-solve-the-valid-parentheses-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The approach used in this code is to iterate through the input string character by character. When an opening symbol is encountered, it is pushed onto the stack. When a closing symbol is encountered, it is checked against the top element of the stack. If they match, the opening symbol is popped from the stack. If they don't match or the stack is empty, it means the string is invalid. At the end, if the stack is empty, it means all symbols were properly matched, so the string is valid; otherwise, it is invalid. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def isValid(self, s: str) -> bool: 12 | #map close symbols to opening symbols 13 | # ) -> ( 14 | # ] -> [ 15 | # } -> { 16 | hashMap = {")": "(", "]": "[", "}": "{"} 17 | stack = [] 18 | 19 | for c in s: #iterate over string 20 | if c not in hashMap: # if it is opening symbol 21 | stack.append(c) # add to stack 22 | continue 23 | # if it is closing symbol and 24 | # it stack is empty or 25 | # not correct closing symbol return false 26 | # stack[-1] -> gives top element on stack 27 | if not stack or stack[-1] != hashMap[c]: 28 | return False 29 | stack.pop() # otherwise pop from stack 30 | 31 | # if stack is empty return true else return false 32 | return not stack 33 | ``` 34 | 35 | ## 🧩 Complexity 36 | 37 | - Time complexity: 38 | 39 | The time complexity of this code is $O(n)$, where n is the length of the input string. This is because the code iterates through each character in the string once. 40 | 41 | - Space complexity: 42 | 43 | The space complexity of this code is $O(n)$, where n is the length of the input string. In the worst case, if all the characters in the string are opening symbols, they will be stored in the stack. Therefore, the space required for the stack will be proportional to the length of the string. 44 | -------------------------------------------------------------------------------- /Python/0020-valid-parentheses/question.md: -------------------------------------------------------------------------------- 1 | # [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. 6 | 7 | An input string is valid if: 8 | 9 | 1. Open brackets must be closed by the same type of brackets. 10 | 2. Open brackets must be closed in the correct order. 11 | 3. Every close bracket has a corresponding open bracket of the same type. 12 | 13 | **Example 1:** 14 | 15 | 16 | >**Input:** s = "()"
17 | **Output:** true
18 | 19 | **Example 2:** 20 | 21 | 22 | >**Input:** s = "()\[\]{}"
23 | **Output:** true
24 | 25 | **Example 3:** 26 | 27 | 28 | >**Input:** s = "(\]"
29 | **Output:** false
30 | 31 | **Constraints:** 32 | 33 | - $1 <= s.length <= 10^4$ 34 | - `s` consists of parentheses only `'()[]{}'`. 35 | 36 | ## 🔐 Solutions 37 | 38 | 39 | | ID | METHOD | 40 | | :-- | :--------------------: | 41 | | 1 | [Stack and Map](1-answer.md) | 42 | -------------------------------------------------------------------------------- /Python/0021-merge-two-sorted-lists/1-answer.md: -------------------------------------------------------------------------------- 1 | # [Header](link) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | Explain the approach 6 | 7 | ## 🔐 Code 8 | 9 | ``` Programming language 10 | printf("Hello World"); 11 | ``` 12 | 13 | ## 🧩 Complexity 14 | 15 | - Time complexity: 16 | 17 | Time Complexity 18 | 19 | - Space complexity: 20 | 21 | Space Complexity 22 | -------------------------------------------------------------------------------- /Python/0021-merge-two-sorted-lists/img/merge_ex1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cukurovablock/awesome-leetcode-algorithms-solutions/5bc0ac7aad4074968d39cee125ab49707f6e6d4b/Python/0021-merge-two-sorted-lists/img/merge_ex1.jpg -------------------------------------------------------------------------------- /Python/0021-merge-two-sorted-lists/question.md: -------------------------------------------------------------------------------- 1 | # [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) 2 | 3 | ## 🚨 Problem 4 | 5 | You are given the heads of two sorted linked lists `list1` and `list2`. 6 | 7 | Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. 8 | 9 | Return _the head of the merged linked list_. 10 | 11 | **Example 1:** 12 | 13 | ![example 1](./img/merge_ex1.jpg) 14 | 15 | >**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
16 | **Output:** \[1,1,2,3,4,4\]
17 | 18 | **Example 2:** 19 | 20 | 21 | >**Input:** list1 = \[\], list2 = \[\]
22 | **Output:** \[\]
23 | 24 | **Example 3:** 25 | 26 | 27 | >**Input:** list1 = \[\], list2 = \[0\]
28 | **Output:** \[0\]
29 | 30 | **Constraints:** 31 | 32 | - The number of nodes in both lists is in the range `[0, 50]`. 33 | - `-100 <= Node.val <= 100` 34 | - Both `list1` and `list2` are sorted in **non-decreasing** order. 35 | 36 | ## 🔐 Solutions 37 | 38 | 39 | | ID | METHOD | 40 | | :-- | :--------------------: | 41 | | 1 | [example](1-answer.md) | 42 | -------------------------------------------------------------------------------- /Python/0049-group-anagram/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Counts the Frequencies to solve the 🧑🏻‍💻 Group Anagram Problem on 🐍 Python language](https://leetcode.com/problems/group-anagrams/solutions/3587269/counts-the-frequencies-to-solve-the-group-anagram-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | the approach counts the occurrences of each letter in the words and groups the anagrams together based on their letter counts using a dictionary. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 12 | ans = collections.defaultdict(list) 13 | # default list dictionary if it is empty it returns empty list 14 | 15 | for s in strs: # iterate of words 16 | count = [0] * 26 # 26 zero list for alpahabet 17 | for c in s: # iterate of letters 18 | count[ord(c) - ord("a")] += 1 # ord(c) gives ascii value 19 | ans[tuple(count)].append(s) # add to word to list that related with key ()whic is count list) 20 | 21 | """ 22 | { 23 | (1,2,...,1,...): [ 24 | "bat" 25 | ], 26 | (1,...,1,...,1,...): [ 27 | "nat", 28 | "tan" 29 | ], 30 | (1,...,1....,1,...): [ 31 | "ate", 32 | "eat", 33 | "tea" 34 | ], 35 | } 36 | """ 37 | 38 | return ans.values() 39 | ``` 40 | 41 | ## 🧩 Complexity 42 | 43 | - Time complexity: 44 | 45 | The time complexity of the solution is $O(n \* k)$, where n is the number of words in the input list `strs` and k is the maximum length of the words. In the worst case, where all words have the same maximum length, the time complexity simplifies to $O(n \* m)$, where m is the maximum length of the words. The constant-time operations performed inside the loops do not significantly impact the overall time complexity. Thus, the solution has a linear time complexity with respect to the size of the input list and the maximum length of the words. 46 | 47 | - Space complexity: 48 | 49 | The space complexity of the solution is $O(n)$, where n is the number of words in the input list `strs`. The `ans` dictionary, which stores the groups of anagrams, is the main factor contributing to the space complexity. The additional space used for the `count` list and other variables is constant and does not significantly affect the overall space requirement. Hence, the space complexity is linear with respect to the size of the input list. 50 | -------------------------------------------------------------------------------- /Python/0049-group-anagram/question.md: -------------------------------------------------------------------------------- 1 | # [Group Anagrams](https://leetcode.com/problems/group-anagrams/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
13 | **Output:** \[\["bat"\], \["nat", "tan"\], \["ate", "eat", "tea"\]\]
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** strs = \[""\]
19 | **Output:** \[\[""\]\]
20 | 21 | **Example 3:** 22 | 23 | 24 | >**Input:** strs = \["a"\]
25 | **Output:** \[\["a"\]\]
26 | 27 | **Constraints:** 28 | 29 | - $1 <= strs.length <= 10^4$ 30 | - $0 <= strs[i].length <= 100$ 31 | - $strs[i]$ consists of lowercase English letters. 32 | 33 | ## 🔐 Solutions 34 | 35 | 36 | | ID | METHOD | 37 | | :-- | :-----------------------------------: | 38 | | 1 | [Counts the Frequencies](1-answer.md) | 39 | -------------------------------------------------------------------------------- /Python/0121-best-time-to-buy-and-sell-stock/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Two Pointer to solve the 🧑🏻‍💻 Best Time to Buy and Sell Stock Problem on 🐍 Python language](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/3681310/two-pointer-to-solve-the-best-time-to-buy-and-sell-stock-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | This problem is a classic example of the Two Pointer Technique where two pointers are maintained to find the maximum difference (maximum profit in this case). The pointers are `left` and `right`, where `left` is initially at the start of the array, and `right` is the second element. We move the right pointer to the end of the array and for each move, we check if the current profit (`prices[right] - prices[left]`) is greater than the current maxProfit. If it is, we update maxProfit. If `prices[right]` is less than `prices[left]`, it means that we could buy at a lower price at `right`, so we update `left` to `right`. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def maxProfit(self, prices: List[int]) -> int: 12 | left, right = 0, 1 13 | maxProfit = 0 14 | 15 | while right < len(prices): 16 | if prices[left] < prices[right]: 17 | profit = prices[right] - prices[left] 18 | maxProfit = max(maxProfit, profit) 19 | else: 20 | left = right 21 | right += 1 22 | 23 | return maxProfit 24 | ``` 25 | 26 | ## 🧩 Complexity 27 | 28 | - Time complexity: 29 | The time complexity of this approach is $O(n)$ where n is the length of the prices array. This is because we are running a loop to traverse through the prices array once. 30 | 31 | - Space complexity: 32 | The space complexity is $O(1)$ as we are only using a constant amount of space to store our variables (left, right, maxProfit, and profit). 33 | -------------------------------------------------------------------------------- /Python/0121-best-time-to-buy-and-sell-stock/2-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Sliding Window to solve the 🧑🏻‍💻 Best Time to Buy and Sell Stock Problem on 🐍 Python language](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/3681349/sliding-window-to-solve-the-best-time-to-buy-and-sell-stock-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | In this problem, we can use a sliding window approach where we iterate over the prices array once, keeping track of the lowest price we've seen so far, and calculate the profit for each price. The approach is to first initialize the lowest price as the first price in the array. Then for each subsequent price, we compare it with the current lowest price. If it's less, we update the lowest price. If it's more, we calculate the profit (current price - lowest price) and compare it with the current maximum profit. If the calculated profit is more, we update the maximum profit. The maximum profit at the end of the iteration is the answer. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def maxProfit(self, prices: List[int]) -> int: 12 | result = 0 13 | 14 | lowest = prices[0] 15 | for price in prices: 16 | if price < lowest: 17 | lowest = price 18 | result = max(result, price - lowest) 19 | return result 20 | ``` 21 | 22 | ## 🧩 Complexity 23 | 24 | - Time complexity: 25 | The time complexity of this approach is $O(n)$ where n is the length of the prices array. This is because we are running a loop to traverse through the prices array once. 26 | 27 | - Space complexity: 28 | The space complexity is $O(1)$ as we are only using a constant amount of space to store our variables (result, lowest, and price). -------------------------------------------------------------------------------- /Python/0121-best-time-to-buy-and-sell-stock/question.md: -------------------------------------------------------------------------------- 1 | # [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) 2 | 3 | ## 🚨 Problem 4 | 5 | You are given an array `prices` where `prices[i]` is the price of a given stock on the $i^{th}$ day. 6 | 7 | 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. 8 | 9 | Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. 10 | 11 | **Example 1:** 12 | 13 | 14 | >**Input:** prices = \[7,1,5,3,6,4\]
15 | **Output:** 5
16 | **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 17 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 18 | 19 | **Example 2:** 20 | 21 | 22 | >**Input:** prices = \[7,6,4,3,1\]
23 | **Output:** 0
24 | **Explanation:** In this case, no transactions are done and the max profit = 0. 25 | 26 | **Constraints:** 27 | 28 | - $1 <= prices.length <= 10^5$ 29 | - $0 <= prices[i] <= 10^4$ 30 | 31 | ## 🔐 Solutions 32 | 33 | 34 | | ID | METHOD | 35 | | :-- | :---------------------------: | 36 | | 1 | [Two Pointer](1-answer.md) | 37 | | 2 | [Sliding Window](2-answer.md) | 38 | -------------------------------------------------------------------------------- /Python/0125-valid-palindrome/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Lowercase Alphanumeric to solve the 🧑🏻‍💻 Valid Palindrome Problem on 🐍 Python language](https://leetcode.com/problems/valid-palindrome/solutions/3602273/lowercase-alphanumeric-to-solve-the-valid-palindrome-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The code determines if a given string is a palindrome by first extracting only the alphanumeric characters and converting them to lowercase. It then compares the characters at corresponding positions from the start and end of the string. If any pair of characters doesn't match, the string is not a palindrome. Otherwise, if all pairs match, the string is a palindrome. The code assumes ASCII characters in the input string. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def isPalindrome(self, s: str) -> bool: 12 | alphanumeric = "" 13 | for c in s: 14 | if self.isAlphanum(c): # or you can use c.isalnum(): 15 | alphanumeric += c.lower() 16 | 17 | length = len(alphanumeric) 18 | 19 | # we need to check half of string 20 | for i in range(length // 2): # // is floor division operator 10 // 3 = 3 21 | if alphanumeric[i] != alphanumeric[length - i - 1]: 22 | return False 23 | 24 | return True 25 | 26 | def isAlphanum(self, c): 27 | return ( 28 | ord("A") <= ord(c) <= ord("Z") 29 | or ord("a") <= ord(c) <= ord("z") 30 | or ord("0") <= ord(c) <= ord("9") 31 | ) 32 | ``` 33 | 34 | ## 🧩 Complexity 35 | 36 | - Time complexity: 37 | 38 | The time complexity of the code is $O(n)$, where n is the length of the input string. The code iterates through each character of the string once to extract the alphanumeric characters, and then performs a comparison for the first half of the alphanumeric string. Since the number of iterations is directly proportional to the length of the input string, the time complexity is linear. 39 | 40 | - Space complexity: 41 | 42 | The space complexity of the code is also $O(n)$, where n is the length of the input string. This is because the code creates a new string `alphanumeric` to store the alphanumeric characters from the input string. The length of the `alphanumeric` string can be at most equal to the length of the input string, so the space complexity is linear. 43 | -------------------------------------------------------------------------------- /Python/0125-valid-palindrome/question.md: -------------------------------------------------------------------------------- 1 | # [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) 2 | 3 | ## 🚨 Problem 4 | 5 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. 6 | 7 | Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** s = "A man, a plan, a canal: Panama"
13 | **Output:** true
14 | **Explanation:** "amanaplanacanalpanama" is a palindrome. 15 | 16 | **Example 2:** 17 | 18 | 19 | >**Input:** s = "race a car"
20 | **Output:** false
21 | **Explanation:** "raceacar" is not a palindrome. 22 | 23 | **Example 3:** 24 | 25 | 26 | >**Input:** s = " "
27 | **Output:** true
28 | **Explanation:** s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. 29 | 30 | **Constraints:** 31 | 32 | - $1 <= s.length <= 2 * 10^5$ 33 | - `s` consists only of printable ASCII characters. 34 | 35 | **Follow-up:** 36 | 37 | 38 | ## 🔐 Solutions 39 | 40 | 41 | | ID | METHOD | 42 | | :-- | :-----------------------------------: | 43 | | 1 | [Lowercase Alphanumeric](1-answer.md) | 44 | -------------------------------------------------------------------------------- /Python/0155-min-stack/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Double Stack to solve the 🧑🏻‍💻 Min Stack Problem on 🐍 Python language](https://leetcode.com/problems/min-stack/solutions/3606186/double-stack-to-solve-the-min-stack-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The `MinStack` class is designed to maintain a stack of values while efficiently retrieving the minimum value at any time. It achieves this by using an additional stack, `minStack`, which keeps track of the minimum value encountered so far. Whenever a new value is pushed onto the stack, the minimum value between the new value and the current minimum is stored in `minStack`. This approach allows constant time retrieval of the minimum value by accessing the top of `minStack`. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class MinStack: 11 | 12 | def __init__(self): 13 | self.stack = [] 14 | self.minStack = [] 15 | 16 | def push(self, val: int) -> None: 17 | self.stack.append(val) 18 | #if minStack is non empty compare it with val and take min 19 | # otherwise take val (or val) (which means they are same) 20 | val = min(val, self.minStack[-1] if self.minStack else val) 21 | self.minStack.append(val) 22 | 23 | def pop(self) -> None: 24 | self.stack.pop() 25 | self.minStack.pop() 26 | 27 | def top(self) -> int: 28 | return self.stack[-1] 29 | 30 | def getMin(self) -> int: 31 | return self.minStack[-1] 32 | 33 | 34 | # Your MinStack object will be instantiated and called as such: 35 | # obj = MinStack() 36 | # obj.push(val) 37 | # obj.pop() 38 | # param_3 = obj.top() 39 | # param_4 = obj.getMin() 40 | ``` 41 | 42 | ## 🧩 Complexity 43 | 44 | - Time complexity: 45 | 46 | The time complexity of the `push`, `pop`, `top`, and `getMin` operations in the `MinStack` class is O(1). These operations involve only basic stack operations such as appending, popping, and accessing the top element, which all have constant time complexity. 47 | 48 | - Space complexity: 49 | 50 | The space complexity of the `MinStack` class is O(n), where n is the number of elements stored in the stack. Both the `stack` and `minStack` lists grow linearly with the number of elements pushed onto the stack. Hence, the space required is proportional to the number of elements in the stack. 51 | -------------------------------------------------------------------------------- /Python/0155-min-stack/question.md: -------------------------------------------------------------------------------- 1 | # [Min Stack](https://leetcode.com/problems/min-stack/) 2 | 3 | ## 🚨 Problem 4 | 5 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 6 | 7 | Implement the `MinStack` class: 8 | 9 | - `MinStack()` initializes the stack object. 10 | - `void push(int val)` pushes the element `val` onto the stack. 11 | - `void pop()` removes the element on the top of the stack. 12 | - `int top()` gets the top element of the stack. 13 | - `int getMin()` retrieves the minimum element in the stack. 14 | 15 | You must implement a solution with `O(1)` time complexity for each function. 16 | 17 | **Example 1:** 18 | 19 | 20 | >**Input:** \["MinStack","push","push","push","getMin","pop","top","getMin"\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]

21 | **Output:** \[null,null,null,null,-3,null,0,-2\]

22 | **Explanation:** 23 | MinStack minStack = new MinStack();
24 | minStack.push(-2);
25 | minStack.push(0);
26 | minStack.push(-3);
27 | minStack.getMin(); // return -3
28 | minStack.pop();
29 | minStack.top(); // return 0
30 | minStack.getMin(); // return -2 31 | 32 | **Constraints:** 33 | 34 | - $-2^{31} <= val <= 2^{31} - 1$ 35 | - Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. 36 | - At most $3 * 10^4$ calls will be made to `push`, `pop`, `top`, and `getMin`. 37 | 38 | **Follow-up:** 39 | 40 | 41 | ## 🔐 Solutions 42 | 43 | 44 | | ID | METHOD | 45 | | :-- | :-------------------------: | 46 | | 1 | [Double Stack](1-answer.md) | 47 | -------------------------------------------------------------------------------- /Python/0167-two-sum-2/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Two Pointer to solve the 🧑🏻‍💻 Two Sum 2 Problem on 🐍 Python](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/solutions/3610884/two-pointer-to-solve-the-two-sum-2-problem-on-python/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The approach in the given code is to use a two-pointer technique to find a pair of numbers in a sorted array that add up to a target value. The pointers start from the beginning and end of the array and move towards each other based on whether the current sum is greater or smaller than the target. This approach takes advantage of the sorted nature of the array to efficiently narrow down the search space and find the desired pair in linear time. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 12 | left, right = 0, len(numbers) - 1 # Initialize the left and right pointers 13 | 14 | while right > left: # Continue until the pointers meet or cross 15 | if numbers[left] + numbers[right] > target: # Current pair is too large 16 | right -= 1 # Decrement right pointer 17 | elif numbers[left] + numbers[right] < target: # Current pair is too small 18 | left += 1 # Increment left pointer 19 | else: # Found the solution 20 | return [left + 1, right + 1] # Return indices (adjusted by adding 1) 21 | 22 | # If no solution is found, return an empty list or handle it as needed 23 | return [] 24 | ``` 25 | 26 | ## 🧩 Complexity 27 | 28 | - Time complexity: 29 | 30 | The time complexity of the given code is $O(n)$, where n is the number of elements in the input array. Since the code uses a two-pointer approach and iterates through the array only once, the time complexity is linear. 31 | 32 | - Space complexity: 33 | 34 | The space complexity of the code is $O(1)$ because it uses a constant amount of additional space. It does not allocate any new data structures that scale with the input size. The code only uses a fixed number of variables to store the pointers and the result, so the space complexity is constant. 35 | -------------------------------------------------------------------------------- /Python/0167-two-sum-2/question.md: -------------------------------------------------------------------------------- 1 | # [Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be $numbers[index_1]$ and $numbers[index_2]$ where $1 <= index_1 < index_2 < numbers.length$. 6 | 7 | Return _the indices of the two numbers,_ $index_1$ _and_ $index_2$_, **added by one** as an integer array_ $[index_1, index_2]$ _of length 2._ 8 | 9 | The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. 10 | 11 | Your solution must use only constant extra space. 12 | 13 | **Example 1:** 14 | 15 | 16 | >**Input:** numbers = \[2,7,11,15\], target = 9
17 | **Output:** \[1,2\]
18 | **Explanation:** The sum of 2 and 7 is 9. Therefore, $index_1$ = 1, $index_2$ = 2. We return \[1, 2\]. 19 | 20 | **Example 2:** 21 | 22 | 23 | >**Input:** numbers = \[2,3,4\], target = 6
24 | **Output:** \[1,3\]
25 | **Explanation:** The sum of 2 and 4 is 6. Therefore $index_1$ = 1, $index_2$ = 3. We return \[1, 3\]. 26 | 27 | **Example 3:** 28 | 29 | 30 | >**Input:** numbers = \[\-1,0\], target = -1
31 | **Output:** \[1,2\]
32 | **Explanation:** The sum of -1 and 0 is -1. Therefore $index_1$ = 1, $index_2$ = 2. We return \[1, 2\]. 33 | 34 | **Constraints:** 35 | 36 | - $2 <= numbers.length <= 3 * 10^4$ 37 | - $-1000 <= numbers[i] <= 1000$ 38 | - `numbers` is sorted in **non-decreasing order**. 39 | - $-1000 <= target <= 1000$ 40 | - The tests are generated such that there is **exactly one solution**. 41 | 42 | **Follow-up:** 43 | 44 | 45 | ## 🔐 Solutions 46 | 47 | 48 | | ID | METHOD | 49 | | :-- | :--------------------: | 50 | | 1 | [Two Pointer](1-answer.md) | 51 | -------------------------------------------------------------------------------- /Python/0206-reverse-linked-list/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Iteratively solving the 🧑🏻‍💻 Reverse Linked List Problem on 🐍 Python language](https://leetcode.com/problems/reverse-linked-list/solutions/3681527/iteratively-solving-the-reverse-linked-list-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The problem is to reverse a linked list. We will use an iterative method for this. We start by initializing two pointers: one (`prev`) that points to None (as the last node in a reversed list should point to None) and another (`curr`) that points to the head node. The idea is to traverse the list and for each node, save its next node, update its next pointer to the node before it (which is `prev`), and then move `prev` and `curr` one step forward. In the end, `prev` will point to the new head, which is the last node in the original list. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, val=0, next=None): 13 | # self.val = val 14 | # self.next = next 15 | class Solution: 16 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 17 | prev, curr = None, head 18 | 19 | while curr: 20 | nxt = curr.next 21 | curr.next = prev 22 | prev = curr 23 | curr = nxt 24 | 25 | return prev 26 | ``` 27 | 28 | ## 🧩 Complexity 29 | 30 | - Time complexity: 31 | The time complexity of this approach is $O(n)$ where n is the length of the linked list. This is because we are running a loop to traverse through the list once. 32 | 33 | - Space complexity: 34 | The space complexity is $O(1)$ as we are only using a constant amount of space to store our variables (prev, curr, and nxt), regardless of the size of the input linked list. 35 | -------------------------------------------------------------------------------- /Python/0206-reverse-linked-list/2-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Recursively solving the 🧑🏻‍💻 Reverse Linked List Problem on 🐍 Python language](https://leetcode.com/problems/reverse-linked-list/solutions/3681605/recursively-solving-the-reverse-linked-list-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The problem is to reverse a linked list. This time, we'll use a recursive method for this. We start by checking if the current node (initially the head) or its next node is None. If it is, we return the current node because it will be the new head of the reversed list. If not, we make a recursive call to the function with the next node. The idea here is that in each recursive call, we are getting the reversed list for the remaining nodes, and we just need to update the next pointer of the next node to point to the current node and update the next pointer of the current node to None. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, val=0, next=None): 13 | # self.val = val 14 | # self.next = next 15 | class Solution: 16 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 17 | 18 | if not head or not head.next: 19 | return head 20 | 21 | newHead = self.reverseList(head.next) 22 | head.next.next = head 23 | head.next = None 24 | 25 | return newHead 26 | ``` 27 | 28 | ## 🧩 Complexity 29 | 30 | - Time complexity: 31 | The time complexity of this approach is $O(n)$ where n is the length of the linked list. This is because each recursive call processes one node of the list, and there are n nodes in total. 32 | 33 | - Space complexity: 34 | The space complexity is $O(n)$, where n is the length of the linked list. This is because each recursive call is added to the call stack, and in the worst-case scenario, if the list has n nodes, there would be n recursive calls, thus n additions to the call stack. So the space complexity is proportional to the length of the list. 35 | -------------------------------------------------------------------------------- /Python/0206-reverse-linked-list/img/rev1ex1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cukurovablock/awesome-leetcode-algorithms-solutions/5bc0ac7aad4074968d39cee125ab49707f6e6d4b/Python/0206-reverse-linked-list/img/rev1ex1.jpg -------------------------------------------------------------------------------- /Python/0206-reverse-linked-list/img/rev1ex2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cukurovablock/awesome-leetcode-algorithms-solutions/5bc0ac7aad4074968d39cee125ab49707f6e6d4b/Python/0206-reverse-linked-list/img/rev1ex2.jpg -------------------------------------------------------------------------------- /Python/0206-reverse-linked-list/question.md: -------------------------------------------------------------------------------- 1 | # [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. 6 | 7 | **Example 1:** 8 | 9 | ![example 1](./img/rev1ex1.jpg) 10 | 11 | >**Input:** head = \[1,2,3,4,5\]
12 | **Output:** \[5,4,3,2,1\]
13 | 14 | **Example 2:** 15 | 16 | ![example 2](./img/rev1ex2.jpg) 17 | 18 | >**Input:** head = \[1,2\]
19 | **Output:** \[2,1\]
20 | 21 | **Example 3:** 22 | 23 | 24 | >**Input:** head = \[\]
25 | **Output:** \[\]
26 | 27 | **Constraints:** 28 | 29 | - The number of nodes in the list is the range `[0, 5000]`. 30 | - `-5000 <= Node.val <= 5000` 31 | 32 | **Follow-up:** 33 | 34 | A linked list can be reversed either iteratively or recursively. Could you implement both? 35 | 36 | ## 🔐 Solutions 37 | 38 | 39 | | ID | METHOD | 40 | | :-- | :----------------------: | 41 | | 1 | [Iterative](1-answer.md) | 42 | | 2 | [Recursive](2-answer.md) | 43 | -------------------------------------------------------------------------------- /Python/0217-contains-duplicate/1-answer.md: -------------------------------------------------------------------------------- 1 | # [Hash Set to solve the Contains Duplicate Problem on Python language](https://leetcode.com/problems/contains-duplicate/solutions/3579958/hash-set-to-solve-the-contains-duplicate-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | We use hash set to efficiently check for duplicates in the array. It iterates through the numbers, adding each number to the set if it hasn't been encountered before. If a duplicate is found during the iteration, the code returns `True`; otherwise, it returns `False`. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def containsDuplicate(self, nums: List[int]) -> bool: 12 | hashSet = set() 13 | 14 | for n in nums: 15 | 16 | if n in hashSet: 17 | return True 18 | hashSet.add(n) 19 | 20 | return False 21 | ``` 22 | 23 | ## 🧩 Complexity 24 | 25 | - Time complexity: 26 | 27 | The time complexity of the given code is $O(n)$, where n is the length of the input array `nums`. This is because the code iterates over each element in the array once, performing constant-time operations for each element. The `in` operator used to check if an element exists in the hash set, as well as the `add()` operation to insert an element into the hash set, both have an average time complexity of $O(1)$. 28 | 29 | - Space complexity: 30 | 31 | Space Complexity: 32 | The space complexity of the given code is $O(n)$ in the worst case. This occurs when all elements in the input array nums are unique and need to be stored in the hash set. In such a scenario, the hash set would contain n elements. However, if there are duplicate elements present in the array, the space usage of the hash set would be smaller as it only stores unique elements. 33 | -------------------------------------------------------------------------------- /Python/0217-contains-duplicate/question.md: -------------------------------------------------------------------------------- 1 | # [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:** nums = \[1,2,3,1\]
11 | **Output:** true
12 | 13 | **Constraints:** 14 | 15 | - $1 <= nums.length <= 10^5$ 16 | - $-10^9 <= nums[i] <= 10^9$ 17 | 18 | ## 🔐 Solutions 19 | 20 | 21 | | ID | METHOD | 22 | | :-- | :---------------------: | 23 | | 1 | [Hash Set](1-answer.md) | 24 | -------------------------------------------------------------------------------- /Python/0238-product-of-array-except-self/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Prefix and Postfix to solve the 🧑🏻‍💻 Product of Array Except Self Problem on 🐍 Python language](https://leetcode.com/problems/product-of-array-except-self/solutions/3598205/prefix-and-postfix-to-solve-the-product-of-array-except-self-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The approach used in the code is as follows: 6 | 7 | 1. Initialize a result list `res` with all elements set to 1. 8 | 2. Perform a forward pass through the input list `nums`: 9 | - Update each element in `res` with the product of all elements to the left of it. 10 | 3. Perform a backward pass through the input list `nums`: 11 | - Update each element in `res` by multiplying it with the product of all elements to the right of it. 12 | 4. Return the resulting list `res`, which contains the product of all elements in `nums` except the element at each index `i`. 13 | 14 | This approach leverages the concept of prefix and postfix products to calculate the desired result efficiently in a single pass in each direction. 15 | 16 | ## 🔐 Code 17 | 18 | ``` python 19 | class Solution: 20 | def productExceptSelf(self, nums: List[int]) -> List[int]: 21 | res = [1] * (len(nums)) #[1,1,1,1] 22 | 23 | prefix = 1 24 | # [1,2,3,4] 25 | for i in range(len(nums)): 26 | res[i] = prefix 27 | # [1,1,1,1] 28 | # [1,1,1,1] 29 | # [1,1,2,1] 30 | # [1,1,2,6] 31 | prefix *= nums[i] 32 | # 1 33 | # 2 34 | # 6 35 | # 24 36 | 37 | postfix = 1 38 | # [1,2,3,4] 39 | for i in range(len(nums) - 1, -1, -1): 40 | res[i] *= postfix 41 | # [1,1,2,6*1] 42 | # [1,1,2*4,6] 43 | # [1,12,8,6] 44 | # [24,12,8,6] 45 | postfix *= nums[i] 46 | # 4 47 | # 12 48 | # 24 49 | # 24 50 | 51 | return res 52 | # [24,12,8,6] 53 | ``` 54 | 55 | ## 🧩 Complexity 56 | 57 | - Time complexity: 58 | 59 | The time complexity of the given code is $O(N)$, where N is the length of the input list `nums`. This is because the code performs two passes through the input list, each taking O(N) time. Therefore, the overall time complexity is $O(N + N)$, which simplifies to $O(N)$. 60 | 61 | - Space complexity: 62 | 63 | The space complexity of the code is $O(N)$ as well. This is because it uses an additional list `res` of the same length as `nums` to store the results. Therefore, the space required is proportional to the length of the input list `nums`, resulting in a space complexity of $O(N)$. However because of the output array does not count as extra space for space complexity analysis we can say Space complexity is $O(1)$ 64 | -------------------------------------------------------------------------------- /Python/0238-product-of-array-except-self/question.md: -------------------------------------------------------------------------------- 1 | # [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. 6 | 7 | The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. 8 | 9 | You must write an algorithm that runs in `O(n)` time and without using the division operation. 10 | 11 | **Example 1:** 12 | 13 | 14 | >**Input:** nums = \[1,2,3,4\]
15 | **Output:** \[24,12,8,6\]
16 | 17 | **Example 2:** 18 | 19 | 20 | >**Input:** nums = \[-1,1,0,-3,3\]
21 | **Output:** \[0,0,9,0,0\]
22 | 23 | **Constraints:** 24 | 25 | - $2 <= nums.length <= 10^5$ 26 | - $-30 <= nums[i] <= 30$ 27 | - The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 28 | 29 | **Follow-up:** 30 | Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.) 31 | 32 | ## 🔐 Solutions 33 | 34 | 35 | | ID | METHOD | 36 | | :-- | :--------------------: | 37 | | 1 | [Prefix & Postfix](1-answer.md) | 38 | -------------------------------------------------------------------------------- /Python/0242-valid-anagram/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Counts the Frequencies to solve the 🧑🏻‍💻 Valid Anagram Problem on 😎 Python language](https://leetcode.com/problems/valid-anagram/solutions/3583443/counts-the-frequencies-to-solve-the-valid-anagram-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | In summary, the approach counts the frequencies of characters in both strings using dictionaries and checks if the character frequencies in s and t are the same. If the character frequencies match, the method returns `True`, indicating that t is an anagram of s. Otherwise, it returns `False`. 6 | 7 | ## 🔐 Code 8 | 9 | ``` python 10 | class Solution: 11 | def isAnagram(self, s: str, t: str) -> bool: 12 | if len(s) != len(t): 13 | return False 14 | 15 | countS, countT = {}, {} 16 | 17 | """ 18 | a => 3 19 | n => 2 20 | s => 1 21 | 22 | s => 1 23 | a => 3 24 | n => 2 25 | """ 26 | 27 | for i in range(len(s)): 28 | # get value with key and add 1 to old value 29 | countS[s[i]] = 1 + countS.get(s[i], 0) 30 | countT[t[i]] = 1 + countT.get(t[i], 0) 31 | return countS == countT 32 | ``` 33 | 34 | ## 🧩 Complexity 35 | 36 | - Time complexity: 37 | 38 | The time complexity of the solution is $O(n)$, where n is the length of the input strings `s` and `t`. The `for` loop iterates over the strings once, performing constant-time operations inside the loop. Since the loop iterates n times, the overall time complexity is linear with respect to the length of the strings. 39 | 40 | - Space complexity: 41 | 42 | The space complexity of the solution is $O(n)$, where n is the length of the input strings `s` and `t`. The dictionaries `countS` and `countT` store the frequency of each character in their respective strings. In the worst case, if all characters are unique, the dictionaries would contain n key-value pairs. Therefore, the space required by the dictionaries is proportional to the length of the strings, resulting in a space complexity of $O(n)$. 43 | -------------------------------------------------------------------------------- /Python/0242-valid-anagram/question.md: -------------------------------------------------------------------------------- 1 | # [Valid Anagram](https://leetcode.com/problems/valid-anagram/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** s = "anagram", t = "nagaram"
13 | **Output:** true
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** s = "rat", t = "car"
19 | **Output:** false
20 | 21 | **Constraints:** 22 | 23 | - $1 <= s.length, t.length <= 5 * 10^4$ 24 | - `s` and `t` consist of lowercase English letters. 25 | 26 | **Follow-up:** 27 | 28 | What if the inputs contain Unicode characters? How would you adapt your solution to such a case? 29 | 30 | ## 🔐 Solutions 31 | 32 | 33 | | ID | METHOD | 34 | | :-- | :-----------------------------------: | 35 | | 1 | [Counts the Frequencies](1-answer.md) | 36 | -------------------------------------------------------------------------------- /Python/0347-top-k-frequent-elements/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Counts and Sort to solve the 🧑🏻‍💻 Top K Frequent Elements Problem on 🐍 Python language](https://leetcode.com/problems/top-k-frequent-elements/solutions/3594131/counts-and-sort-to-solve-the-top-k-frequent-elements-problem-on-python-language/) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | 1. Create an empty dictionary called `hashSet` to store the frequencies of elements. 6 | 2. Iterate through the `nums` list using a for loop. 7 | 3. For each element `num` in the `nums` list, update its frequency in the `hashSet` dictionary by incrementing the value associated with the key `num`. If the key doesn't exist, set its value to 1. 8 | 4. Convert the `hashSet` dictionary into a list of tuples called `freq_list` using the `items()` method. Each tuple in `freq_list` contains an element from the `nums` list and its corresponding frequency. 9 | 5. Sort the `freq_list` in descending order based on the second element (frequency) of each tuple. This is achieved using the `sort()` method with a lambda function as the `key` argument. 10 | 6. Extract the first `k` elements from the sorted `freq_list` and store them in the `result` list. The first element of each tuple in `freq_list` represents the element from `nums`. 11 | 7. Return the `result` list containing the top `k` frequent elements. 12 | 13 | ## 🔐 Code 14 | 15 | ``` python 16 | class Solution: 17 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 18 | hashSet = {} #create empty dict 19 | 20 | #hashSet = {1: 3, 2: 5, 4: 2} 21 | for i in range(len(nums)): 22 | hashSet[nums[i]] = 1 + hashSet.get(nums[i], 0) 23 | 24 | # freq_list = [(1,3),(2,5),(4,2)] 25 | freq_list = list(hashSet.items()) 26 | # freq_list = [(2,5),(1,3),(4,2)] 27 | freq_list.sort(key=lambda x: x[1], reverse=True) #x represent each tuple 28 | 29 | # result[2,1] 30 | result = [x[0] for x in freq_list[:k]] 31 | return result 32 | ``` 33 | 34 | ## 🧩 Complexity 35 | 36 | - Time complexity: 37 | 38 | The time complexity of this code is dominated by the sorting operation performed on `freq_list`. Sorting a list of length `n` has a time complexity of O(n log n). Therefore, the overall time complexity of the code is O(n log n), where `n` is the length of the input list `nums`. 39 | 40 | - Space complexity: 41 | 42 | The space complexity is determined by the space used to store the `hashSet` dictionary and the `freq_list`. The `hashSet` dictionary will have a space complexity of O(n) in the worst case, where `n` is the length of the input list `nums`. The `freq_list` will also have a space complexity of O(n) because it stores all the elements and their frequencies. Additionally, the `result` list will have a space complexity of O(k) since it stores the top `k` frequent elements. Therefore, the overall space complexity is O(n + k), where `n` is the length of the input list `nums` and `k` is the parameter passed to the method. 43 | -------------------------------------------------------------------------------- /Python/0347-top-k-frequent-elements/question.md: -------------------------------------------------------------------------------- 1 | # [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:** nums = \[1,1,1,2,2,3\], k = 2
11 | **Output:** \[1,2\]
12 | 13 | **Example 2:** 14 | 15 | 16 | >**Input:** nums = \[1\], k = 1
17 | **Output:** \[1\]
18 | 19 | **Constraints:** 20 | 21 | - $1 <= nums.length <= 10^5$ 22 | - $-10^4 <= nums[i] <= 10^4$ 23 | - k is in the range [1, the number of unique elements in the array]. 24 | - It is guaranteed that the answer is unique. 25 | 26 | **Follow-up:** 27 | 28 | Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size. 29 | 30 | ## 🔐 Solutions 31 | 32 | 33 | | ID | METHOD | 34 | | :-- | :--------------------: | 35 | | 1 | [Count And Sort](1-answer.md) | 36 | -------------------------------------------------------------------------------- /Python/0704-binary-search/1-answer.md: -------------------------------------------------------------------------------- 1 | # [Header](link) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | Explain the approach 6 | 7 | ## 🔐 Code 8 | 9 | ``` Programming language 10 | printf("Hello World"); 11 | ``` 12 | 13 | ## 🧩 Complexity 14 | 15 | - Time complexity: 16 | 17 | Time Complexity 18 | 19 | - Space complexity: 20 | 21 | Space Complexity 22 | -------------------------------------------------------------------------------- /Python/0704-binary-search/question.md: -------------------------------------------------------------------------------- 1 | # [Binary Search](https://leetcode.com/problems/binary-search/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`. 6 | 7 | You must write an algorithm with `O(log n)` runtime complexity. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** nums = \[-1,0,3,5,9,12\], target = 9
13 | **Output:** 4
14 | **Explanation:** 9 exists in nums and its index is 4 15 | 16 | **Example 2:** 17 | 18 | 19 | >**Input:** nums = \[-1,0,3,5,9,12\], target = 2
20 | **Output:** -1
21 | **Explanation:** 2 does not exist in nums so return -1 22 | 23 | **Constraints:** 24 | 25 | - $1 <= nums.length <= 10^4$ 26 | - $-10^4 < nums[i], target < 10^4$ 27 | - All the integers in `nums` are **unique**. 28 | - `nums` is sorted in ascending order. 29 | 30 | ## 🔐 Solutions 31 | 32 | 33 | | ID | METHOD | 34 | | :-- | :--------------------: | 35 | | 1 | [example](1-answer.md) | 36 | -------------------------------------------------------------------------------- /Python/README.md: -------------------------------------------------------------------------------- 1 | # Awesome Leetcode Algorithms Solutions With Python 2 | 3 | 4 | 5 | 6 | 7 | Twitter Follow 8 | 9 | 10 | Author: 11 | Muhammed Mustafa (muffafa) Savar
12 | May, 2023 13 |
14 | 15 | --- 16 | 17 | ## 🙋🏻 Introduction 18 | 19 | Welcome to the solutions of leetcode algorithms with Python. 20 | 21 | ## 🚀 How to Use It? 22 | 23 | I suggest cloning the repository locally to work with it, but you can easily look at any solution you want without cloning it. Simply press `Ctrl + F` and type the name of the question or its ID. Each folder includes an .md file that you can click on to go to the Leetcode website. There are two parts of questions: 24 | 25 | 1. Problem:
This part includes the definition of the problem, example cases, input and output examples, constraints, and follow-up information. 26 | 2. Solution:
This part includes a table to navigate to the solutions. 27 | 28 | ## 😎 Solutions 29 | 30 | Each .md file for a solution includes: 31 | 32 | - Header (that navigates to the online explanation of the solution) 33 | - Approach (describing the approach to solving the problem) 34 | - Complexity (determining the time and space complexity of the solution) 35 | - Code (the actual solution to the problem) 36 | 37 | --- 38 | 39 | | ID | Leetcode ID | 👀 Question Name | 📦 Category | 🔥 Difficulty | 40 | | --- | :---------- | :---------------------------------------------------------------------------------: | ---------------- | -------------- | 41 | | 1 | 0001 | [Two Sum](0001-two-sum/question.md) | Arrays & Hashing | Easy | 42 | | 2 | 0217 | [Contains Duplicate](0217-contains-duplicate/question.md) | Arrays & Hashing | Easy | 43 | | 3 | 0242 | [Valid Anagram](0242-valid-anagram/question.md) | Arrays & Hashing | Easy | 44 | | 4 | 0049 | [Group Anagram](0049-group-anagram/question.md) | Arrays & Hashing | Medium | 45 | | 5 | 0347 | [Top K Frequent Elements](0347-top-k-frequent-elements/question.md) | Arrays & Hashing | Medium | 46 | | 6 | 0238 | [Product Of Array Except Self](0238-product-of-array-except-self/question.md) | Arrays & Hashing | Medium | 47 | | 7 | 0020 | [Valid Parentheses](0020-valid-parentheses/question.md) | Stack | Easy | 48 | | 8 | 0125 | [Valid Palindrome](0125-valid-palindrome/question.md) | Two Pointers | Easy | 49 | | 9 | 0155 | [Min Stack](0155-min-stack/question.md) | Stack | Medium | 50 | | 10 | 0167 | [Two Sum II Input Array Is Sorted](0167-two-sum-2/question.md) | Two Pointers | Medium | 51 | | 11 | 0121 | [Best Time to Buy and Sell Stock](0121-best-time-to-buy-and-sell-stock/question.md) | Sliding Window | Easy | 52 | | 12 | 0206 | [Reverse Linked List](0206-reverse-linked-list/question.md) | Linked List | Easy | 53 | | 13 | 0021 | [Merge Two Sorted Lists](0021-merge-two-sorted-lists/question.md) | Linked List | Easy | 54 | | 14 | 0704 | [Binary Search](0704-binary-search/question.md) | Binary Search | Easy | 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Awesome Leetcode Algorithms Solutions 2 | 3 | | 🗣️ Language | 🔗 Repo Link | 👀 Contributors | 🧠 Quantity | 4 | | -------------- | ---------------------------------- | ---------------------------------------------------- | ------------ | 5 | | Python | [Python](Python/README.md) | [@muffafa](https://github.com/muffafa) | 14 | 6 | | Java | [JAVA](Java/README.md) | [@cagridemirtash](https://github.com/cagridemirtash) | 3 | 7 | | Javascript | [Javascript](Javascript/README.md) | [@kaanncavdar](https://github.com/kaanncavdar) | 4 | 8 | | Rust | [Rust](Rust/README.md) | [@sektor7k](https://github.com/sektor7k) | 13 | 9 | | C++ | [Cpp](Cpp/README.md) | [@sametaydinq](https://github.com/sametaydinq) | 0 | 10 | 11 | --- 12 | 13 | ## 🙋🏻 Introduction 14 | 15 | Welcome to the solutions of leetcode algorithms. 16 | 17 | ## 🚀 How to Use It? 18 | 19 | I suggest cloning the repository locally to work with it, but you can easily look at any solution you want without cloning it. Simply press `Ctrl + F` and type the name of the question or its ID. Each folder includes an .md file that you can click on to go to the Leetcode website. There are two parts of questions: 20 | 21 | 1. Problem:
This part includes the definition of the problem, example cases, input and output examples, constraints, and follow-up information. 22 | 2. Solution:
This part includes a table to navigate to the solutions. 23 | 24 | ## 😎 Solutions 25 | 26 | Each .md file for a solution includes: 27 | 28 | - Header (that navigates to the online explanation of the solution) 29 | - Approach (describing the approach to solving the problem) 30 | - Complexity (determining the time and space complexity of the solution) 31 | - Code (the actual solution to the problem) 32 | 33 | ## 👾 How to Clone It? 34 | 35 | > `git clone https://github.com/cukurovablock/awesome-leetcode-algorithms-solutions.git` 36 | 37 | ## 👽 Extensions 38 | 39 | - [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) 40 | - [Markdown Table](https://marketplace.visualstudio.com/items?itemName=TakumiI.markdowntable) 41 | - [Markdown All in One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) 42 | - [Markdown Preview Github Styling](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-preview-github-styles) 43 | - [Auto-Open Markdown Preview](https://marketplace.visualstudio.com/items?itemName=hnw.vscode-auto-open-markdown-preview) 44 | - [vscode-icons](https://marketplace.visualstudio.com/items?itemName=vscode-icons-team.vscode-icons) 45 | 46 | ## 🫶🏻 How to Contribute? 47 | 48 | [How to Contribute to Open Source Projects on GitHub](https://www.youtube.com/watch?v=waEb2c9NDL8) 49 | 50 | You can create a custom snippet for .md files in Visual Studio Code: 51 | 52 | 1. Open Visual Studio Code, click "File" > "Preferences" > "User Snippets". 53 | 2. Select "Markdown" from the list of languages. 54 | 3. Add the following code to create a basic markdown snippet. 55 | 4. You can easily type `mdproblem` to create a problem template and `mdsolution` to create a solution template. `mdexample`, `mdexamplewithexplanation` and `mdheading` snippets also can be used. 56 | 5. Now you can easily start contributing! 57 | 58 | ``` json 59 | { 60 | "Leetcode Problem Template": { 61 | "prefix": "mdproblem", 62 | "body": [ 63 | "# [${6:Header}](${7:Link})", 64 | "", 65 | "## 🚨 Problem", 66 | "", 67 | "${1:Explain the problem}", 68 | "", 69 | "**Example 1:**", 70 | "", 71 | "", 72 | ">**Input:** ${2}
", 73 | "**Output:** ${3}
", 74 | "**Explanation:** ${4} ", 75 | "", 76 | "**Constraints:**", 77 | "", 78 | "- ${5}", 79 | "", 80 | "**Follow-up:** ", 81 | "", 82 | "", 83 | "## 🔐 Solutions", 84 | "", 85 | "", 86 | "| ID | METHOD |", 87 | "| :-- | :--------------------: |", 88 | "| 1 | [example](1-answer.md) |", 89 | "" 90 | ], 91 | "description": "It creates a problem template for leetcode" 92 | }, 93 | "Leetcode Solution Template": { 94 | "prefix": "mdsolution", 95 | "body": [ 96 | "# [${6:Header}](${7:link})", 97 | "", 98 | "## 🧑🏻‍💻 Approach", 99 | "", 100 | "${1:Explain the approach}", 101 | "", 102 | "## 🔐 Code", 103 | "", 104 | "``` ${2:Programming language}", 105 | "${3:printf(\"Hello World\");}", 106 | "```", 107 | "", 108 | "## 🧩 Complexity", 109 | "", 110 | "- Time complexity:", 111 | "", 112 | "${4:Time Complexity}", 113 | "", 114 | "- Space complexity:", 115 | "", 116 | "${5:Space Complexity}", 117 | "" 118 | ], 119 | "description": "It creates a solution template for leetcode problem" 120 | }, 121 | "Leetcode Example Template": { 122 | "prefix": "mdexample", 123 | "body": [ 124 | "**Example ${1}:**", 125 | "", 126 | "", 127 | ">**Input:** ${2}
", 128 | "**Output:** ${3}
", 129 | ], 130 | "description": "It creates a example template for leetcode problem" 131 | }, 132 | "Leetcode Example Template w/ Explanation": { 133 | "prefix": "mdexamplewithexplanation", 134 | "body": [ 135 | "**Example ${1}:**", 136 | "", 137 | "", 138 | ">**Input:** ${2}
", 139 | "**Output:** ${3}
", 140 | "**Explanation:** ${4} ", 141 | "" 142 | ], 143 | "description": "It creates a example template with explanation for leetcode problem" 144 | }, 145 | "Leetcode Heading Template for Solution": { 146 | "prefix": "mdheading", 147 | "body": [ 148 | "✅ ${1:Method} to solve the 🧑🏻‍💻 ${2:Question Name} Problem on 🐍 ${3:Language Name}" 149 | ], 150 | "description": "It creates a heading for leetcode solution" 151 | } 152 | } 153 | ``` 154 | -------------------------------------------------------------------------------- /Rust/0001-two-sum/question.md: -------------------------------------------------------------------------------- 1 | # [1. Two Sum](https://leetcode.com/problems/two-sum) 2 | 3 | ## Problem 4 | 5 | Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. 6 | 7 | You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. 8 | 9 | You can return the answer in any order. 10 | 11 | **Example 1:** 12 | 13 | >**Input:** nums = \[2,7,11,15\], target = 9
14 | **Output:** \[0,1\]
15 | **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. 16 | 17 | **Example 2:** 18 | 19 | >**Input:** nums = \[3,2,4\], target = 6
20 | **Output:** \[1,2\] 21 | 22 | **Example 3:** 23 | 24 | >**Input:** nums = \[3,3\], target = 6
25 | **Output:** \[0,1\] 26 | 27 | **Constraints:** 28 | 29 | - $2 <= nums.length <= 10^4$ 30 | - $-10^9 <= nums[i] <= 10^9$ 31 | - $-10^9 <= target <= 10^9$ 32 | - **Only one valid answer exists.** 33 | 34 | **Follow-up:** Can you come up with an algorithm that is less than $O(n^2)$ time complexity? 35 | 36 | ## Solutions 37 | 38 | | ID | METHOD | LINK | 39 | | :-- | :---------: | :----------------------- | 40 | | 1 | Brute Force | [two-sum.md](two-sum.md) | 41 | -------------------------------------------------------------------------------- /Rust/0001-two-sum/two-sum.md: -------------------------------------------------------------------------------- 1 | # Brute Force to solve the Two-Sum Problem on Rust language 2 | 3 | 4 | ## 🧑🏻‍💻 Approach 5 | 6 | The function `two_sum` takes two parameters: a vector of integers `nums` and a target integer `target`. It aims to find two numbers in the `nums` vector whose sum equals the `target`. The function returns a vector containing the indices of these two numbers. 7 | 8 | In the beginning, you initialize an empty vector called `result` to store the indices of the two numbers. 9 | 10 | You then iterate through the `nums` vector using two nested loops, represented by `i` and `j`. The condition `i.0 != j.0` ensures that you don't compare the same element with itself. 11 | 12 | Inside the nested loops, you check if the sum of the current pair of numbers (`i.1` and `j.1`) is equal to the `target`. If it is, you push the indices (`i.0` and `j.0`) into the `result` vector and break out of the inner loop. 13 | 14 | After the inner loop, you check if the `result` vector contains any indices. If it does, you break out of the outer loop as well. 15 | 16 | Finally, you return the `result` vector. 17 | ## Code 18 | 19 | ``` Rust 20 | impl Solution { 21 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 22 | 23 | let mut result = Vec::new(); 24 | 25 | for i in nums.iter().enumerate(){ 26 | 27 | 28 | for j in nums.iter().enumerate(){ 29 | 30 | if i.0 != j.0 && i.1+j.1== target{ 31 | 32 | result.push(i.0 as i32); 33 | result.push(j.0 as i32); 34 | break; 35 | 36 | } 37 | } 38 | if result.len()>0{ 39 | break; 40 | } 41 | } 42 | return result; 43 | 44 | 45 | } 46 | } 47 | ``` 48 | -------------------------------------------------------------------------------- /Rust/0020-valid-parentheses/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Stack and Map to solve the 🧑🏻‍💻 Valid Parentheses on 🦀 RUST language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | Create an empty vector called `result` to act as a stack. 6 | 7 | Iterate over each character, `i`, in the given string `s`. 8 | 9 | Inside the loop, use a match statement to handle different cases: 10 | 11 | If i is an opening bracket, i.e., `'('`, `'{'`, or `'['`, push it onto the stack (`result` vector). 12 | 13 | If `i` is a closing bracket, check if the top element of the stack matches the corresponding opening bracket. If it does not match or the stack is empty, return `false`, as the brackets are not valid. 14 | 15 | After processing all the characters, check if the stack is empty. If it is empty, return `true`, indicating that all brackets are valid. Otherwise, return `false`, indicating that there are unmatched brackets. 16 | 17 | ## 🔐 Code 18 | 19 | ``` RUST 20 | impl Solution { 21 | pub fn is_valid(s: String) -> bool { 22 | 23 | let mut result : Vec = Vec::new(); 24 | 25 | for i in s.chars(){ 26 | match i { 27 | '('|'{'|'[' => result.push(i), 28 | ')' => { 29 | if result.pop() != Some('('){ 30 | return false; 31 | } 32 | } 33 | '}' => { 34 | if result.pop() != Some('{'){ 35 | return false; 36 | } 37 | } 38 | ']' => { 39 | if result.pop() != Some('['){ 40 | return false; 41 | } 42 | } 43 | 44 | _ => return false, 45 | } 46 | 47 | 48 | } 49 | return result.is_empty(); 50 | 51 | 52 | } 53 | 54 | } 55 | ``` 56 | 57 | 58 | -------------------------------------------------------------------------------- /Rust/0020-valid-parentheses/question.md: -------------------------------------------------------------------------------- 1 | # [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. 6 | 7 | An input string is valid if: 8 | 9 | 1. Open brackets must be closed by the same type of brackets. 10 | 2. Open brackets must be closed in the correct order. 11 | 3. Every close bracket has a corresponding open bracket of the same type. 12 | 13 | **Example 1:** 14 | 15 | 16 | >**Input:** s = "()"
17 | **Output:** true
18 | 19 | **Example 2:** 20 | 21 | 22 | >**Input:** s = "()\[\]{}"
23 | **Output:** true
24 | 25 | **Example 3:** 26 | 27 | 28 | >**Input:** s = "(\]"
29 | **Output:** false
30 | 31 | **Constraints:** 32 | 33 | - $1 <= s.length <= 10^4$ 34 | - `s` consists of parentheses only `'()[]{}'`. 35 | 36 | ## 🔐 Solutions 37 | 38 | 39 | | ID | METHOD | 40 | | :-- | :--------------------: | 41 | | 1 | [Stack and Map](1-answer.md) | 42 | -------------------------------------------------------------------------------- /Rust/0049-group-anagram/group-anagram.md: -------------------------------------------------------------------------------- 1 | # ✅ Counts the Frequencies to solve the 🧑🏻‍💻 Group Anagram Problem on 😎 Rust language 2 | 3 | 4 | ## 🧑🏻‍💻 Approach 5 | 6 | This code contains a function called `group_anagrams`, which takes a `Vec` parameter named `strs` and returns a vector containing the groups of anagrams. 7 | 8 | Firstly, a `HashMap` named `groups` is created. This `HashMap` will be used to group the anagrams. The keys are `Vec` that represent the sorted characters of the words in alphabetical order. The values are `Vec` that hold the lists of grouped words. 9 | 10 | Then, for each word in the `strs` vector, the following steps are performed: 11 | 12 | Convert the characters of the word into a `Vec` called `chars` using the `chars()` method and `collect()` function. 13 | Sort the `chars` vector in alphabetical order using the `sort()` method. 14 | In the `groups` hashmap, try to find the corresponding entry using `chars` as the key. If the entry exists, the `entry` variable will hold a reference to the existing entry. If the entry doesn't exist, the `or_insert(Vec::new())` method will create a new entry with an empty `Vec` as the value and return a reference to the newly created entry. 15 | Append the word to the value associated with the obtained entry reference using the `entry.push(i)` statement. This adds the word to the value of the corresponding key, grouping the anagrams together. 16 | Finally, the code returns a `Vec>` by cloning the values from the `groups` hashmap using `groups.values().cloned().` 17 | 18 | This way, the `group_anagrams` function will group the anagrams in the strs vector and return a vector containing the groups of anagrams. 19 | 20 | ## Code 21 | 22 | ``` Rust 23 | use std::collections::HashMap; 24 | 25 | impl Solution { 26 | pub fn group_anagrams(strs: Vec) -> Vec> { 27 | 28 | let mut groups: HashMap, Vec> = HashMap::new(); 29 | 30 | for i in strs { 31 | let mut chars: Vec = i.chars().collect(); 32 | chars.sort(); 33 | let entry = groups.entry(chars).or_insert(Vec::new()); 34 | entry.push(i); 35 | } 36 | 37 | groups.values().cloned().collect() 38 | 39 | } 40 | } 41 | ``` -------------------------------------------------------------------------------- /Rust/0049-group-anagram/question.md: -------------------------------------------------------------------------------- 1 | # [Group Anagrams](https://leetcode.com/problems/group-anagrams/) 2 | 3 | ## Problem 4 | 5 | Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
13 | **Output:** \[\["bat"\], \["nat", "tan"\], \["ate", "eat", "tea"\]\]
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** strs = \[""\]
19 | **Output:** \[\[""\]\]
20 | 21 | **Example 3:** 22 | 23 | 24 | >**Input:** strs = \["a"\]
25 | **Output:** \[\["a"\]\]
26 | 27 | **Constraints:** 28 | 29 | - $1 <= strs.length <= 10^4$ 30 | - $0 <= strs[i].length <= 100$ 31 | - $strs[i]$ consists of lowercase English letters. 32 | 33 | ## Solutions 34 | 35 | 36 | | ID | METHOD | LINK | 37 | | :-- | :-----: | :----------------------- | 38 | | 1 | example | [link](group-anagram.md) | 39 | -------------------------------------------------------------------------------- /Rust/0121-best-time-to-buy-and-sell-stock/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Double Stack to solve the 🧑🏻‍💻 Best Time to Buy and Sell Stock Problem on 🦀 RUST language](#) 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The function `max_profit` takes a vector of integers `prices` as input and returns an integer representing the maximum profit that can be obtained from buying and selling a stock. 6 | 7 | The code begins by initializing two variables, `min_price` and `max_profit`. `min_price` is set to the maximum possible integer value initially, while `max_profit` is set to 0. 8 | 9 | The `for` loop iterates through each element `i` in the `prices` vector. Inside the loop, the code checks if the current price `i` is less than the current minimum price `min_price`. If it is, the `min_price` is updated to `i`, indicating that this is the new lowest price encountered so far. 10 | 11 | On the other hand, if the current price `i` is not less than the current minimum price, the code proceeds to check if the difference between `i` and `min_price` is greater than the current maximum profit `max_profit`. If it is, the `max_profit` is updated to the new higher profit, representing a better opportunity to sell the stock and maximize the gain. 12 | 13 | Once the loop completes, the final value of `max_profit` represents the maximum possible profit that could be achieved by buying the stock at the lowest price and selling it at the highest price. 14 | 15 | Finally, the function returns the calculated `max_profit`. 16 | 17 | ## 🔐 Code 18 | 19 | ``` rust 20 | impl Solution { 21 | pub fn max_profit(prices: Vec) -> i32 { 22 | let mut count = 0; 23 | 24 | 25 | 26 | let mut min_price = i32::max_value(); 27 | let mut max_profit = 0; 28 | 29 | for i in prices{ 30 | if i< min_price{ 31 | min_price = i; 32 | } 33 | else if i - min_price> max_profit{ 34 | max_profit = i - min_price; 35 | } 36 | } 37 | 38 | return max_profit; 39 | 40 | } 41 | } 42 | ``` 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Rust/0121-best-time-to-buy-and-sell-stock/question.md: -------------------------------------------------------------------------------- 1 | # [Best Time to Buy and Sell Stock]() 2 | 3 | ## 🚨 Problem 4 | 5 | You are given an array `prices` where `prices[i]` is the price of a given stock on the $i^{th}$ day. 6 | 7 | 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. 8 | 9 | Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. 10 | 11 | **Example 1:** 12 | 13 | 14 | >**Input:** prices = \[7,1,5,3,6,4\]
15 | **Output:** 5
16 | **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 17 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 18 | 19 | **Example 2:** 20 | 21 | 22 | >**Input:** prices = \[7,6,4,3,1\]
23 | **Output:** 0
24 | **Explanation:** In this case, no transactions are done and the max profit = 0. 25 | 26 | **Constraints:** 27 | 28 | - $1 <= prices.length <= 10^5$ 29 | - $0 <= prices[i] <= 10^4$ 30 | 31 | ## 🔐 Solutions 32 | 33 | 34 | | ID | METHOD | 35 | | :-- | :-------------------: | 36 | | 1 | [Answer](1-answer.md) | 37 | -------------------------------------------------------------------------------- /Rust/0125-valid-palindrome/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Lowercase Alphanumeric to solve the 🧑🏻‍💻 Valid Palindrome Problem on 🦀 Python language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The `Solution` struct contains a public function `is_palindrome` that takes a `String` parameter `s` and returns a boolean value. The goal of the function is to determine if the given string `s` is a palindrome. 6 | 7 | The solution first converts the string `s` to lowercase using the `to_lowercase` method, storing the result in the variable `a`. This step is necessary to perform a case-insensitive comparison. 8 | 9 | Next, the characters of `a` are collected into a vector `b` using the `chars` method. Each character is filtered using the `retain` method, which removes whitespace and punctuation characters from `b`. This is achieved by keeping only the characters for which the closure condition `!x.is_whitespace() && !x.is_ascii_punctuation()` returns true. 10 | 11 | To check if the string is a palindrome, a clone of `b` is created in the variable `c`. The reverse method is then used to `reverse` the order of characters in `c`. 12 | 13 | Finally, an if statement compares the vectors `b` and `c`. If they are equal, it means that the original string `s` is a palindrome, so the function returns `true`. Otherwise, it returns `false`. 14 | 15 | ## 🔐 Code 16 | 17 | ``` RUST 18 | impl Solution { 19 | pub fn is_palindrome(s: String) -> bool { 20 | let a = s.to_lowercase(); 21 | let mut b = a.chars().collect::>(); 22 | b.retain(|&x| !x.is_whitespace() && !x. is_ascii_punctuation()); 23 | 24 | let mut c = b.clone(); 25 | c.reverse(); 26 | if b == c{ 27 | return true; 28 | } 29 | return false; 30 | } 31 | } 32 | ``` 33 | 34 | 35 | -------------------------------------------------------------------------------- /Rust/0125-valid-palindrome/question.md: -------------------------------------------------------------------------------- 1 | # [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) 2 | 3 | ## 🚨 Problem 4 | 5 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. 6 | 7 | Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** s = "A man, a plan, a canal: Panama"
13 | **Output:** true
14 | **Explanation:** "amanaplanacanalpanama" is a palindrome. 15 | 16 | **Example 2:** 17 | 18 | 19 | >**Input:** s = "race a car"
20 | **Output:** false
21 | **Explanation:** "raceacar" is not a palindrome. 22 | 23 | **Example 3:** 24 | 25 | 26 | >**Input:** s = " "
27 | **Output:** true
28 | **Explanation:** s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. 29 | 30 | **Constraints:** 31 | 32 | - $1 <= s.length <= 2 * 10^5$ 33 | - `s` consists only of printable ASCII characters. 34 | 35 | **Follow-up:** 36 | 37 | 38 | ## 🔐 Solutions 39 | 40 | 41 | | ID | METHOD | 42 | | :-- | :-----------------------------------: | 43 | | 1 | [Lowercase Alphanumeric](1-answer.md) | 44 | -------------------------------------------------------------------------------- /Rust/0155-min-stack/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Double Stack to solve the 🧑🏻‍💻 Min Stack Problem on 🦀 RUST language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | `new()`: This is the constructor method that creates a new instance of `MinStack` by initializing an empty `Vec` using `Vec::new()`. 6 | 7 | `push(&mut self, val: i32)`: This method takes an integer value `val` as a parameter and adds it to the top of the stack by using the `push` method of the underlying `Vec`. 8 | 9 | `pop(&mut self)`: This method removes the top element from the stack by using the `pop` method of the underlying `Vec`. 10 | 11 | `top(&self) -> i32`: This method returns the value of the top element of the stack without removing it. It uses the `last` method of the `Vec` to get a reference to the last element and then dereferences it with `*` to obtain the value. 12 | 13 | `get_min(&self) -> i32`: This method returns the minimum value in the stack. It uses the `iter` method of the `Vec` to create an iterator over the elements, and then calls the `min` method to find the minimum value. The minimum value is obtained by calling `unwrap` on the result, assuming that the stack is not empty. 14 | 15 | ## 🔐 Code 16 | 17 | ``` RUST 18 | #[derive(Debug)] 19 | struct MinStack { 20 | stack:Vec 21 | 22 | } 23 | /** 24 | * `&self` means the method takes an immutable reference. 25 | * If you need a mutable reference, change it to `&mut self` instead. 26 | */ 27 | impl MinStack { 28 | 29 | fn new() -> Self { 30 | MinStack { stack: Vec::new() } 31 | } 32 | 33 | fn push(&mut self, val: i32) { 34 | self.stack.push(val); 35 | 36 | } 37 | 38 | fn pop(&mut self) { 39 | self.stack.pop(); 40 | 41 | } 42 | 43 | fn top(&self) -> i32 { 44 | *self.stack.last().unwrap() 45 | } 46 | 47 | fn get_min(&self) -> i32 { 48 | *self.stack.iter().min().unwrap() 49 | } 50 | } 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /Rust/0155-min-stack/2-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Double Stack to solve the 🧑🏻‍💻 Min Stack Problem on 🦀 RUST language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | `new()`: This is the constructor method that creates a new instance of `MinStack` by initializing empty vectors for `stack` and `min_stack` using `Vec::new()`. 6 | 7 | `push(&mut self, val: i32)`: This method takes an integer value `val` as a parameter and adds it to the top of the `stack` by using the `push` method of the `stack` vector. It also checks if the `min_stack` is empty or if the new value `val` is less than or equal to the current minimum value (`*self.min_stack.last().unwrap()`). If so, it pushes the new value `val` to the `min_stack` as well. 8 | 9 | `pop(&mut self)`: This method removes the top element from the `stack` by using the `pop` method of the `stack` vector. It also checks if the removed element is equal to the current minimum value (`*self.min_stack.last().unwrap()`). If so, it removes the minimum value from the `min_stack` as well. 10 | 11 | `top(&self) -> i32`: This method returns the value of the top element of the `stack` without removing it. It uses the `last` method of the `stack` vector to get a reference to the last element and then dereferences it with `*` to obtain the value. 12 | 13 | `get_min(&self) -> i32`: This method returns the minimum value in the `stack` by accessing the last element of the `min_stack`. It uses the last method of the `min_stack` vector to get a reference to the last element and then dereferences it with `* `to obtain the value. 14 | 15 | ## 🔐 Code 16 | 17 | ``` RUST 18 | struct MinStack { 19 | stack:Vec, 20 | min_stack:Vec 21 | } 22 | 23 | 24 | /** 25 | * `&self` means the method takes an immutable reference. 26 | * If you need a mutable reference, change it to `&mut self` instead. 27 | */ 28 | impl MinStack { 29 | 30 | fn new() -> Self { 31 | MinStack { stack: Vec::new(), min_stack: Vec::new() } 32 | } 33 | 34 | fn push(&mut self, val: i32) { 35 | self.stack.push(val); 36 | if self.min_stack.is_empty() || val <= *self.min_stack.last().unwrap(){ 37 | self.min_stack.push(val) 38 | } 39 | } 40 | 41 | fn pop(&mut self) { 42 | if let Some(x) = self.stack.pop() { 43 | if x == *self.min_stack.last().unwrap() { 44 | self.min_stack.pop(); 45 | } 46 | } 47 | 48 | } 49 | 50 | fn top(&self) -> i32 { 51 | *self.stack.last().unwrap() 52 | } 53 | 54 | fn get_min(&self) -> i32 { 55 | *self.min_stack.last().unwrap() 56 | } 57 | } 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /Rust/0155-min-stack/question.md: -------------------------------------------------------------------------------- 1 | # [Min Stack](https://leetcode.com/problems/min-stack/) 2 | 3 | ## 🚨 Problem 4 | 5 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 6 | 7 | Implement the `MinStack` class: 8 | 9 | - `MinStack()` initializes the stack object. 10 | - `void push(int val)` pushes the element `val` onto the stack. 11 | - `void pop()` removes the element on the top of the stack. 12 | - `int top()` gets the top element of the stack. 13 | - `int getMin()` retrieves the minimum element in the stack. 14 | 15 | You must implement a solution with `O(1)` time complexity for each function. 16 | 17 | **Example 1:** 18 | 19 | 20 | >**Input:** \["MinStack","push","push","push","getMin","pop","top","getMin"\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]

21 | **Output:** \[null,null,null,null,-3,null,0,-2\]

22 | **Explanation:** 23 | MinStack minStack = new MinStack();
24 | minStack.push(-2);
25 | minStack.push(0);
26 | minStack.push(-3);
27 | minStack.getMin(); // return -3
28 | minStack.pop();
29 | minStack.top(); // return 0
30 | minStack.getMin(); // return -2 31 | 32 | **Constraints:** 33 | 34 | - $-2^{31} <= val <= 2^{31} - 1$ 35 | - Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. 36 | - At most $3 * 10^4$ calls will be made to `push`, `pop`, `top`, and `getMin`. 37 | 38 | **Follow-up:** 39 | 40 | 41 | ## 🔐 Solutions 42 | 43 | 44 | | ID | METHOD | 45 | | :-- | :-------------------------: | 46 | | 1 | [Double Stack](1-answer.md) | 47 | | 2 | [Double Stack 2](2-answer.md) | 48 | -------------------------------------------------------------------------------- /Rust/0167-two-sum-2/1-answer.md: -------------------------------------------------------------------------------- 1 | # Brute Force to solve the Two-Sum 2 Problem on Rust language 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The function `two_sum` takes two parameters: a vector of integers `nums` and a target integer `target`. It aims to find two numbers in the `nums` vector whose sum equals the `target`. The function returns a vector containing the indices of these two numbers. 6 | 7 | In the beginning, you initialize an empty vector called `result` to store the indices of the two numbers. 8 | 9 | You then iterate through the `nums` vector using two nested loops, represented by `i` and `j`. The condition `i.0 != j.0` ensures that you don't compare the same element with itself. 10 | 11 | Inside the nested loops, you check if the sum of the current pair of numbers (`i.1` and `j.1`) is equal to the `target`. If it is, you push the indices (`i.0` and `j.0`) into the `result` vector and break out of the inner loop. 12 | 13 | After the inner loop, you check if the `result` vector contains any indices. If it does, you break out of the outer loop as well. 14 | 15 | Finally, you return the `result` vector. 16 | ## Code 17 | 18 | ``` Rust 19 | impl Solution { 20 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 21 | 22 | let mut result = Vec::new(); 23 | 24 | for i in nums.iter().enumerate(){ 25 | 26 | 27 | for j in nums.iter().enumerate(){ 28 | 29 | if i.0 != j.0 && i.1+j.1== target{ 30 | 31 | result.push((i.0 as i32)+1); 32 | result.push((j.0 as i32)+1); 33 | break; 34 | 35 | } 36 | } 37 | if result.len()>0{ 38 | break; 39 | } 40 | } 41 | return result; 42 | 43 | 44 | } 45 | } 46 | ``` -------------------------------------------------------------------------------- /Rust/0167-two-sum-2/question.md: -------------------------------------------------------------------------------- 1 | # [Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be $numbers[index_1]$ and $numbers[index_2]$ where $1 <= index_1 < index_2 < numbers.length$. 6 | 7 | Return _the indices of the two numbers,_ $index_1$ _and_ $index_2$_, **added by one** as an integer array_ $[index_1, index_2]$ _of length 2._ 8 | 9 | The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. 10 | 11 | Your solution must use only constant extra space. 12 | 13 | **Example 1:** 14 | 15 | 16 | >**Input:** numbers = \[2,7,11,15\], target = 9
17 | **Output:** \[1,2\]
18 | **Explanation:** The sum of 2 and 7 is 9. Therefore, $index_1$ = 1, $index_2$ = 2. We return \[1, 2\]. 19 | 20 | **Example 2:** 21 | 22 | 23 | >**Input:** numbers = \[2,3,4\], target = 6
24 | **Output:** \[1,3\]
25 | **Explanation:** The sum of 2 and 4 is 6. Therefore $index_1$ = 1, $index_2$ = 3. We return \[1, 3\]. 26 | 27 | **Example 3:** 28 | 29 | 30 | >**Input:** numbers = \[\-1,0\], target = -1
31 | **Output:** \[1,2\]
32 | **Explanation:** The sum of -1 and 0 is -1. Therefore $index_1$ = 1, $index_2$ = 2. We return \[1, 2\]. 33 | 34 | **Constraints:** 35 | 36 | - $2 <= numbers.length <= 3 * 10^4$ 37 | - $-1000 <= numbers[i] <= 1000$ 38 | - `numbers` is sorted in **non-decreasing order**. 39 | - $-1000 <= target <= 1000$ 40 | - The tests are generated such that there is **exactly one solution**. 41 | 42 | **Follow-up:** 43 | 44 | 45 | ## 🔐 Solutions 46 | 47 | 48 | | ID | METHOD | 49 | | :-- | :--------------------: | 50 | | 1 | [Brute Force](1-answer.md) | 51 | -------------------------------------------------------------------------------- /Rust/0206-reverse-linked-list/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Iteratively solving the 🧑🏻‍💻 Reverse Linked List Problem on 🦀 Rust language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | The given code defines a struct `ListNode` that represents a node of a linked list. It has two fields: `val`, which stores the value of the node, and `next`, which is an `Option` containing the next node in the list. 6 | 7 | The `impl` block contains an implementation for the `ListNode` struct. It defines a constructor function `new` that creates a new `ListNode` with the given value and initializes `next` to `None`. 8 | 9 | The `reverse_list` function takes an `Option>` as input, representing the head of a linked list, and returns the head of the reversed linked list. 10 | 11 | Inside the function, two variables `current` and `previous` are initialized. `current` holds the current node being processed, and `previous` holds the reversed portion of the linked list. 12 | 13 | The function enters a loop, where it iteratively reverses the linked list. It uses a combination of `while let` and `Option::take()` to move the current node (`node`) out of the Option and assign its next to `current`. 14 | 15 | Within each iteration, the `next` node is temporarily stored, and the `next` field of the current node is set to `previous`, effectively reversing the pointer direction. 16 | 17 | Finally, the `previous` node becomes the new `current` node, and the `next` node becomes the new `current` for the next iteration. 18 | 19 | Once the loop completes, the reversed linked list is stored in `previous`, which now represents the new head of the reversed list, and it is returned. 20 | 21 | ## 🔐 Code 22 | 23 | ``` rust 24 | // Definition for singly-linked list. 25 | // #[derive(PartialEq, Eq, Clone, Debug)] 26 | // pub struct ListNode { 27 | // pub val: i32, 28 | // pub next: Option> 29 | // } 30 | // 31 | // impl ListNode { 32 | // #[inline] 33 | // fn new(val: i32) -> Self { 34 | // ListNode { 35 | // next: None, 36 | // val 37 | // } 38 | // } 39 | // } 40 | impl Solution { 41 | pub fn reverse_list(head: Option>) -> Option> { 42 | let mut current = head; 43 | let mut previous = None; 44 | 45 | while let Some(mut node) = current{ 46 | let next = node.next.take(); 47 | node.next=previous; 48 | previous = Some(node); 49 | current = next; 50 | } 51 | 52 | previous 53 | } 54 | } 55 | ``` 56 | -------------------------------------------------------------------------------- /Rust/0206-reverse-linked-list/img/rev1ex1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cukurovablock/awesome-leetcode-algorithms-solutions/5bc0ac7aad4074968d39cee125ab49707f6e6d4b/Rust/0206-reverse-linked-list/img/rev1ex1.jpg -------------------------------------------------------------------------------- /Rust/0206-reverse-linked-list/img/rev1ex2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cukurovablock/awesome-leetcode-algorithms-solutions/5bc0ac7aad4074968d39cee125ab49707f6e6d4b/Rust/0206-reverse-linked-list/img/rev1ex2.jpg -------------------------------------------------------------------------------- /Rust/0206-reverse-linked-list/question.md: -------------------------------------------------------------------------------- 1 | # [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. 6 | 7 | **Example 1:** 8 | 9 | ![example 1](./img/rev1ex1.jpg) 10 | 11 | >**Input:** head = \[1,2,3,4,5\]
12 | **Output:** \[5,4,3,2,1\]
13 | 14 | **Example 2:** 15 | 16 | ![example 2](./img/rev1ex2.jpg) 17 | 18 | >**Input:** head = \[1,2\]
19 | **Output:** \[2,1\]
20 | 21 | **Example 3:** 22 | 23 | 24 | >**Input:** head = \[\]
25 | **Output:** \[\]
26 | 27 | **Constraints:** 28 | 29 | - The number of nodes in the list is the range `[0, 5000]`. 30 | - `-5000 <= Node.val <= 5000` 31 | 32 | **Follow-up:** 33 | 34 | A linked list can be reversed either iteratively or recursively. Could you implement both? 35 | 36 | ## 🔐 Solutions 37 | 38 | 39 | | ID | METHOD | 40 | | :-- | :----------------------: | 41 | | 1 | [Iterative](1-answer.md) | 42 | 43 | -------------------------------------------------------------------------------- /Rust/0217-contains-duplicate/1-answer.md: -------------------------------------------------------------------------------- 1 | # Contains Duplicate on Rust language 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | First, we import the necessary library std::collections::HashSet to use the HashSet data structure.ses a constant amount of memory, regardless of the size of the input array. Next, we define a function called contains_duplicate which takes a Vec input parameter named nums and returns a bool value. Inside the function, we create a HashSet of type HashSet to keep track of numbers we have encountered so far. Then, we start a loop for each element in the nums vector. At each iteration, we check if the element is already present in the set. If it is, it means we have encountered a duplicate element, so we return true. If the element is not present in the set, we add it to the set so that we can check if the next element is a duplicate. Once the loop is completed, it means there are no duplicate elements, so we return false. This way, the contains_duplicate function checks for the presence of duplicate elements in the given number vector. You can call the function and test it with sample cases to ensure its correctness. In this example, since the number 1 appears twice in the nums vector, the output will be "true". You can create your own test cases to verify that the function works correctly. 6 | 7 | ## Code 8 | 9 | ``` Rust 10 | use std::collections::HashSet; 11 | 12 | impl Solution { 13 | fn contains_duplicate(nums: Vec) -> bool { 14 | 15 | 16 | 17 | 18 | let mut set:HashSet = HashSet::new(); 19 | 20 | for i in nums { 21 | if set.contains(&i){ 22 | return true; 23 | } 24 | set.insert(i); 25 | } 26 | return false; 27 | 28 | 29 | } 30 | } 31 | ``` 32 | -------------------------------------------------------------------------------- /Rust/0217-contains-duplicate/question.md: -------------------------------------------------------------------------------- 1 | # [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) 2 | 3 | ## Problem 4 | 5 | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:** nums = \[1,2,3,1\]
11 | **Output:** true
12 | 13 | **Constraints:** 14 | 15 | - $1 <= nums.length <= 10^5$ 16 | - $-10^9 <= nums[i] <= 10^9$ 17 | 18 | ## Solutions 19 | 20 | 21 | | ID | METHOD | 22 | | :-- | :--------------------: | 23 | | 1 | [example](1-answer.md) | 24 | -------------------------------------------------------------------------------- /Rust/0238-product-of-array-except-self/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Prefix and Postfix to solve the 🧑🏻‍💻 Product of Array Except Self Problem on 🦀 Rust language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | First, we assign the length of the `nums` vector to the variable `n`. 6 | 7 | We create a vector called `left_vecs` and initialize each element to 1. This vector will represent the prefix products of each element. 8 | 9 | Next, we create a variable called `left` and set its initial value to 1. This variable will represent the product on the left side of each element. 10 | 11 | Using a loop from 1 to `n`, we update the `left` value and populate the `left_vecs` vector. At each step, we multiply `left` with the previous element in `nums` and assign the result to the corresponding index in `left_vecs`. 12 | 13 | We create a variable called `right` and set its initial value to 1. This variable will represent the product on the right side of each element. 14 | 15 | We create a result vector called `result` and initialize each element to 0. 16 | 17 | Using a reverse loop from `n-1` to 0, we fill the `result` vector. At each step, we multiply the prefix product (`left_vecs[i]`) with the suffix product (`right`) and assign the `result` to the corresponding index in `result`. Then, we update the right value by multiplying it with the current element in `nums`. 18 | 19 | Finally, we return the `result` vector. 20 | 21 | 22 | ## 🔐 Code 23 | 24 | ``` RUST 25 | impl Solution { 26 | pub fn product_except_self(nums: Vec) -> Vec { 27 | 28 | let n = nums.len(); 29 | 30 | // prefix 31 | let mut left_vecs = vec![1;n]; 32 | let mut left = 1; 33 | 34 | for i in 1..n{ 35 | left *= nums[i-1]; 36 | left_vecs[i] = left 37 | } 38 | 39 | // spefix or result 40 | let mut right = 1; 41 | let mut result = vec![0;n]; 42 | for i in (0..n).rev(){ 43 | result[i] = left_vecs[i] * right; 44 | right *= nums[i]; 45 | } 46 | 47 | 48 | return result; 49 | } 50 | } 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /Rust/0238-product-of-array-except-self/question.md: -------------------------------------------------------------------------------- 1 | # [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. 6 | 7 | The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. 8 | 9 | You must write an algorithm that runs in `O(n)` time and without using the division operation. 10 | 11 | **Example 1:** 12 | 13 | 14 | >**Input:** nums = \[1,2,3,4\]
15 | **Output:** \[24,12,8,6\]
16 | 17 | **Example 2:** 18 | 19 | 20 | >**Input:** nums = \[-1,1,0,-3,3\]
21 | **Output:** \[0,0,9,0,0\]
22 | 23 | **Constraints:** 24 | 25 | - $2 <= nums.length <= 10^5$ 26 | - $-30 <= nums[i] <= 30$ 27 | - The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 28 | 29 | **Follow-up:** 30 | Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.) 31 | 32 | ## 🔐 Solutions 33 | 34 | 35 | | ID | METHOD | 36 | | :-- | :--------------------: | 37 | | 1 | [example](1-answer.md) | 38 | -------------------------------------------------------------------------------- /Rust/0242-valid-anagram/question.md: -------------------------------------------------------------------------------- 1 | # [Valid Anagram](https://leetcode.com/problems/valid-anagram/) 2 | 3 | ## Problem 4 | 5 | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. 6 | 7 | An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** s = "anagram", t = "nagaram"
13 | **Output:** true
14 | 15 | **Example 2:** 16 | 17 | 18 | >**Input:** s = "rat", t = "car"
19 | **Output:** false
20 | 21 | **Constraints:** 22 | 23 | - $1 <= s.length, t.length <= 5 * 10^4$ 24 | - `s` and `t` consist of lowercase English letters. 25 | 26 | **Follow-up:** 27 | 28 | What if the inputs contain Unicode characters? How would you adapt your solution to such a case? 29 | 30 | ## Solutions 31 | 32 | 33 | | ID | METHOD | LINK | 34 | | :-- | :--------------------: | :----------------------------------- | 35 | | 1 | Counts the Frequencies | [valid-anagram.md](valid-anagram.md) | 36 | -------------------------------------------------------------------------------- /Rust/0242-valid-anagram/valid-anagram.md: -------------------------------------------------------------------------------- 1 | # ✅ Counts the Frequencies to solve the 🧑🏻‍💻 Valid Anagram Problem on 😎 Rust language 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | This code contains a function `is_anagram` nested inside a structure called `Solution`. The function checks whether the given two input strings are anagrams of each other. 6 | 7 | Here's how the function works: 8 | 9 | First, it compares the lengths of the strings `s` and `t`. If they have different lengths, it means they cannot be anagrams, so the function returns `false`. 10 | 11 | The function converts the strings s and t into character arrays using the `chars()` function. Then, it converts these character arrays into vectors of type `Vec`. These vectors will be used to compare and sort the characters. 12 | 13 | The function sorts the vectors `vec_s` and `vec_t`, ensuring that the characters are in the correct order for comparison. 14 | 15 | After sorting, it compares the vectors `vec_s` and `vec_t`. If the vectors are equal, it means the input strings are anagrams of each other, and the function returns `true`. 16 | 17 | If the vectors are not equal, it means the input strings are not anagrams, and the function returns `false`. 18 | 19 | ## Code 20 | 21 | ``` Rust 22 | impl Solution { 23 | pub fn is_anagram(s: String, t: String) -> bool { 24 | 25 | if s.len() != t.len() { 26 | return false; 27 | } 28 | 29 | let mut vec_s = s.chars().collect::>(); 30 | 31 | let mut vec_t = t.chars().collect::>(); 32 | 33 | vec_s.sort(); 34 | vec_t.sort(); 35 | 36 | if vec_s == vec_t { 37 | return true; 38 | } 39 | 40 | return false; 41 | } 42 | } 43 | ``` -------------------------------------------------------------------------------- /Rust/0347-top-k-frequent-elements/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Counts and Sort to solve the 🧑🏻‍💻 Top K Frequent Elements Problem on 🦀 RUST language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | 5 | You defined a helper function called `remove_duplicates`. This function removes duplicate numbers from the given vector and returns a sorted vector. It achieves this by first converting the input vector into a `HashSet`, which automatically filters out duplicates. Then, it converts the `HashSet` back into a `Vec` and sorts it to maintain the order of the numbers. 6 | 7 | You also defined another helper function called `sort_hashmap_by_value`. This function sorts a given `HashMap` by its values and returns a sorted vector of key-value pairs. It converts the `HashMap` into a `Vec` of `(i32, i32)` tuples and uses the `sort_by` function to sort the tuples based on their values. 8 | 9 | The `top_k_frequent` function is the main solution function. It calculates the frequencies of numbers in the given `nums` vector and returns the first `k` numbers with the highest frequency. 10 | 11 | Firstly, it creates an empty `HashMap` called `map` and calculates the frequencies of numbers in the `nums` vector by inserting them into the `map` with their corresponding counts. 12 | 13 | Then, it uses the `remove_duplicates` function to remove duplicates from the `nums` vector and obtain a sorted vector called `vec`. 14 | 15 | Next, it uses the `sort_hashmap_by_value` function to sort the `map` by its values and obtains a sorted vector called `vec3`. 16 | 17 | Finally, it extracts the numbers with the highest frequencies from the `vec3` vector, up to the `k` specified, and adds them to the `vec2` vector. 18 | 19 | The function returns the `vec2` vector as the result. 20 | 21 | ## 🔐 Code 22 | 23 | ``` RUST 24 | use std::collections::{HashMap, HashSet}; 25 | 26 | impl Solution { 27 | 28 | pub fn top_k_frequent(nums: Vec, k: i32) -> Vec { 29 | 30 | fn remove_duplicates(nums: Vec) -> Vec { 31 | let set: HashSet = nums.into_iter().collect(); 32 | let mut result: Vec = set.into_iter().collect(); 33 | result.sort(); 34 | result 35 | } 36 | 37 | fn sort_hashmap_by_value(map: HashMap) -> Vec<(i32, i32)> { 38 | let mut vec: Vec<(i32, i32)> = map.into_iter().collect(); 39 | vec.sort_by(|(_, value1), (_, value2)| value1.cmp(value2)); 40 | vec 41 | } 42 | 43 | let mut map: HashMap = HashMap::new(); 44 | 45 | let vec = remove_duplicates(nums.clone()); 46 | 47 | let mut vec2: Vec = Vec::new(); 48 | 49 | for i in vec { 50 | let mut count = 0; 51 | for j in nums.clone() { 52 | if i == j { 53 | count += 1 54 | } 55 | } 56 | map.insert(i, count); 57 | } 58 | 59 | let vec3 = sort_hashmap_by_value(map); 60 | let mut k2 = k; 61 | 62 | let mut l = vec3.len() - 1; 63 | loop { 64 | if k2 == 0 { 65 | break; 66 | } 67 | vec2.push(vec3[l].0); 68 | l -= 1; 69 | k2 -= 1; 70 | } 71 | 72 | return vec2; 73 | } 74 | 75 | } 76 | ``` 77 | 78 | -------------------------------------------------------------------------------- /Rust/0347-top-k-frequent-elements/question.md: -------------------------------------------------------------------------------- 1 | # [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. 6 | 7 | **Example 1:** 8 | 9 | 10 | >**Input:** nums = \[1,1,1,2,2,3\], k = 2
11 | **Output:** \[1,2\]
12 | 13 | **Example 2:** 14 | 15 | 16 | >**Input:** nums = \[1\], k = 1
17 | **Output:** \[1\]
18 | 19 | **Constraints:** 20 | 21 | - $1 <= nums.length <= 10^5$ 22 | - $-10^4 <= nums[i] <= 10^4$ 23 | - k is in the range [1, the number of unique elements in the array]. 24 | - It is guaranteed that the answer is unique. 25 | 26 | **Follow-up:** 27 | 28 | Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size. 29 | 30 | ## 🔐 Solutions 31 | 32 | 33 | | ID | METHOD | 34 | | :-- | :--------------------: | 35 | | 1 | [Count And Sort](1-answer.md) | 36 | -------------------------------------------------------------------------------- /Rust/0704-binary-search/1-answer.md: -------------------------------------------------------------------------------- 1 | # [✅ Counts the Frequencies to solve the 🧑🏻‍💻 Binary Search Problem on 🦀 Rust language]() 2 | 3 | ## 🧑🏻‍💻 Approach 4 | The function `search` takes in a vector of integers (`nums`) and a target integer (`target`). 5 | A copy of the `nums` vector is created and stored in `nums2` to avoid modifying the original vector. 6 | The `nums2` vector is sorted in ascending order using the `sort()` function. 7 | Pointers `low` and `high` are initialized to keep track of the search range in the sorted vector. 8 | The binary search algorithm is performed using a while loop, which continues until `low` is greater than `high`. 9 | Inside the loop, the middle index `mid` is calculated as the average of `low` and `high`. 10 | The element at the middle index (`nums2[mid]`) is compared to the target. 11 | If they are equal, it means the target has been found, and the index `mid` is returned as the result. 12 | If the element at the middle index is less than the target, it means the target is in the right half of the remaining range. Therefore, the `low` pointer is moved to `mid + 1`. 13 | If the element at the middle index is greater than the target, it means the target is in the left half of the remaining range. Therefore, the `high` pointer is moved to `mid - 1`. 14 | If the target is not found after the loop finishes, `-1` is returned as the result. 15 | 16 | ## 🔐 Code 17 | 18 | ``` rust 19 | impl Solution { 20 | pub fn search(nums: Vec, target: i32) -> i32 { 21 | let mut nums2 = nums.clone(); 22 | nums2.sort(); 23 | 24 | let mut low = 0; 25 | let mut high = nums2.len() as i32 - 1; 26 | 27 | while low <= high{ 28 | let mid= (low+(high - low)/2) as usize; 29 | if nums2[mid] == target{ 30 | return mid as i32; 31 | } 32 | else if nums2[mid]< target { 33 | low = mid as i32 +1; 34 | } 35 | else { 36 | high = mid as i32 -1 37 | } 38 | } 39 | -1 40 | } 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /Rust/0704-binary-search/question.md: -------------------------------------------------------------------------------- 1 | # [Binary Search](https://leetcode.com/problems/binary-search/) 2 | 3 | ## 🚨 Problem 4 | 5 | Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`. 6 | 7 | You must write an algorithm with `O(log n)` runtime complexity. 8 | 9 | **Example 1:** 10 | 11 | 12 | >**Input:** nums = \[-1,0,3,5,9,12\], target = 9
13 | **Output:** 4
14 | **Explanation:** 9 exists in nums and its index is 4 15 | 16 | **Example 2:** 17 | 18 | 19 | >**Input:** nums = \[-1,0,3,5,9,12\], target = 2
20 | **Output:** -1
21 | **Explanation:** 2 does not exist in nums so return -1 22 | 23 | **Constraints:** 24 | 25 | - $1 <= nums.length <= 10^4$ 26 | - $-10^4 < nums[i], target < 10^4$ 27 | - All the integers in `nums` are **unique**. 28 | - `nums` is sorted in ascending order. 29 | 30 | ## 🔐 Solutions 31 | 32 | 33 | | ID | METHOD | 34 | | :-- | :--------------------------: | 35 | | 1 | [Binary Search](1-answer.md) | 36 | -------------------------------------------------------------------------------- /Rust/README.md: -------------------------------------------------------------------------------- 1 | # Awesome Leetcode Algorithms Solututions With Rust 2 | 3 | --- 4 | 5 | | ID | Leetcode ID | 👀 Question Name | 📦 Category | 🔥 Difficulty | 🏢 Company | 6 | | --- | :---------- | :---------------------------------------------------------------------------------: | ---------------- | -------------- | ----------- | 7 | | 1 | 0001 | [Two Sum](0001-two-sum/question.md) | Arrays & Hashing | Easy | Microsoft | 8 | | 2 | 0217 | [Contains Duplicate](0217-contains-duplicate/question.md) | Arrays & Hashing | Easy | Uber | 9 | | 3 | 0242 | [Valid Anagram](0242-valid-anagram/question.md) | Arrays & Hashing | Easy | Facebook | 10 | | 4 | 0049 | [Group Anagram](0049-group-anagram/question.md) | Arrays & Hashing | Medium | Amazon | 11 | | 5 | 0347 | [Top K Frequent Elements](0347-top-k-frequent-elements/question.md) | Arrays & Hashing | Medium | Amazon | 12 | | 6 | 0238 | [Product Of Array Except Self](0238-product-of-array-except-self/question.md) | Arrays & Hashing | Medium | Amazon | 13 | | 7 | 0020 | [Valid Parentheses](0020-valid-parentheses/question.md) | Stack | Easy | Facebook | 14 | | 8 | 0125 | [Valid Palindrome](0125-valid-palindrome/question.md) | Two Pointers | Easy | Spotify | 15 | | 9 | 0155 | [Min Stack](0155-min-stack/question.md) | Stack | Medium | Amazon | 16 | | 10 | 0167 | [Two Sum II Input Array Is Sorted](0167-two-sum-2/question.md) | Two Pointers | Medium | Amazon | 17 | | 11 | 0121 | [Best Time to Buy and Sell Stock](0121-best-time-to-buy-and-sell-stock/question.md) | Sliding Window | Easy | | 18 | | 12 | 0206 | [Reverse Linked List](0206-reverse-linked-list/question.md) | Linked List | Easy | 19 | | 13 | 0704 | [Binary Search](0704-binary-search/question.md) | Binary Search | Easy | 20 | 21 |
22 |

Awesome Leetcode Algorithms Solututions With Rust

23 | 24 | 25 | Twitter Follow 26 | 27 | 28 | Author: 29 | Ömer Aydın
30 | May, 2023 31 |
32 |
33 | 34 | ## Introduction 35 | 36 | Welcome to the solutions of leetcode algorithms with Rust. 37 | 38 | ## How to Use It? 39 | 40 | I suggest cloning the repository locally to work with it, but you can easily look at any solution you want without cloning it. Simply press `Ctrl + F` and type the name of the question or its ID. Each folder includes an .md file that you can click on to go to the Leetcode website. There are two parts of questions: 41 | 42 | 1. Problem:
This part includes the definition of the problem, example cases, input and output examples, constraints, and follow-up information. 43 | 2. Solution:
This part includes a table to navigate to the solutions. 44 | 45 | ## Solutions 46 | 47 | Each .md file for a solution includes: 48 | 49 | - Header (that navigates to the online explanation of the solution) 50 | - Approach (describing the approach to solving the problem) 51 | - Complexity (determining the time and space complexity of the solution) 52 | - Code (the actual solution to the problem) 53 | --------------------------------------------------------------------------------