├── C++ ├── Easy │ ├── 1. Two Sum.cpp │ ├── 1217. Minimum Cost to Move Chips to The Same Position.cpp │ ├── 1252. Cells with Odd Values in a Matrix.cpp │ ├── 1281. Subtract the Product and Sum of Digits of an Integer.cpp │ ├── 1295. Find Numbers with Even Number of Digits.cpp │ ├── 1304. Find N Unique Integers Sum up to Zero.cpp │ ├── 1346. Check If N and Its Double Exist.cpp │ ├── 1351. Count Negative Numbers in a Sorted Matrix.cpp │ ├── 1365. How Many Numbers Are Smaller Than the Current Number.cpp │ ├── 1380. Lucky Numbers in a Matrix.cpp │ ├── 1389. Create Target Array in the Given Order.cpp │ ├── 141. Linked List Cycle.cpp │ ├── 1431. Kids With the Greatest Number of Candies.cpp │ ├── 1470. Shuffle the Array.cpp │ ├── 1480. Running Sum of 1d Array.cpp │ ├── 1512. Number of Good Pairs.cpp │ ├── 1572. Matrix Diagonal Sum.cpp │ ├── 160. Intersection of Two Linked Lists.cpp │ ├── 1672. Richest Customer Wealth.cpp │ ├── 1773. Count Items Matching a Rule.cpp │ ├── 1832. Check if the Sentence Is Pangram.cpp │ ├── 1854. Maximum Population Year.cpp │ ├── 1886. Determine Whether Matrix Can Be Obtained By Rotation.cpp │ ├── 1920. Build Array from Permutation.cpp │ ├── 1929. Concatenation of Array.cpp │ ├── 202. Happy Number.cpp │ ├── 203. Remove Linked List Elements.cpp │ ├── 206. Reverse Linked List.cpp │ ├── 21. Merge Two Sorted Lists.cpp │ ├── 234. Palindrome Linked List.cpp │ ├── 2437. Number of Valid Clock Times.cpp │ ├── 26. Remove Duplicates from Sorted Array.cpp │ ├── 278. First Bad Version.cpp │ ├── 349. Intersection of Two Arrays.cpp │ ├── 35. Search Insert Position.cpp │ ├── 350. Intersection of Two Arrays II.cpp │ ├── 374. Guess Number Higher or Lower.cpp │ ├── 441. Arranging Coins.cpp │ ├── 53. Maximum Subarray.cpp │ ├── 566. Reshape the Matrix.cpp │ ├── 66. Plus One.cpp │ ├── 69. Sqrt(x).cpp │ ├── 704. Binary Search.cpp │ ├── 744. Find Smallest Letter Greater Than Target.cpp │ ├── 83. Remove Duplicates from Sorted List.cpp │ ├── 832. Flipping an Image.cpp │ ├── 867. Transpose Matrix.cpp │ ├── 876. Middle of the Linked List.cpp │ ├── 88. Merge Sorted Array.cpp │ ├── 9. Palindrome Number.cpp │ ├── 989. Add to Array-Form of Integer.cpp │ └── Readme.md ├── Hard │ ├── 1095. Find in Mountain Array.cpp │ ├── 1250. Check If It Is a Good Array.cpp │ ├── 25. Reverse Nodes in k-Group.cpp │ ├── 4. Median of Two Sorted Arrays.cpp │ ├── 41. First Missing Positive.cpp │ └── Readme.md └── Medium │ ├── 142. Linked List Cycle II.cpp │ ├── 143. Reorder List.cpp │ ├── 148. Sort List.cpp │ ├── 153. Find Minimum in Rotated Sorted Array.cpp │ ├── 167. Two Sum II - Input Array Is Sorted.cpp │ ├── 189. Rotate Array.cpp │ ├── 198. House Robber.cpp │ ├── 238. Product of Array Except Self.cpp │ ├── 3. Longest Substring Without Repeating Characters.cpp │ ├── 33. Search in Rotated Sorted Array.cpp │ ├── 34. Find First and Last Position of Element in Sorted Array.cpp │ ├── 367. Valid Perfect Square.cpp │ ├── 54. Spiral Matrix.cpp │ ├── 540. Single Element in a Sorted Array.cpp │ ├── 55. Jump Game.cpp │ ├── 59. Spiral Matrix II.cpp │ ├── 707. Design Linked List.cpp │ ├── 73. Set Matrix Zeroes.cpp │ ├── 75. Sort Colors.cpp │ ├── 81. Search in Rotated Sorted Array II.cpp │ ├── 852. Peak Index in a Mountain Array.cpp │ ├── 875. Koko Eating Bananas.cpp │ ├── 885. Spiral Matrix III.cpp │ ├── 92. Reverse Linked List II.cpp │ └── Readme.md ├── C ├── Easy │ └── Readme.md ├── Hard │ └── Readme.md └── Medium │ └── Readme.md ├── Contributing.md ├── Java ├── Easy │ └── Readme.md ├── Hard │ └── Readme.md └── Medium │ └── Readme.md ├── LICENSE ├── Learn.md ├── Python ├── Easy │ ├── 1. Two Sum.py │ ├── 13. Roman to Integer.py │ ├── 1672. Richest Customer Wealth.py │ ├── 2259. Remove Digit From Number to Maximize Result.py │ ├── 26. Remove Duplicates from Sorted Array.py │ ├── 412. Fizz Buzz.py │ ├── 9. Palindrome Number.py │ └── Readme.md ├── Hard │ └── Readme.md └── Medium │ └── Readme.md └── README.md /C++/Easy/1. Two Sum.cpp: -------------------------------------------------------------------------------- 1 | //Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 2 | //You may assume that each input would have exactly one solution, and you may not use the same element twice. 3 | //You can return the answer in any order. 4 | // 5 | //Example 1: 6 | // 7 | //Input: nums = [2,7,11,15], target = 9 8 | //Output: [0,1] 9 | //Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 10 | // 11 | //Example 2: 12 | // 13 | //Input: nums = [3,2,4], target = 6 14 | //Output: [1,2] 15 | // 16 | //Example 3: 17 | // 18 | //Input: nums = [3,3], target = 6 19 | //Output: [0,1] 20 | // 21 | //Constraints: 22 | // 23 | //2 <= nums.length <= 104 24 | //-109 <= nums[i] <= 109 25 | //-109 <= target <= 109 26 | //Only one valid answer exists. 27 | 28 | class Solution { 29 | public: 30 | vector twoSum(vector& nums, int target) { 31 | for(int i = 0; i& chips) { 36 | int even=0,odd=0; 37 | for(int i=0;iodd) 44 | return odd; 45 | return even; 46 | 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /C++/Easy/1252. Cells with Odd Values in a Matrix.cpp: -------------------------------------------------------------------------------- 1 | //There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. 2 | // 3 | //For each location indices[i], do both of the following: 4 | // 5 | //Increment all the cells on row ri. 6 | //Increment all the cells on column ci. 7 | //Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. 8 | // 9 | // 10 | //Example 1: 11 | // 12 | //Input: m = 2, n = 3, indices = [[0,1],[1,1]] 13 | //Output: 6 14 | //Explanation: Initial matrix = [[0,0,0],[0,0,0]]. 15 | //After applying first increment it becomes [[1,2,1],[0,1,0]]. 16 | //The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers. 17 | //Example 2: 18 | // 19 | // 20 | //Input: m = 2, n = 2, indices = [[1,1],[0,0]] 21 | //Output: 0 22 | //Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix. 23 | // 24 | // 25 | //Constraints: 26 | // 27 | //1 <= m, n <= 50 28 | //1 <= indices.length <= 100 29 | //0 <= ri < m 30 | //0 <= ci < n 31 | 32 | class Solution { 33 | public: 34 | int oddCells(int m, int n, vector>& indices) { 35 | vector> vec (m, vector (n)); 36 | 37 | for(int i = 0; i < indices.size(); i++){ 38 | //row 39 | for(int j = 0; j < n; j++) 40 | vec[indices[i][0]][j]++; 41 | //column 42 | for(int j = 0; j < m; j++) 43 | vec[j][indices[i][1]]++; 44 | } 45 | 46 | int count_odd = 0; 47 | for(int i = 0; i < m; i++){ 48 | for(int j = 0; j < n; j++){ 49 | if(vec[i][j]%2 != 0){ 50 | count_odd++; 51 | } 52 | } 53 | } 54 | 55 | return count_odd; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /C++/Easy/1281. Subtract the Product and Sum of Digits of an Integer.cpp: -------------------------------------------------------------------------------- 1 | //Given an integer number n, return the difference between the product of its digits and the sum of its digits. 2 | // 3 | // 4 | //Example 1: 5 | // 6 | //Input: n = 234 7 | //Output: 15 8 | //Explanation: 9 | //Product of digits = 2 * 3 * 4 = 24 10 | //Sum of digits = 2 + 3 + 4 = 9 11 | //Result = 24 - 9 = 15 12 | // 13 | //Example 2: 14 | // 15 | //Input: n = 4421 16 | //Output: 21 17 | //Explanation: 18 | //Product of digits = 4 * 4 * 2 * 1 = 32 19 | //Sum of digits = 4 + 4 + 2 + 1 = 11 20 | //Result = 32 - 11 = 21 21 | // 22 | //Constraints: 23 | //1 <= n <= 10^5 24 | 25 | class Solution { 26 | public: 27 | int subtractProductAndSum(int n) { 28 | int sum = 0; 29 | int product = 1; 30 | int temp; 31 | 32 | while(n != 0){ 33 | temp = n%10; 34 | sum += temp; 35 | product *= temp; 36 | n /= 10; 37 | } 38 | 39 | return product - sum; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /C++/Easy/1295. Find Numbers with Even Number of Digits.cpp: -------------------------------------------------------------------------------- 1 | //Given an array nums of integers, return how many of them contain an even number of digits. 2 | // 3 | //Example 1: 4 | // 5 | //Input: nums = [12,345,2,6,7896] 6 | //Output: 2 7 | //Explanation: 8 | //12 contains 2 digits (even number of digits). 9 | //345 contains 3 digits (odd number of digits). 10 | //2 contains 1 digit (odd number of digits). 11 | //6 contains 1 digit (odd number of digits). 12 | //7896 contains 4 digits (even number of digits). 13 | //Therefore only 12 and 7896 contain an even number of digits. 14 | //Example 2: 15 | // 16 | //Input: nums = [555,901,482,1771] 17 | //Output: 1 18 | //Explanation: 19 | //Only 1771 contains an even number of digits. 20 | // 21 | //Constraints: 22 | // 23 | //1 <= nums.length <= 500 24 | //1 <= nums[i] <= 105 25 | 26 | 27 | class Solution { 28 | public: 29 | int countDigit(long long n) 30 | { 31 | if(n == 0) 32 | return 1; 33 | int count = 0; 34 | while (n != 0) 35 | { 36 | n = n / 10; 37 | ++count; 38 | } 39 | return count; 40 | } 41 | int findNumbers(vector& nums) { 42 | int even = 0; 43 | for(int i = 0; i sumZero(int n) { 26 | vector ans; 27 | int i = n/2; 28 | if(n%2 != 0){ 29 | while(n>0){ 30 | ans.push_back(i); 31 | i--; 32 | n--; 33 | } 34 | } 35 | else{ 36 | while(n>0){ 37 | if(i == 0){ 38 | i--; 39 | } 40 | else{ 41 | ans.push_back(i); 42 | i--; 43 | n--; 44 | } 45 | } 46 | } 47 | return ans; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /C++/Easy/1346. Check If N and Its Double Exist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array arr of integers, check if there exist two indices i and j such that : 3 | 4 | i != j 5 | 0 <= i, j < arr.length 6 | arr[i] == 2 * arr[j] 7 | 8 | 9 | Example 1: 10 | 11 | Input: arr = [10,2,5,3] 12 | Output: true 13 | Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j] 14 | Example 2: 15 | 16 | Input: arr = [3,1,7,11] 17 | Output: false 18 | Explanation: There is no i and j that satisfy the conditions. 19 | 20 | 21 | Constraints: 22 | 23 | 2 <= arr.length <= 500 24 | -10^3 <= arr[i] <= 10^3 25 | */ 26 | class Solution { 27 | public: 28 | bool checkIfExist(vector& arr) { 29 | sort(arr.begin(), arr.end()); 30 | int start, end; 31 | for(int i = 0; i<= arr.size()-1; i++){ 32 | int target = arr[i]; 33 | if (target < 0){ 34 | start = 0; 35 | end = i - 1; 36 | } 37 | else{ 38 | start = i + 1; 39 | end = arr.size() - 1; 40 | } 41 | while(start <= end){ 42 | int mid = start + (end - start)/2; 43 | if(target*2 == arr[mid]) return true; 44 | else if(target*2 < arr[mid]) end = mid - 1; 45 | else start = mid + 1; 46 | } 47 | } 48 | return false; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /C++/Easy/1351. Count Negative Numbers in a Sorted Matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 9 | Output: 8 10 | Explanation: There are 8 negatives number in the matrix. 11 | Example 2: 12 | 13 | Input: grid = [[3,2],[1,0]] 14 | Output: 0 15 | 16 | 17 | Constraints: 18 | 19 | m == grid.length 20 | n == grid[i].length 21 | 1 <= m, n <= 100 22 | -100 <= grid[i][j] <= 100 23 | */ 24 | 25 | class Solution { 26 | public: 27 | int countNegatives(vector>& grid) { 28 | int n = grid.size(); 29 | int m = grid[0].size()-1; 30 | int count = 0; 31 | cout<=0){ 36 | continue; 37 | } 38 | //whole col is negative 39 | if(grid[i][0] < 0){ 40 | count += m+1; 41 | continue; 42 | } 43 | 44 | //some part is negative 45 | int l = 0, h = m; 46 | while(l <= h){ 47 | int mid = (h+l)/2; 48 | if(grid[i][mid] >= 0){ 49 | l = mid + 1; 50 | } 51 | else{ 52 | h = mid-1; 53 | } 54 | } 55 | count += m - h; 56 | cout << grid[i][h]<<" "; 57 | } 58 | return count; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /C++/Easy/1365. How Many Numbers Are Smaller Than the Current Number.cpp: -------------------------------------------------------------------------------- 1 | //Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. 2 | //Return the answer in an array. 3 | // 4 | // 5 | //Example 1: 6 | // 7 | //Input: nums = [8,1,2,2,3] 8 | //Output: [4,0,1,1,3] 9 | //Explanation: 10 | //For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 11 | //For nums[1]=1 does not exist any smaller number than it. 12 | //For nums[2]=2 there exist one smaller number than it (1). 13 | //For nums[3]=2 there exist one smaller number than it (1). 14 | //For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). 15 | //Example 2: 16 | // 17 | //Input: nums = [6,5,4,8] 18 | //Output: [2,1,0,3] 19 | //Example 3: 20 | // 21 | //Input: nums = [7,7,7,7] 22 | //Output: [0,0,0,0] 23 | // 24 | // 25 | //Constraints: 26 | // 27 | //2 <= nums.length <= 500 28 | //0 <= nums[i] <= 100 29 | 30 | class Solution { 31 | public: 32 | vector smallerNumbersThanCurrent(vector& nums) { 33 | vector temp = nums; 34 | map mp; 35 | 36 | sort(temp.begin(), temp.end()); 37 | for(int i=nums.size()-1;i>=0;i--) 38 | mp[temp[i]]=i; 39 | 40 | for(int i = 0; i luckyNumbers (vector>& matrix) { 33 | int m = matrix.size(); 34 | int n = matrix[0].size(); 35 | 36 | // only one number in matrix can be lucky number that will be maximum among all minimum row numbers && minimum among all maximum col numbers 37 | 38 | //maximum number among all minimum row numbers 39 | int maxMin = INT_MIN; 40 | for (int i = 0; i < m; i++) { 41 | int min = INT_MAX; 42 | for (int j = 0; j < n; j++){ 43 | min = std::min(min, matrix[i][j]); 44 | } 45 | maxMin = std::max(maxMin, min); 46 | } 47 | 48 | //minimum number among all maximum col numbers 49 | int minMax = INT_MAX; 50 | for (int j = 0; j < n; j++) { 51 | int max = INT_MIN; 52 | for (int i = 0; i < m; i++){ 53 | max = std::max(max, matrix[i][j]); 54 | } 55 | minMax = std::min(minMax, max); 56 | } 57 | 58 | //if not equal 59 | if (maxMin != minMax) 60 | { 61 | return vector { }; 62 | } 63 | //else 64 | return vector { maxMin }; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /C++/Easy/1389. Create Target Array in the Given Order.cpp: -------------------------------------------------------------------------------- 1 | //Given two arrays of integers nums and index. Your task is to create target array under the following rules: 2 | // 3 | //Initially target array is empty. 4 | //From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. 5 | //Repeat the previous step until there are no elements to read in nums and index. 6 | //Return the target array. 7 | // 8 | //It is guaranteed that the insertion operations will be valid. 9 | // 10 | // 11 | // 12 | //Example 1: 13 | // 14 | //Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] 15 | //Output: [0,4,1,3,2] 16 | //Explanation: 17 | //nums index target 18 | //0 0 [0] 19 | //1 1 [0,1] 20 | //2 2 [0,1,2] 21 | //3 2 [0,1,3,2] 22 | //4 1 [0,4,1,3,2] 23 | //Example 2: 24 | // 25 | //Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] 26 | //Output: [0,1,2,3,4] 27 | //Explanation: 28 | //nums index target 29 | //1 0 [1] 30 | //2 1 [1,2] 31 | //3 2 [1,2,3] 32 | //4 3 [1,2,3,4] 33 | //0 0 [0,1,2,3,4] 34 | //Example 3: 35 | // 36 | //Input: nums = [1], index = [0] 37 | //Output: [1] 38 | // 39 | // 40 | //Constraints: 41 | // 42 | //1 <= nums.length, index.length <= 100 43 | //nums.length == index.length 44 | //0 <= nums[i] <= 100 45 | //0 <= index[i] <= i 46 | 47 | class Solution { 48 | public: 49 | vector createTargetArray(vector& nums, vector& index) { 50 | vector target; 51 | for(int i = 0; ival == 1000000){ 53 | return true; 54 | } 55 | slow->val = 1000000; 56 | slow = slow->next; 57 | } 58 | return false; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /C++/Easy/1431. Kids With the Greatest Number of Candies.cpp: -------------------------------------------------------------------------------- 1 | //There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have. 2 | //Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise. 3 | //Note that multiple kids can have the greatest number of candies. 4 | // 5 | // 6 | //Example 1: 7 | // 8 | //Input: candies = [2,3,5,1,3], extraCandies = 3 9 | //Output: [true,true,true,false,true] 10 | //Explanation: If you give all extraCandies to: 11 | //- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. 12 | //- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. 13 | //- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. 14 | //- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. 15 | //- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. 16 | //Example 2: 17 | // 18 | //Input: candies = [4,2,1,1,2], extraCandies = 1 19 | //Output: [true,false,false,false,false] 20 | //Explanation: There is only 1 extra candy. 21 | //Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. 22 | //Example 3: 23 | // 24 | //Input: candies = [12,1,12], extraCandies = 10 25 | //Output: [true,false,true] 26 | // 27 | //Constraints: 28 | // 29 | //n == candies.length 30 | //2 <= n <= 100 31 | //1 <= candies[i] <= 100 32 | //1 <= extraCandies <= 50 33 | 34 | class Solution { 35 | public: 36 | vector kidsWithCandies(vector& candies, int extraCandies) { 37 | vector out (candies.size(), false); 38 | int max = *max_element(candies.begin(), candies.end()); 39 | 40 | for(int i=0; i < candies.size(); i++){ 41 | if(candies[i]+extraCandies >= max) 42 | out[i] = true; 43 | } 44 | 45 | return out; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /C++/Easy/1470. Shuffle the Array.cpp: -------------------------------------------------------------------------------- 1 | //Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. 2 | // 3 | //Example 1: 4 | // 5 | //Input: nums = [2,5,1,3,4,7], n = 3 6 | //Output: [2,3,5,4,1,7] 7 | //Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. 8 | //Example 2: 9 | // 10 | //Input: nums = [1,2,3,4,4,3,2,1], n = 4 11 | //Output: [1,4,2,3,3,2,4,1] 12 | //Example 3: 13 | // 14 | //Input: nums = [1,1,2,2], n = 2 15 | //Output: [1,2,1,2] 16 | // 17 | // 18 | //Constraints: 19 | // 20 | //1 <= n <= 500 21 | //nums.length == 2n 22 | //1 <= nums[i] <= 10^3 23 | 24 | class Solution { 25 | public: 26 | vector shuffle(vector& nums, int n) { 27 | for(int i = 1; i runningSum(vector& nums) { 21 | for(int i = 1; i < nums.size(); i++){ 22 | nums[i] += nums[i-1]; 23 | } 24 | return nums; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/Easy/1512. Number of Good Pairs.cpp: -------------------------------------------------------------------------------- 1 | //Given an array of integers nums, return the number of good pairs. 2 | //A pair (i, j) is called good if nums[i] == nums[j] and i < j. 3 | // 4 | // 5 | //Example 1: 6 | // 7 | //Input: nums = [1,2,3,1,1,3] 8 | //Output: 4 9 | //Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 10 | //Example 2: 11 | // 12 | //Input: nums = [1,1,1,1] 13 | //Output: 6 14 | //Explanation: Each pair in the array are good. 15 | //Example 3: 16 | // 17 | //Input: nums = [1,2,3] 18 | //Output: 0 19 | // 20 | // 21 | //Constraints: 22 | // 23 | //1 <= nums.length <= 100 24 | //1 <= nums[i] <= 100 25 | 26 | class Solution { 27 | public: 28 | int numIdenticalPairs(vector& nums) { 29 | int ans = 0; 30 | int arr[101] = {0}; 31 | for(int i = 0; i>& mat) { 33 | int sum = 0; 34 | int i = 0; 35 | int j = mat[0].size(); 36 | 37 | for(i = 0; inext; 82 | } 83 | a = a->next; 84 | } 85 | return NULL; 86 | } 87 | }; 88 | -------------------------------------------------------------------------------- /C++/Easy/1672. Richest Customer Wealth.cpp: -------------------------------------------------------------------------------- 1 | //You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i^th customer has in the j^th bank. Return the wealth that the richest customer has. 2 | // 3 | //A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. 4 | // 5 | //Example 1: 6 | // 7 | //Input: accounts = [[1,2,3],[3,2,1]] 8 | //Output: 6 9 | //Explanation: 10 | //1st customer has wealth = 1 + 2 + 3 = 6 11 | //2nd customer has wealth = 3 + 2 + 1 = 6 12 | //Both customers are considered the richest with a wealth of 6 each, so return 6. 13 | //Example 2: 14 | // 15 | //Input: accounts = [[1,5],[7,3],[3,5]] 16 | //Output: 10 17 | //Explanation: 18 | //1st customer has wealth = 6 19 | //2nd customer has wealth = 10 20 | //3rd customer has wealth = 8 21 | //The 2nd customer is the richest with a wealth of 10. 22 | //Example 3: 23 | // 24 | //Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] 25 | //Output: 17 26 | // 27 | // 28 | //Constraints: 29 | // 30 | //m == accounts.length 31 | //n == accounts[i].length 32 | //1 <= m, n <= 50 33 | //1 <= accounts[i][j] <= 100 34 | 35 | 36 | class Solution { 37 | public: 38 | int maximumWealth(vector>& accounts) { 39 | 40 | int sum = INT_MIN; 41 | 42 | for(int i = 0; i>& items, string ruleKey, string ruleValue) { 32 | int ans = 0; 33 | int val; 34 | if(ruleKey == "type"){ 35 | val = 0; 36 | } 37 | else if(ruleKey == "color"){ 38 | val = 1; 39 | } 40 | // ruleKey == "name" 41 | else{ 42 | val = 2; 43 | } 44 | for(int i = 0; i pangram(26, false); 25 | 26 | for(int i = 0; i>& logs) { 28 | int arr[101]={0}; 29 | 30 | for(vector log : logs){ 31 | arr[log[0] - 1950]++; 32 | arr[log[1] - 1950]--; 33 | } 34 | int max = 0, year, cnt = 0; 35 | 36 | for(int i = 0; i < 101; i++){ 37 | cnt += arr[i]; 38 | if(cnt > max){ 39 | max = cnt; 40 | year = i; 41 | } 42 | } 43 | return year + 1950; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/Easy/1886. Determine Whether Matrix Can Be Obtained By Rotation.cpp: -------------------------------------------------------------------------------- 1 | //Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise. 2 | // 3 | // 4 | //Example 1: 5 | // 6 | //Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]] 7 | //Output: true 8 | //Explanation: We can rotate mat 90 degrees clockwise to make mat equal target. 9 | // 10 | //Example 2: 11 | // 12 | //Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]] 13 | //Output: false 14 | //Explanation: It is impossible to make mat equal to target by rotating mat. 15 | // 16 | //Example 3: 17 | // 18 | //Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]] 19 | //Output: true 20 | //Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target. 21 | // 22 | // 23 | //Constraints: 24 | // 25 | //n == mat.length == target.length 26 | //n == mat[i].length == target[i].length 27 | //1 <= n <= 10 28 | //mat[i][j] and target[i][j] are either 0 or 1. 29 | 30 | class Solution { 31 | public: 32 | //rotate 90 degree 33 | void rotate(vector>& mat) 34 | { 35 | int N = mat.size(); 36 | // REVERSE every row 37 | for (int i = 0; i < N; i++) 38 | reverse(mat[i].begin(), mat[i].end()); 39 | 40 | // Performing Transpose 41 | for (int i = 0; i < N; i++) { 42 | for (int j = i; j < N; j++){ 43 | swap(mat[i][j], mat[j][i]); 44 | } 45 | } 46 | } 47 | 48 | bool findRotation(vector>& mat, vector>& target) { 49 | //check and rotate the matrix 50 | for(int i = 0; i <= 3; i++){ 51 | if(mat == target){ 52 | return true; 53 | } 54 | rotate(mat); 55 | } 56 | return false; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /C++/Easy/1920. Build Array from Permutation.cpp: -------------------------------------------------------------------------------- 1 | //Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. 2 | // 3 | //A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). 4 | // 5 | // 6 | // 7 | //Example 1: 8 | // 9 | //Input: nums = [0,2,1,5,3,4] 10 | //Output: [0,1,2,4,5,3] 11 | //Explanation: The array ans is built as follows: 12 | //ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] 13 | // = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] 14 | // = [0,1,2,4,5,3] 15 | //Example 2: 16 | // 17 | //Input: nums = [5,0,1,2,3,4] 18 | //Output: [4,5,0,1,2,3] 19 | //Explanation: The array ans is built as follows: 20 | //ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] 21 | // = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]] 22 | // = [4,5,0,1,2,3] 23 | // 24 | // 25 | //Constraints: 26 | // 27 | //1 <= nums.length <= 1000 28 | //0 <= nums[i] < nums.length 29 | //The elements in nums are distinct. 30 | 31 | 32 | class Solution { 33 | public: 34 | vector buildArray(vector& nums) { 35 | vector ans(nums.size()); 36 | for(int i = 0; i getConcatenation(vector& nums) { 30 | vector ans; 31 | for(auto i = nums.begin(); i!=nums.end(); ++i){ 32 | ans.push_back(*i); 33 | } 34 | for(auto i = nums.begin(); i!=nums.end(); ++i){ 35 | ans.push_back(*i); 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /C++/Easy/202. Happy Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write an algorithm to determine if a number n is happy. 3 | 4 | A happy number is a number defined by the following process: 5 | 6 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 7 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 8 | Those numbers for which this process ends in 1 are happy. 9 | Return true if n is a happy number, and false if not. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: n = 19 16 | Output: true 17 | Explanation: 18 | 12 + 92 = 82 19 | 82 + 22 = 68 20 | 62 + 82 = 100 21 | 12 + 02 + 02 = 1 22 | Example 2: 23 | 24 | Input: n = 2 25 | Output: false 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= n <= 231 - 1 31 | */ 32 | class Solution { 33 | public: 34 | int findSquare(int n){ 35 | int ans = 0; 36 | while(n > 0){ 37 | int rem = n%10; 38 | ans += rem*rem; 39 | n /= 10; 40 | } 41 | return ans; 42 | } 43 | bool isHappy(int n) { 44 | int slow = n; 45 | int fast = n; 46 | do{ 47 | slow = findSquare(slow); 48 | fast = findSquare(findSquare(fast)); 49 | }while(slow != fast); 50 | if(slow == 1){ 51 | return true; 52 | } 53 | return false; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /C++/Easy/203. Remove Linked List Elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: head = [1,2,6,3,4,5,6], val = 6 10 | Output: [1,2,3,4,5] 11 | Example 2: 12 | 13 | Input: head = [], val = 1 14 | Output: [] 15 | Example 3: 16 | 17 | Input: head = [7,7,7,7], val = 7 18 | Output: [] 19 | 20 | 21 | Constraints: 22 | 23 | The number of nodes in the list is in the range [0, 104]. 24 | 1 <= Node.val <= 50 25 | 0 <= val <= 50 26 | */ 27 | 28 | /** 29 | * Definition for singly-linked list. 30 | * struct ListNode { 31 | * int val; 32 | * ListNode *next; 33 | * ListNode() : val(0), next(nullptr) {} 34 | * ListNode(int x) : val(x), next(nullptr) {} 35 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 36 | * }; 37 | */ 38 | class Solution { 39 | public: 40 | ListNode* removeElements(ListNode* head, int val) { 41 | if(head == NULL){ 42 | return NULL; 43 | } 44 | while(head && head->val == val){ 45 | head = head->next; 46 | } 47 | ListNode* curr = head; 48 | ListNode* prev = nullptr; 49 | 50 | while(curr != nullptr){ 51 | if(curr->val == val){ 52 | prev->next = curr->next; 53 | curr = curr->next; 54 | } 55 | else{ 56 | prev = curr; 57 | curr = curr->next; 58 | } 59 | } 60 | 61 | return head; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /C++/Easy/206. Reverse Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a singly linked list, reverse the list, and return the reversed list. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: head = [1,2,3,4,5] 10 | Output: [5,4,3,2,1] 11 | Example 2: 12 | 13 | 14 | Input: head = [1,2] 15 | Output: [2,1] 16 | Example 3: 17 | 18 | Input: head = [] 19 | Output: [] 20 | 21 | 22 | Constraints: 23 | 24 | The number of nodes in the list is the range [0, 5000]. 25 | -5000 <= Node.val <= 5000 26 | 27 | */ 28 | 29 | /** 30 | * Definition for singly-linked list. 31 | * struct ListNode { 32 | * int val; 33 | * ListNode *next; 34 | * ListNode() : val(0), next(nullptr) {} 35 | * ListNode(int x) : val(x), next(nullptr) {} 36 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 37 | * }; 38 | */ 39 | class Solution { 40 | public: 41 | ListNode* reverseList(ListNode* head) { 42 | //base condition 43 | if(head == NULL || head->next == NULL){ 44 | return head; 45 | } 46 | ListNode* res = reverseList(head->next); 47 | head->next->next = head; 48 | head->next = NULL; 49 | return res; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /C++/Easy/21. Merge Two Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given the heads of two sorted linked lists list1 and list2. 3 | 4 | Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. 5 | 6 | Return the head of the merged linked list. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | 13 | Input: list1 = [1,2,4], list2 = [1,3,4] 14 | Output: [1,1,2,3,4,4] 15 | Example 2: 16 | 17 | Input: list1 = [], list2 = [] 18 | Output: [] 19 | Example 3: 20 | 21 | Input: list1 = [], list2 = [0] 22 | Output: [0] 23 | 24 | 25 | Constraints: 26 | 27 | The number of nodes in both lists is in the range [0, 50]. 28 | -100 <= Node.val <= 100 29 | Both list1 and list2 are sorted in non-decreasing order. 30 | */ 31 | 32 | /** 33 | * Definition for singly-linked list. 34 | * struct ListNode { 35 | * int val; 36 | * ListNode *next; 37 | * ListNode() : val(0), next(nullptr) {} 38 | * ListNode(int x) : val(x), next(nullptr) {} 39 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 40 | * }; 41 | */ 42 | class Solution { 43 | public: 44 | void insertEnd(ListNode* head, int n){ 45 | ListNode* newNode = new ListNode(n); 46 | if(head == NULL){ 47 | head = newNode; 48 | } 49 | else{ 50 | ListNode* l = head; 51 | while(l->next != NULL){ 52 | l = l->next; 53 | } 54 | l->next = newNode; 55 | } 56 | return; 57 | } 58 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 59 | if(l1 == NULL){ 60 | return l2; 61 | } 62 | if(l2 == NULL){ 63 | return l1; 64 | } 65 | ListNode* newlist = new ListNode(); 66 | while(l1 != NULL && l2 != NULL){ 67 | if(l1 != NULL || l2 != NULL){ 68 | if(l1->val <= l2->val){ 69 | insertEnd(newlist, l1->val); 70 | l1 = l1->next; 71 | } 72 | else{ 73 | insertEnd(newlist, l2->val); 74 | l2 = l2->next; 75 | } 76 | } 77 | else if(l1 == NULL){ 78 | newlist->next = l2; 79 | } 80 | else{ 81 | newlist->next = l1; 82 | } 83 | } 84 | if(l1 == NULL){ 85 | while(l2!= NULL){ 86 | insertEnd(newlist, l2->val); 87 | l2 = l2->next; 88 | } 89 | } 90 | 91 | else{ 92 | while(l1!= NULL){ 93 | insertEnd(newlist, l1->val); 94 | l1 = l1->next; 95 | } 96 | } 97 | return newlist->next; 98 | } 99 | }; 100 | -------------------------------------------------------------------------------- /C++/Easy/234. Palindrome Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a singly linked list, return true if it is a 3 | palindrome 4 | or false otherwise. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | Input: head = [1,2,2,1] 12 | Output: true 13 | Example 2: 14 | 15 | 16 | Input: head = [1,2] 17 | Output: false 18 | 19 | 20 | Constraints: 21 | 22 | The number of nodes in the list is in the range [1, 105]. 23 | 0 <= Node.val <= 9 24 | 25 | */ 26 | 27 | /** 28 | * Definition for singly-linked list. 29 | * struct ListNode { 30 | * int val; 31 | * ListNode *next; 32 | * ListNode() : val(0), next(nullptr) {} 33 | * ListNode(int x) : val(x), next(nullptr) {} 34 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 35 | * }; 36 | */ 37 | class Solution { 38 | public: 39 | void Print(ListNode* head) { 40 | ListNode* cur = head; 41 | while(cur!=NULL){ 42 | cout<val<<" "; 43 | cur = cur->next; 44 | } 45 | cout<next; 53 | curr->next = prev; 54 | 55 | prev = curr; 56 | curr = nxt; 57 | } 58 | return prev; 59 | } 60 | bool isPalindrome(ListNode* head) { 61 | if(head == NULL){ 62 | return false; 63 | } 64 | if(head->next == NULL){ 65 | return true; 66 | } 67 | ListNode* slow = head; 68 | ListNode* fast = head; 69 | while(fast && fast->next){ 70 | slow = slow->next; 71 | fast = fast->next->next; 72 | } 73 | 74 | ListNode* curr = slow; 75 | ListNode* prev = reverse(slow); 76 | 77 | Print(prev); 78 | Print(head); 79 | // check first half and last half is equal 80 | while(prev && head){ 81 | if(prev->val !=head->val) return false; 82 | prev=prev->next; 83 | head=head->next; 84 | } 85 | return true; 86 | } 87 | }; 88 | -------------------------------------------------------------------------------- /C++/Easy/2437. Number of Valid Clock Times.cpp: -------------------------------------------------------------------------------- 1 | //You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59". 2 | //In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9. 3 | //Return an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9. 4 | // 5 | // 6 | //Example 1: 7 | // 8 | //Input: time = "?5:00" 9 | //Output: 2 10 | //Explanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices. 11 | // 12 | //Example 2: 13 | // 14 | //Input: time = "0?:0?" 15 | //Output: 100 16 | //Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices. 17 | // 18 | //Example 3: 19 | // 20 | //Input: time = "??:??" 21 | //Output: 1440 22 | //Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices. 23 | // 24 | // 25 | //Constraints: 26 | // 27 | //time is a valid string of length 5 in the format "hh:mm". 28 | //"00" <= hh <= "23" 29 | //"00" <= mm <= "59" 30 | //Some of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9. 31 | 32 | class Solution { 33 | public: 34 | int countTime(string time) { 35 | int hour = 1; 36 | int min = 1; 37 | 38 | // for hour 39 | // 00 --> 23 40 | if(time[0] == '?' && time[1] == '?') 41 | { 42 | hour = 24; 43 | } 44 | 45 | else if(time[0] == '?') 46 | { 47 | if(time[1] <= '3') 48 | { 49 | hour = 3; 50 | } 51 | else 52 | { 53 | hour = 2; 54 | } 55 | } 56 | else if(time[1] == '?') 57 | { 58 | if(time[0] == '2') 59 | { 60 | hour = 4; 61 | } 62 | else 63 | { 64 | hour = 10; 65 | } 66 | } 67 | 68 | // for min 69 | if(time[3] == '?') 70 | { 71 | min = min*6; 72 | } 73 | 74 | if(time[4] == '?') 75 | { 76 | min = min*10; 77 | } 78 | 79 | return hour * min; 80 | } 81 | }; 82 | -------------------------------------------------------------------------------- /C++/Easy/26. Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | //Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. 2 | //Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. 3 | //Return k after placing the final result in the first k slots of nums. 4 | //Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. 5 | // 6 | //Custom Judge: 7 | // 8 | //The judge will test your solution with the following code: 9 | // 10 | //int[] nums = [...]; // Input array 11 | //int[] expectedNums = [...]; // The expected answer with correct length 12 | // 13 | //int k = removeDuplicates(nums); // Calls your implementation 14 | // 15 | //assert k == expectedNums.length; 16 | //for (int i = 0; i < k; i++) { 17 | // assert nums[i] == expectedNums[i]; 18 | //} 19 | //If all assertions pass, then your solution will be accepted. 20 | // 21 | // 22 | //Example 1: 23 | // 24 | //Input: nums = [1,1,2] 25 | //Output: 2, nums = [1,2,_] 26 | //Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. 27 | //It does not matter what you leave beyond the returned k (hence they are underscores). 28 | // 29 | //Example 2: 30 | // 31 | //Input: nums = [0,0,1,1,1,2,2,3,3,4] 32 | //Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] 33 | //Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. 34 | //It does not matter what you leave beyond the returned k (hence they are underscores). 35 | // 36 | // 37 | //Constraints: 38 | // 39 | //1 <= nums.length <= 3 * 10^4 40 | //-100 <= nums[i] <= 100 41 | //nums is sorted in non-decreasing order. 42 | 43 | class Solution { 44 | public: 45 | int removeDuplicates(vector& nums) { 46 | if(nums.size() == 0) return 0; 47 | int left = 0; 48 | for(int right =1; right< nums.size(); right++){ 49 | if(nums[left] != nums[right]) 50 | left++; 51 | nums[left] = nums[right]; 52 | } 53 | return left+1; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /C++/Easy/278. First Bad Version.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 3 | 4 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 5 | 6 | You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: n = 5, bad = 4 13 | Output: 4 14 | Explanation: 15 | call isBadVersion(3) -> false 16 | call isBadVersion(5) -> true 17 | call isBadVersion(4) -> true 18 | Then 4 is the first bad version. 19 | Example 2: 20 | 21 | Input: n = 1, bad = 1 22 | Output: 1 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= bad <= n <= 2^31 - 1 28 | */ 29 | 30 | // The API isBadVersion is defined for you. 31 | // bool isBadVersion(int version); 32 | 33 | class Solution { 34 | public: 35 | int firstBadVersion(int n) { 36 | long l = 1, h = n, mid; 37 | while(l<= h){ 38 | mid = (l+h)/2; 39 | if(isBadVersion(mid) == false){ 40 | l = mid+1; 41 | } 42 | else{ 43 | h = mid-1; 44 | } 45 | } 46 | return l; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /C++/Easy/349. Intersection of Two Arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 9 | Output: [2] 10 | Example 2: 11 | 12 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 13 | Output: [9,4] 14 | Explanation: [4,9] is also accepted. 15 | 16 | 17 | Constraints: 18 | 19 | 1 <= nums1.length, nums2.length <= 1000 20 | 0 <= nums1[i], nums2[i] <= 1000 21 | */ 22 | 23 | class Solution { 24 | public: 25 | void remove(vector &v) 26 | { 27 | auto end = v.end(); 28 | for (auto it = v.begin(); it != end; ++it) { 29 | end = std::remove(it + 1, end, *it); 30 | } 31 | 32 | v.erase(end, v.end()); 33 | } 34 | 35 | vector intersection(vector& nums1, vector& nums2) { 36 | sort(nums1.begin(), nums1.end()); 37 | sort(nums2.begin(), nums2.end()); 38 | int i = 0, j = 0; 39 | vector res; 40 | while(i < nums1.size() && j < nums2.size()){ 41 | if(nums1[i] == nums2[j]){ 42 | res.push_back(nums1[i]); 43 | i++; 44 | j++; 45 | } 46 | else if(nums1[i] < nums2[j]){ 47 | i++; 48 | } 49 | else if(nums1[i] > nums2[j]){ 50 | j++; 51 | } 52 | } 53 | remove(res); 54 | return res; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /C++/Easy/35. Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,3,5,6], target = 5 11 | Output: 2 12 | Example 2: 13 | 14 | Input: nums = [1,3,5,6], target = 2 15 | Output: 1 16 | Example 3: 17 | 18 | Input: nums = [1,3,5,6], target = 7 19 | Output: 4 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= nums.length <= 10^4 25 | -10^4 <= nums[i] <= 10^4 26 | nums contains distinct values sorted in ascending order. 27 | -104 <= target <= 10^4 28 | */ 29 | 30 | class Solution { 31 | public: 32 | int searchInsert(vector& nums, int target) { 33 | int l = 0; 34 | int h = nums.size()-1; 35 | int mid; 36 | while(l<=h){ 37 | mid = (l+h)/2; 38 | if(nums[mid] == target){ 39 | return mid; 40 | } 41 | else if(nums[mid] < target){ 42 | l = mid+1; 43 | } 44 | else{ 45 | h = mid-1; 46 | } 47 | } 48 | return l; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /C++/Easy/350. Intersection of Two Arrays II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 9 | Output: [2,2] 10 | Example 2: 11 | 12 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 13 | Output: [4,9] 14 | Explanation: [9,4] is also accepted. 15 | 16 | 17 | Constraints: 18 | 19 | 1 <= nums1.length, nums2.length <= 1000 20 | 0 <= nums1[i], nums2[i] <= 1000 21 | 22 | 23 | Follow up: 24 | 25 | What if the given array is already sorted? How would you optimize your algorithm? 26 | What if nums1's size is small compared to nums2's size? Which algorithm is better? 27 | What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? 28 | */ 29 | 30 | class Solution { 31 | public: 32 | vector intersect(vector& nums1, vector& nums2) { 33 | sort(nums1.begin(), nums1.end()); 34 | sort(nums2.begin(), nums2.end()); 35 | int i = 0, j = 0; 36 | vector res; 37 | while(i < nums1.size() && j < nums2.size()){ 38 | if(nums1[i] == nums2[j]){ 39 | res.push_back(nums1[i]); 40 | i++; 41 | j++; 42 | } 43 | else if(nums1[i] < nums2[j]){ 44 | i++; 45 | } 46 | else if(nums1[i] > nums2[j]){ 47 | j++; 48 | } 49 | } 50 | return res; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /C++/Easy/374. Guess Number Higher or Lower.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We are playing the Guess Game. The game is as follows: 3 | 4 | I pick a number from 1 to n. You have to guess which number I picked. 5 | 6 | Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. 7 | 8 | You call a pre-defined API int guess(int num), which returns three possible results: 9 | 10 | -1: Your guess is higher than the number I picked (i.e. num > pick). 11 | 1: Your guess is lower than the number I picked (i.e. num < pick). 12 | 0: your guess is equal to the number I picked (i.e. num == pick). 13 | Return the number that I picked. 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: n = 10, pick = 6 20 | Output: 6 21 | Example 2: 22 | 23 | Input: n = 1, pick = 1 24 | Output: 1 25 | Example 3: 26 | 27 | Input: n = 2, pick = 1 28 | Output: 1 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= n <= 2^31 - 1 34 | 1 <= pick <= n 35 | */ 36 | 37 | /** 38 | * Forward declaration of guess API. 39 | * @param num your guess 40 | * @return -1 if num is higher than the picked number 41 | * 1 if num is lower than the picked number 42 | * otherwise return 0 43 | * int guess(int num); 44 | */ 45 | 46 | class Solution { 47 | public: 48 | int guessNumber(int n) { 49 | long l = 1, h = n, mid; 50 | while(l <= h){ 51 | mid = l + (h-l)/2; 52 | if(guess(mid) == 1){ 53 | l = mid + 1; 54 | } 55 | else if(guess(mid) == -1){ 56 | h = mid-1; 57 | } 58 | else{ 59 | return mid; 60 | } 61 | } 62 | return l; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /C++/Easy/441. Arranging Coins.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. 3 | Given the integer n, return the number of complete rows of the staircase you will build. 4 | 5 | Example 1: 6 | 7 | 8 | Input: n = 5 9 | Output: 2 10 | Explanation: Because the 3rd row is incomplete, we return 2. 11 | Example 2: 12 | 13 | 14 | Input: n = 8 15 | Output: 3 16 | Explanation: Because the 4th row is incomplete, we return 3. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= n <= 2^31 - 1 22 | */ 23 | 24 | class Solution { 25 | public: 26 | int arrangeCoins(int n) { 27 | long int l = 0, h = n; 28 | while(l <= h){ 29 | long int mid = l + (h-l)/2; 30 | long long int curr = mid*(mid+1)/2; 31 | if(curr == n) 32 | return mid; 33 | else if(curr > n) 34 | h = mid - 1; 35 | else 36 | l = mid + 1; 37 | } 38 | return h; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /C++/Easy/53. Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | //Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 2 | //A subarray is a contiguous part of an array. 3 | // 4 | // 5 | //Example 1: 6 | // 7 | //Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 8 | //Output: 6 9 | //Explanation: [4,-1,2,1] has the largest sum = 6. 10 | //Example 2: 11 | // 12 | //Input: nums = [1] 13 | //Output: 1 14 | //Example 3: 15 | // 16 | //Input: nums = [5,4,-1,7,8] 17 | //Output: 23 18 | // 19 | // 20 | //Constraints: 21 | // 22 | //1 <= nums.length <= 10^5 23 | //-10^4 <= nums[i] <= 10^4 24 | 25 | class Solution { 26 | public: 27 | int maxSubArray(vector& nums) { 28 | int max_till = INT_MIN, max_ending = 0; 29 | 30 | for(int i = 0; i> matrixReshape(vector>& mat, int r, int c) { 29 | int n = mat.size(); //dimension 30 | int m = mat[0].size(); 31 | if(n*m != r*c){ //check if not legal 32 | return mat; 33 | } 34 | 35 | vector> ans(r, vector(c)); 36 | int in = 0; //new matrix dimension 37 | int jn = 0; 38 | for(int i = 0; i plusOne(vector& digits) { 38 | for(int i=digits.size()-1;i>=0;i--){ 39 | if(digits[i]==9){ 40 | digits[i]=0; 41 | } 42 | else{ 43 | digits[i]++; 44 | return digits; 45 | } 46 | } 47 | digits.insert(digits.begin(), 1); 48 | return digits; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /C++/Easy/69. Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. 3 | 4 | You must not use any built-in exponent function or operator. 5 | 6 | For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. 7 | 8 | 9 | Example 1: 10 | 11 | Input: x = 4 12 | Output: 2 13 | Explanation: The square root of 4 is 2, so we return 2. 14 | Example 2: 15 | 16 | Input: x = 8 17 | Output: 2 18 | Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. 19 | 20 | 21 | Constraints: 22 | 23 | 0 <= x <= 2^31 - 1 24 | */ 25 | class Solution { 26 | public: 27 | int mySqrt(int x) { 28 | int result = sqrt(x); 29 | 30 | return result; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /C++/Easy/704. Binary Search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [-1,0,3,5,9,12], target = 9 11 | Output: 4 12 | Explanation: 9 exists in nums and its index is 4 13 | Example 2: 14 | 15 | Input: nums = [-1,0,3,5,9,12], target = 2 16 | Output: -1 17 | Explanation: 2 does not exist in nums so return -1 18 | 19 | 20 | Constraints: 21 | 22 | 1 <= nums.length <= 10^4 23 | -10^4 < nums[i], target < 10^4 24 | All the integers in nums are unique. 25 | nums is sorted in ascending order. 26 | */ 27 | 28 | class Solution { 29 | public: 30 | int search(vector& nums, int target) { 31 | int l = 0; 32 | int h = nums.size() -1; 33 | while(l <= h){ 34 | int mid = l + (h-l)/2; 35 | if(nums[mid] == target){ 36 | return mid; 37 | } 38 | else if(nums[mid] < target) 39 | l = mid + 1; 40 | else 41 | h = mid - 1; 42 | } 43 | return -1; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/Easy/744. Find Smallest Letter Greater Than Target.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters. 3 | 4 | Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: letters = ["c","f","j"], target = "a" 11 | Output: "c" 12 | Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'. 13 | Example 2: 14 | 15 | Input: letters = ["c","f","j"], target = "c" 16 | Output: "f" 17 | Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'. 18 | Example 3: 19 | 20 | Input: letters = ["x","x","y","y"], target = "z" 21 | Output: "x" 22 | Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0]. 23 | 24 | 25 | Constraints: 26 | 27 | 2 <= letters.length <= 104 28 | letters[i] is a lowercase English letter. 29 | letters is sorted in non-decreasing order. 30 | letters contains at least two different characters. 31 | target is a lowercase English letter. 32 | */ 33 | class Solution { 34 | public: 35 | char nextGreatestLetter(vector& letters, char target) { 36 | int l = 0; 37 | int h = letters.size() -1; 38 | while(l < h){ 39 | int m = (l+h)/2; 40 | if(letters[m] <= target) 41 | l = m+1; 42 | else 43 | h = m; 44 | } 45 | if(l == letters.size()-1){ 46 | if(letters[l] <= target){ 47 | return letters[0]; 48 | } 49 | } 50 | return letters[l]; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /C++/Easy/83. Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: head = [1,1,2] 10 | Output: [1,2] 11 | Example 2: 12 | 13 | 14 | Input: head = [1,1,2,3,3] 15 | Output: [1,2,3] 16 | 17 | 18 | Constraints: 19 | 20 | The number of nodes in the list is in the range [0, 300]. 21 | -100 <= Node.val <= 100 22 | The list is guaranteed to be sorted in ascending order. 23 | */ 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * struct ListNode { 28 | * int val; 29 | * ListNode *next; 30 | * ListNode() : val(0), next(nullptr) {} 31 | * ListNode(int x) : val(x), next(nullptr) {} 32 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 33 | * }; 34 | */ 35 | class Solution { 36 | public: 37 | ListNode* deleteDuplicates(ListNode* head) { 38 | ListNode* curr = head; 39 | while (curr && curr->next) { 40 | ListNode* next_node = curr->next; 41 | if (curr->val == next_node->val){ 42 | curr->next = next_node->next; 43 | delete next_node; 44 | } 45 | else 46 | curr = next_node; 47 | } 48 | return head; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /C++/Easy/832. Flipping an Image.cpp: -------------------------------------------------------------------------------- 1 | //Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. 2 | //To flip an image horizontally means that each row of the image is reversed. 3 | // 4 | //For example, flipping [1,1,0] horizontally results in [0,1,1]. 5 | //To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. 6 | // 7 | //For example, inverting [0,1,1] results in [1,0,0]. 8 | // 9 | // 10 | //Example 1: 11 | // 12 | //Input: image = [[1,1,0],[1,0,1],[0,0,0]] 13 | //Output: [[1,0,0],[0,1,0],[1,1,1]] 14 | //Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. 15 | //Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] 16 | //Example 2: 17 | // 18 | //Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 19 | //Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 20 | //Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 21 | //Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 22 | // 23 | // 24 | //Constraints: 25 | // 26 | //n == image.length 27 | //n == image[i].length 28 | //1 <= n <= 20 29 | //images[i][j] is either 0 or 1. 30 | 31 | class Solution { 32 | public: 33 | vector> flipAndInvertImage(vector>& A) { 34 | for (int i=0; i> transpose(vector>& matrix) { 25 | int n = matrix.size(); //row 26 | int m = matrix[0].size(); //col 27 | 28 | vector> res(m,vector (n,0)); 29 | for(int i=0;inext; 45 | length++; 46 | } 47 | int nodePos = length/2; 48 | ListNode* mid = head; 49 | for(int i = 0; inext; 51 | } 52 | return mid; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /C++/Easy/88. Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. 3 | 4 | Merge nums1 and nums2 into a single array sorted in non-decreasing order. 5 | 6 | The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 13 | Output: [1,2,2,3,5,6] 14 | Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. 15 | The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. 16 | Example 2: 17 | 18 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 19 | Output: [1] 20 | Explanation: The arrays we are merging are [1] and []. 21 | The result of the merge is [1]. 22 | Example 3: 23 | 24 | Input: nums1 = [0], m = 0, nums2 = [1], n = 1 25 | Output: [1] 26 | Explanation: The arrays we are merging are [] and [1]. 27 | The result of the merge is [1]. 28 | Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. 29 | 30 | 31 | Constraints: 32 | 33 | nums1.length == m + n 34 | nums2.length == n 35 | 0 <= m, n <= 200 36 | 1 <= m + n <= 200 37 | -109 <= nums1[i], nums2[j] <= 109 38 | */ 39 | 40 | class Solution { 41 | public: 42 | void merge(vector& nums1, int m, vector& nums2, int n) { 43 | int i=m-1,j=n-1,k=m+n-1; 44 | while(i>=0&&j>=0) 45 | { 46 | if(nums1[i]>nums2[j]) 47 | { 48 | nums1[k]=nums1[i]; 49 | i--; 50 | k--; 51 | } 52 | else 53 | { 54 | nums1[k]=nums2[j]; 55 | j--; 56 | k--; 57 | } 58 | } 59 | while(i>=0) 60 | nums1[k--]=nums1[i--]; 61 | while(j>=0) 62 | nums1[k--]=nums2[j--]; 63 | 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /C++/Easy/9. Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer x, return true if x is a 3 | palindrome 4 | , and false otherwise. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: x = 121 11 | Output: true 12 | Explanation: 121 reads as 121 from left to right and from right to left. 13 | Example 2: 14 | 15 | Input: x = -121 16 | Output: false 17 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 18 | Example 3: 19 | 20 | Input: x = 10 21 | Output: false 22 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 23 | 24 | 25 | Constraints: 26 | 27 | -231 <= x <= 231 - 1 28 | */ 29 | class Solution { 30 | public: 31 | bool isPalindrome(int x) { 32 | string str = to_string(x); 33 | string s1 = str; 34 | reverse(s1.begin(), s1.end()); 35 | return s1==str; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /C++/Easy/989. Add to Array-Form of Integer.cpp: -------------------------------------------------------------------------------- 1 | //The array-form of an integer num is an array representing its digits in left to right order.// 2 | //For example, for num = 1321, the array form is [1,3,2,1]. 3 | //Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. 4 | // 5 | // 6 | //Example 1: 7 | // 8 | //Input: num = [1,2,0,0], k = 34 9 | //Output: [1,2,3,4] 10 | //Explanation: 1200 + 34 = 1234 11 | //Example 2: 12 | // 13 | //Input: num = [2,7,4], k = 181 14 | //Output: [4,5,5] 15 | //Explanation: 274 + 181 = 455 16 | //Example 3: 17 | // 18 | //Input: num = [2,1,5], k = 806 19 | //Output: [1,0,2,1] 20 | //Explanation: 215 + 806 = 1021 21 | // 22 | // 23 | //Constraints: 24 | // 25 | //1 <= num.length <= 10^//4 26 | //0 <= num[i] <= 9 27 | //num does not contain any leading zeros except for the zero itself. 28 | //1 <= k <= 10^4 29 | 30 | class Solution { 31 | public: 32 | vector addToArrayForm(vector& num, int k) { 33 | int i = num.size() - 1; 34 | int carr = k; 35 | vector ans; 36 | while(i >= 0 || carr > 0){ 37 | if(i >= 0){ 38 | carr += num[i]; 39 | i--; 40 | } 41 | 42 | ans.push_back(carr%10); 43 | carr /= 10; 44 | } 45 | reverse(ans.begin(), ans.end()); 46 | return ans; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /C++/Easy/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Easy** solved in the `C++` Programming Language 3 | -------------------------------------------------------------------------------- /C++/Hard/1095. Find in Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | (This problem is an interactive problem.) 3 | 4 | You may recall that an array arr is a mountain array if and only if: 5 | 6 | arr.length >= 3 7 | There exists some i with 0 < i < arr.length - 1 such that: 8 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 9 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 10 | Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. 11 | 12 | You cannot access the mountain array directly. You may only access the array using a MountainArray interface: 13 | 14 | MountainArray.get(k) returns the element of the array at index k (0-indexed). 15 | MountainArray.length() returns the length of the array. 16 | Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: array = [1,2,3,4,5,3,1], target = 3 23 | Output: 2 24 | Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. 25 | Example 2: 26 | 27 | Input: array = [0,1,2,4,2,1], target = 3 28 | Output: -1 29 | Explanation: 3 does not exist in the array, so we return -1. 30 | 31 | 32 | Constraints: 33 | 34 | 3 <= mountain_arr.length() <= 10^4 35 | 0 <= target <= 109 36 | 0 <= mountain_arr.get(index) <= 10^9 37 | */ 38 | 39 | /** 40 | * // This is the MountainArray's API interface. 41 | * // You should not implement it, or speculate about its implementation 42 | * class MountainArray { 43 | * public: 44 | * int get(int index); 45 | * int length(); 46 | * }; 47 | */ 48 | 49 | class Solution { 50 | public: 51 | int findInMountainArray(int target, MountainArray &mountainArr) { 52 | int n = mountainArr.length(); 53 | int max_idx = 0; 54 | int lo=0, hi = n-1; 55 | while(lotarget) 80 | lo = mid+1; 81 | else if(mountainArr.get(mid)==target) 82 | return mid; 83 | else 84 | hi = mid-1; 85 | } 86 | return -1; 87 | } 88 | }; 89 | -------------------------------------------------------------------------------- /C++/Hard/1250. Check If It Is a Good Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. 3 | 4 | Return True if the array is good otherwise return False. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [12,5,7,23] 11 | Output: true 12 | Explanation: Pick numbers 5 and 7. 13 | 5*3 + 7*(-2) = 1 14 | Example 2: 15 | 16 | Input: nums = [29,6,10] 17 | Output: true 18 | Explanation: Pick numbers 29, 6 and 10. 19 | 29*1 + 6*(-3) + 10*(-1) = 1 20 | Example 3: 21 | 22 | Input: nums = [3,6] 23 | Output: false 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 10^5 29 | 1 <= nums[i] <= 10^9 30 | */ 31 | 32 | class Solution { 33 | public: 34 | int gcd(int a, int b){ 35 | if(b == 0){ 36 | return a; 37 | } 38 | 39 | return gcd(b, a%b); 40 | } 41 | bool isGoodArray(vector& nums) { 42 | int a = 0; 43 | for(int i = 0; inext; 46 | } 47 | ListNode* curr = head; 48 | ListNode* prev = nullptr; 49 | ListNode* nxt = nullptr; 50 | for(int i = 0; i < k; i++){ 51 | nxt = curr->next; 52 | curr->next = prev; 53 | prev = curr; 54 | curr = nxt; 55 | } 56 | for(int i = 0; curr!=NULL && i < k; i++){ 57 | prev = curr; 58 | curr = curr->next; 59 | } 60 | head->next = reverseKGroup(curr, k); 61 | return prev; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /C++/Hard/4. Median of Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 3 | 4 | The overall run time complexity should be O(log (m+n)). 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums1 = [1,3], nums2 = [2] 11 | Output: 2.00000 12 | Explanation: merged array = [1,2,3] and median is 2. 13 | Example 2: 14 | 15 | Input: nums1 = [1,2], nums2 = [3,4] 16 | Output: 2.50000 17 | Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. 18 | 19 | 20 | Constraints: 21 | 22 | nums1.length == m 23 | nums2.length == n 24 | 0 <= m <= 1000 25 | 0 <= n <= 1000 26 | 1 <= m + n <= 2000 27 | -106 <= nums1[i], nums2[i] <= 106 28 | */ 29 | 30 | class Solution { 31 | public: 32 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 33 | vector srt(nums1.size() + nums2.size()); 34 | merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), srt.begin()); 35 | int mid = ((srt.size() / 2) - 1); 36 | if (srt.size() % 2 == 1) 37 | return (double)srt[mid + 1]; 38 | else 39 | return (((double)srt[mid] + srt[mid + 1]) / 2); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /C++/Hard/41. First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted integer array nums, return the smallest missing positive integer. 3 | You must implement an algorithm that runs in O(n) time and uses constant extra space. 4 | 5 | Example 1: 6 | 7 | Input: nums = [1,2,0] 8 | Output: 3 9 | Explanation: The numbers in the range [1,2] are all in the array. 10 | 11 | Example 2: 12 | 13 | Input: nums = [3,4,-1,1] 14 | Output: 2 15 | Explanation: 1 is in the array but 2 is missing. 16 | 17 | Example 3: 18 | 19 | Input: nums = [7,8,9,11,12] 20 | Output: 1 21 | Explanation: The smallest positive integer 1 is missing. 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= nums.length <= 10^5 27 | -2^31 <= nums[i] <= 2^31 - 1 28 | */ 29 | 30 | class Solution { 31 | public: 32 | int firstMissingPositive(vector& nums) { 33 | int n=nums.size(); 34 | int i=0; 35 | //cycle sort 36 | while(i0 && nums[i]<=n && nums[i] != nums[nums[i]-1]) 39 | { 40 | swap(nums[i] , nums[nums[i]-1]); 41 | } 42 | else 43 | { 44 | i++; 45 | } 46 | } 47 | //search for first missing number 48 | for(i = 0; inext == NULL){ 54 | return NULL; 55 | } 56 | while(fast != NULL && fast->next != NULL){ 57 | fast = fast->next->next; 58 | slow = slow->next; 59 | lcycle++; 60 | 61 | //cycle present 62 | if(slow == fast){ 63 | fast = head; 64 | while(fast != slow){ 65 | fast = fast->next; 66 | slow = slow->next; 67 | } 68 | return slow; 69 | } 70 | } 71 | return NULL; 72 | } 73 | }; 74 | -------------------------------------------------------------------------------- /C++/Medium/143. Reorder List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given the head of a singly linked-list. The list can be represented as: 3 | 4 | L0 → L1 → … → Ln - 1 → Ln 5 | Reorder the list to be on the following form: 6 | 7 | L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … 8 | You may not modify the values in the list's nodes. Only nodes themselves may be changed. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | 15 | Input: head = [1,2,3,4] 16 | Output: [1,4,2,3] 17 | Example 2: 18 | 19 | 20 | Input: head = [1,2,3,4,5] 21 | Output: [1,5,2,4,3] 22 | 23 | 24 | Constraints: 25 | 26 | The number of nodes in the list is in the range [1, 5 * 104]. 27 | 1 <= Node.val <= 1000 28 | */ 29 | /** 30 | * Definition for singly-linked list. 31 | * struct ListNode { 32 | * int val; 33 | * ListNode *next; 34 | * ListNode() : val(0), next(nullptr) {} 35 | * ListNode(int x) : val(x), next(nullptr) {} 36 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 37 | * }; 38 | */ 39 | //Upvote and Comment 40 | class Solution { 41 | public: 42 | ListNode* reverse(ListNode* head) 43 | { 44 | ListNode* prev=NULL; 45 | ListNode* curr=head; 46 | ListNode* nxt=NULL; 47 | 48 | while(curr) 49 | { 50 | nxt=curr->next; 51 | curr->next=prev; 52 | prev=curr; 53 | curr=nxt; 54 | } 55 | return prev; 56 | } 57 | 58 | void reorderList(ListNode* head) { 59 | 60 | //step 1 - using slow and fast pointer approach to find the mid of the list 61 | ListNode* slow=head; 62 | ListNode* fast=head->next; 63 | 64 | while(fast and fast->next) 65 | { 66 | slow=slow->next; 67 | fast=fast->next->next; 68 | } 69 | 70 | //step 2 - reverse the second half and split the List into two. 71 | ListNode* second=reverse(slow->next); // independent list second 72 | slow->next=NULL; 73 | ListNode* first=head; // independent list first 74 | 75 | //step 3 - merging the two list 76 | // second list can be shorter when LL size is odd 77 | while(second) 78 | { 79 | ListNode* temp1=first->next; 80 | ListNode* temp2=second->next; 81 | first->next=second; 82 | second->next=temp1; 83 | first=temp1; 84 | second=temp2; 85 | } 86 | } 87 | }; 88 | -------------------------------------------------------------------------------- /C++/Medium/148. Sort List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a linked list, return the list after sorting it in ascending order. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: head = [4,2,1,3] 10 | Output: [1,2,3,4] 11 | Example 2: 12 | 13 | 14 | Input: head = [-1,5,3,4,0] 15 | Output: [-1,0,3,4,5] 16 | Example 3: 17 | 18 | Input: head = [] 19 | Output: [] 20 | 21 | 22 | Constraints: 23 | 24 | The number of nodes in the list is in the range [0, 5 * 104]. 25 | -105 <= Node.val <= 105 26 | 27 | */ 28 | /** 29 | * Definition for singly-linked list. 30 | * struct ListNode { 31 | * int val; 32 | * ListNode *next; 33 | * ListNode() : val(0), next(nullptr) {} 34 | * ListNode(int x) : val(x), next(nullptr) {} 35 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 36 | * }; 37 | */ 38 | class Solution { 39 | public: 40 | ListNode* midpoint(ListNode* head){ 41 | if(head == NULL or head->next == NULL){ 42 | return head; 43 | } 44 | 45 | ListNode *slow = head, *fast = head->next; 46 | while(fast && fast->next){ 47 | slow = slow->next; 48 | fast = fast->next->next; 49 | } 50 | 51 | return slow; 52 | } 53 | 54 | ListNode* mergeSortedLists(ListNode* a, ListNode* b){ 55 | if(a == NULL) return b; 56 | if(b == NULL) return a; 57 | 58 | ListNode* temp; 59 | if(a->val <= b->val){ 60 | temp = a; 61 | temp->next = mergeSortedLists(a->next, b); 62 | } 63 | else{ 64 | temp = b; 65 | temp->next = mergeSortedLists(a, b->next); 66 | } 67 | 68 | return temp; 69 | } 70 | 71 | ListNode* sortList(ListNode* head) { 72 | if(head == NULL or head->next == NULL){ 73 | return head; 74 | } 75 | 76 | ListNode* mid = midpoint(head); 77 | ListNode* a = head; 78 | ListNode* b = mid->next; 79 | 80 | mid->next = NULL; 81 | 82 | a = sortList(a); 83 | b = sortList(b); 84 | 85 | ListNode* temp = mergeSortedLists(a, b); 86 | return temp; 87 | } 88 | }; 89 | -------------------------------------------------------------------------------- /C++/Medium/153. Find Minimum in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: 3 | 4 | [4,5,6,7,0,1,2] if it was rotated 4 times. 5 | [0,1,2,4,5,6,7] if it was rotated 7 times. 6 | Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. 7 | 8 | Given the sorted rotated array nums of unique elements, return the minimum element of this array. 9 | 10 | You must write an algorithm that runs in O(log n) time. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums = [3,4,5,1,2] 17 | Output: 1 18 | Explanation: The original array was [1,2,3,4,5] rotated 3 times. 19 | Example 2: 20 | 21 | Input: nums = [4,5,6,7,0,1,2] 22 | Output: 0 23 | Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. 24 | Example 3: 25 | 26 | Input: nums = [11,13,15,17] 27 | Output: 11 28 | Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 29 | 30 | 31 | Constraints: 32 | 33 | n == nums.length 34 | 1 <= n <= 5000 35 | -5000 <= nums[i] <= 5000 36 | All the integers of nums are unique. 37 | nums is sorted and rotated between 1 and n times. 38 | */ 39 | 40 | class Solution { 41 | public: 42 | int findMin(vector& nums) { 43 | int s = 0; 44 | int e = nums.size()-1; 45 | int mid; 46 | 47 | while(s<=e){ 48 | mid = (s+e)/2; 49 | 50 | if(nums[mid] >= nums[e]){ 51 | s = mid+1; 52 | } 53 | else{ 54 | e = mid; 55 | } 56 | } 57 | return nums[mid]; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /C++/Medium/167. Two Sum II - Input Array Is Sorted.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. 3 | 4 | Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. 5 | 6 | The tests are generated such that there is exactly one solution. You may not use the same element twice. 7 | 8 | Your solution must use only constant extra space. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: numbers = [2,7,11,15], target = 9 15 | Output: [1,2] 16 | Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. 17 | Example 2: 18 | 19 | Input: numbers = [2,3,4], target = 6 20 | Output: [1,3] 21 | Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. 22 | Example 3: 23 | 24 | Input: numbers = [-1,0], target = -1 25 | Output: [1,2] 26 | Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. 27 | 28 | 29 | Constraints: 30 | 31 | 2 <= numbers.length <= 3 * 10^4 32 | -1000 <= numbers[i] <= 1000 33 | numbers is sorted in non-decreasing order. 34 | -1000 <= target <= 1000 35 | The tests are generated such that there is exactly one solution. 36 | */ 37 | 38 | class Solution { 39 | public: 40 | vector twoSum(vector& numbers, int target) { 41 | int low = 0, high = numbers.size()-1; 42 | while(low < high) 43 | { 44 | if(numbers[low] + numbers[high] == target) 45 | { 46 | return vector {low+1, high+1}; 47 | } 48 | else if(numbers[low] + numbers[high] > target) 49 | high--; 50 | else 51 | low++; 52 | } 53 | return vector { }; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /C++/Medium/189. Rotate Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, rotate the array to the right by k steps, where k is non-negative. 3 | 4 | Example 1: 5 | 6 | Input: nums = [1,2,3,4,5,6,7], k = 3 7 | Output: [5,6,7,1,2,3,4] 8 | Explanation: 9 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 10 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 11 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 12 | 13 | Example 2: 14 | 15 | Input: nums = [-1,-100,3,99], k = 2 16 | Output: [3,99,-1,-100] 17 | Explanation: 18 | rotate 1 steps to the right: [99,-1,-100,3] 19 | rotate 2 steps to the right: [3,99,-1,-100] 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= nums.length <= 10^5 25 | -2^31 <= nums[i] <= 2^31 - 1 26 | 0 <= k <= 10^5 27 | */ 28 | class Solution { 29 | public : 30 | void reverse(vector& nums, int i, int j){ 31 | int li = i; // left; 32 | int ri = j; 33 | 34 | while(li < ri){ 35 | int temp = nums[li]; 36 | nums[li] = nums[ri]; 37 | nums[ri] = temp; 38 | 39 | li++; 40 | ri--; 41 | } 42 | } 43 | void rotate(vector& nums, int k) { 44 | k = k % nums.size(); 45 | if(k < 0){ 46 | k += nums.size(); 47 | } 48 | reverse(nums, 0, nums.size() - k - 1); 49 | reverse(nums, nums.size() - k, nums.size() - 1); 50 | reverse(nums, 0, nums.size() - 1); 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /C++/Medium/198. House Robber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 3 | Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. 4 | 5 | Example 1: 6 | 7 | Input: nums = [1,2,3,1] 8 | Output: 4 9 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 10 | Total amount you can rob = 1 + 3 = 4. 11 | 12 | Example 2: 13 | 14 | Input: nums = [2,7,9,3,1] 15 | Output: 12 16 | Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 17 | Total amount you can rob = 2 + 9 + 1 = 12. 18 | 19 | Constraints: 20 | 21 | 1 <= nums.length <= 100 22 | 0 <= nums[i] <= 400 23 | */ 24 | 25 | class Solution { 26 | public: 27 | int rob(vector& nums) { 28 | int n = nums.size(); 29 | if(n == 1) 30 | return nums[0]; 31 | 32 | vector profit_till_now(n); 33 | profit_till_now[0] = nums[0]; 34 | profit_till_now[1] = max(nums[0], nums[1]); 35 | 36 | for(int i = 2; i productExceptSelf(vector& nums) { 26 | int n = nums.size(); 27 | vector left_product (n, 1); 28 | vector right_product (n, 1); 29 | 30 | // left product 31 | for(int i = 1; i=0; i--){ 37 | right_product[i] = nums[i+1]*right_product[i+1]; 38 | } 39 | 40 | // product left product with right one 41 | for(int i = 0; i1) 44 | { 45 | store[s[l]]--; 46 | l++; 47 | } 48 | 49 | ans = max(ans,r-l+1); 50 | r++; 51 | } 52 | return ans; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /C++/Medium/33. Search in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There is an integer array nums sorted in ascending order (with distinct values). 3 | 4 | Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. 5 | 6 | Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 7 | 8 | You must write an algorithm with O(log n) runtime complexity. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: nums = [4,5,6,7,0,1,2], target = 0 15 | Output: 4 16 | Example 2: 17 | 18 | Input: nums = [4,5,6,7,0,1,2], target = 3 19 | Output: -1 20 | Example 3: 21 | 22 | Input: nums = [1], target = 0 23 | Output: -1 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 5000 29 | -10^4 <= nums[i] <= 104^ 30 | All values of nums are unique. 31 | nums is an ascending array that is possibly rotated. 32 | -10^4 <= target <= 10^4 33 | */ 34 | class Solution { 35 | public: 36 | int search(vector& nums, int target) { 37 | int low=0,high=nums.size()-1; 38 | while(low<=high){ 39 | int mid = (low+high)/2; 40 | if(nums[mid]==target) return mid; 41 | 42 | if(nums[mid]>=nums[low]){ 43 | //left half is sorted 44 | if(target>=nums[low] && targetnums[mid] && target<=nums[high]) 52 | low = mid+1; 53 | else 54 | high = mid-1; 55 | } 56 | } 57 | return -1; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /C++/Medium/34. Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. 3 | 4 | If target is not found in the array, return [-1, -1]. 5 | 6 | You must write an algorithm with O(log n) runtime complexity. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [5,7,7,8,8,10], target = 8 13 | Output: [3,4] 14 | Example 2: 15 | 16 | Input: nums = [5,7,7,8,8,10], target = 6 17 | Output: [-1,-1] 18 | Example 3: 19 | 20 | Input: nums = [], target = 0 21 | Output: [-1,-1] 22 | 23 | 24 | Constraints: 25 | 26 | 0 <= nums.length <= 10^5 27 | -10^9 <= nums[i] <= 10^9 28 | nums is a non-decreasing array. 29 | -109 <= target <= 109 30 | */ 31 | 32 | class Solution { 33 | public: 34 | int returnIndex(vector& nums, int target, bool findStartIndex){ 35 | int l = 0, h = nums.size() -1; 36 | int res = -1; 37 | 38 | 39 | while(l <= h){ 40 | int m = l + (h-l)/2; //middle element 41 | if(nums[m] == target){ 42 | //check for first occurance 43 | if(findStartIndex == true){ 44 | h = m-1; 45 | res = m; 46 | } 47 | //check for last occurance 48 | else{ 49 | l = m +1; 50 | res = m; 51 | } 52 | } 53 | else if(nums[m] < target) 54 | l = m+1; 55 | else 56 | h = m-1; 57 | } 58 | return res; 59 | } 60 | 61 | vector searchRange(vector& nums, int target) { 62 | vector ans (2, -1); 63 | //find first occurance 64 | ans[0] = returnIndex(nums, target, true); 65 | //find last occurance 66 | ans[1] = returnIndex(nums, target, false); 67 | return ans; 68 | } 69 | }; 70 | -------------------------------------------------------------------------------- /C++/Medium/367. Valid Perfect Square.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 3 | 4 | Follow up: Do not use any built-in library function such as sqrt. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: num = 16 11 | Output: true 12 | Example 2: 13 | 14 | Input: num = 14 15 | Output: false 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= num <= 2^31 - 1 21 | */ 22 | class Solution { 23 | public: 24 | bool isPerfectSquare(int num) { 25 | long l = 1, h = num, mid; 26 | if(num == 1){ 27 | return true; 28 | } 29 | while(l spiralOrder(vector>& matrix) { 23 | int n = matrix.size(); 24 | int m = matrix[0].size(); 25 | int left = 0,right = m-1,bottom = n-1,top = 0; 26 | int direction = 1; 27 | vector v; 28 | while(left <= right && top <= bottom) 29 | { 30 | if(direction == 1) 31 | { 32 | for(int i = left; i <= right; i++){ 33 | v.push_back(matrix[top][i]); 34 | } 35 | direction = 2; 36 | top++; 37 | } 38 | 39 | else if(direction == 2) 40 | { 41 | for(int i = top; i <= bottom; i++){ 42 | v.push_back(matrix[i][right]); 43 | } 44 | direction = 3; 45 | right--; 46 | } 47 | 48 | else if(direction == 3) 49 | { 50 | for(int i = right; i >= left; i--){ 51 | v.push_back(matrix[bottom][i]); 52 | } 53 | direction = 4; 54 | bottom--; 55 | } 56 | 57 | else if(direction == 4) 58 | { 59 | for(int i = bottom; i >= top; i--){ 60 | v.push_back(matrix[i][left]); 61 | } 62 | direction = 1; 63 | left++; 64 | } 65 | } 66 | return v; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /C++/Medium/540. Single Element in a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. 3 | 4 | Return the single element that appears only once. 5 | 6 | Your solution must run in O(log n) time and O(1) space. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,1,2,3,3,4,4,8,8] 13 | Output: 2 14 | Example 2: 15 | 16 | Input: nums = [3,3,7,7,10,11,11] 17 | Output: 10 18 | 19 | 20 | Constraints: 21 | 22 | 1 <= nums.length <= 10^5 23 | 0 <= nums[i] <= 10^5 24 | */ 25 | 26 | class Solution { 27 | public: 28 | int singleNonDuplicate(vector& nums) { 29 | int l = 0; 30 | int h = nums.size() -1; 31 | int mid; 32 | while(h > l){ 33 | mid = l + (h-l)/2; 34 | if(nums[mid] != nums[mid+1] && nums[mid] != nums[mid-1]) 35 | return nums[mid]; 36 | else if(mid%2 == 0){ 37 | if(nums[mid] != nums[mid+1]) 38 | h = mid - 2; 39 | else 40 | l = mid + 2; 41 | } 42 | else{ 43 | if(nums[mid] != nums[mid+1]) 44 | l = mid+1; 45 | else 46 | h = mid-1; 47 | } 48 | } 49 | return nums[l]; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /C++/Medium/55. Jump Game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. 3 | Return true if you can reach the last index, or false otherwise. 4 | 5 | 6 | Example 1: 7 | 8 | Input: nums = [2,3,1,1,4] 9 | Output: true 10 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 11 | 12 | Example 2: 13 | 14 | Input: nums = [3,2,1,0,4] 15 | Output: false 16 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= nums.length <= 10^4 22 | 0 <= nums[i] <= 10^5 23 | */ 24 | 25 | class Solution { 26 | public: 27 | bool canJump(vector& nums) { 28 | int min_jump = 0; //min jump required to reach the end 29 | for(int i = nums.size() - 2; i >= 0; i--){ 30 | min_jump++; 31 | if(nums[i] >= min_jump) // can reach the end 32 | min_jump = 0; 33 | } 34 | if(min_jump == 0) 35 | return true; 36 | return false; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /C++/Medium/59. Spiral Matrix II.cpp: -------------------------------------------------------------------------------- 1 | //Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. 2 | // 3 | //Example 1: 4 | // 5 | //Input: n = 3 6 | //Output: [[1,2,3],[8,9,4],[7,6,5]] 7 | // 8 | //Example 2: 9 | // 10 | //Input: n = 1 11 | //Output: [[1]] 12 | // 13 | //Constraints: 14 | // 15 | //1 <= n <= 20 16 | 17 | class Solution { 18 | public: 19 | vector> generateMatrix(int n) { 20 | vector> matrix(n,vector(n)); 21 | int top = 0; 22 | int bottom = n-1; 23 | int left = 0; 24 | int right = n-1; 25 | int direction = 1; 26 | int num = 1; 27 | while(left <= right && top <= bottom) 28 | { 29 | if(direction == 1) 30 | { 31 | for(int i = left; i <= right; i++){ 32 | matrix[top][i] = num; 33 | num++; 34 | } 35 | direction = 2; 36 | top++; 37 | } 38 | 39 | else if(direction == 2) 40 | { 41 | for(int i = top; i <= bottom; i++){ 42 | matrix[i][right] = num; 43 | num++; 44 | } 45 | direction = 3; 46 | right--; 47 | } 48 | 49 | else if(direction == 3) 50 | { 51 | for(int i = right; i >= left; i--){ 52 | matrix[bottom][i] = num; 53 | num++; 54 | } 55 | direction = 4; 56 | bottom--; 57 | } 58 | 59 | else if(direction == 4) 60 | { 61 | for(int i = bottom; i >= top; i--){ 62 | matrix[i][left] = num; 63 | num++; 64 | } 65 | direction = 1; 66 | left++; 67 | } 68 | } 69 | return matrix; 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /C++/Medium/707. Design Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list. 3 | A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. 4 | If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. 5 | 6 | Implement the MyLinkedList class: 7 | 8 | MyLinkedList() Initializes the MyLinkedList object. 9 | int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1. 10 | void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. 11 | void addAtTail(int val) Append a node of value val as the last element of the linked list. 12 | void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted. 13 | void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid. 14 | 15 | 16 | Example 1: 17 | 18 | Input 19 | ["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"] 20 | [[], [1], [3], [1, 2], [1], [1], [1]] 21 | Output 22 | [null, null, null, null, 2, null, 3] 23 | 24 | Explanation 25 | MyLinkedList myLinkedList = new MyLinkedList(); 26 | myLinkedList.addAtHead(1); 27 | myLinkedList.addAtTail(3); 28 | myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3 29 | myLinkedList.get(1); // return 2 30 | myLinkedList.deleteAtIndex(1); // now the linked list is 1->3 31 | myLinkedList.get(1); // return 3 32 | 33 | 34 | Constraints: 35 | 36 | 0 <= index, val <= 1000 37 | Please do not use the built-in LinkedList library. 38 | At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex. 39 | */ 40 | 41 | class MyLinkedList { 42 | 43 | private: 44 | class Node{ 45 | public: 46 | int val; 47 | Node* next; 48 | 49 | Node(int val, Node* next): val(val), next(next){} 50 | Node(int val): Node(val, NULL){} 51 | }; 52 | 53 | Node* head; 54 | 55 | public: 56 | /** Initialize your data structure here. */ 57 | MyLinkedList() { 58 | head = NULL; 59 | } 60 | 61 | /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ 62 | int get(int index) { 63 | 64 | Node* cur = head; 65 | for(int i = 0; i < index && cur; i ++) 66 | cur = cur->next; 67 | 68 | if(!cur) return -1; 69 | return cur->val; 70 | } 71 | 72 | /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ 73 | void addAtHead(int val) { 74 | head = new Node(val, head); 75 | } 76 | 77 | /** Append a node of value val to the last element of the linked list. */ 78 | void addAtTail(int val) { 79 | 80 | if(head == NULL) 81 | head = new Node(val); 82 | else{ 83 | Node* pre = head; 84 | while(pre->next) 85 | pre = pre->next; 86 | pre->next = new Node(val); 87 | } 88 | } 89 | 90 | /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ 91 | void addAtIndex(int index, int val) { 92 | 93 | if(index == 0) 94 | addAtHead(val); 95 | else{ 96 | Node* pre = head; 97 | for(int i = 1; i < index && pre; i ++) 98 | pre = pre->next; 99 | 100 | if(pre) 101 | pre->next = new Node(val, pre->next); 102 | } 103 | } 104 | 105 | /** Delete the index-th node in the linked list, if the index is valid. */ 106 | void deleteAtIndex(int index) { 107 | if(index == 0){ 108 | if(head){ 109 | Node* delNode = head; 110 | head = head->next; 111 | delete delNode; 112 | } 113 | } 114 | else{ 115 | Node* pre = head; 116 | for(int i = 1; i < index && pre; i ++) 117 | pre = pre->next; 118 | 119 | if(pre && pre->next){ 120 | Node* delNode = pre->next; 121 | pre->next = delNode->next; 122 | delete delNode; 123 | } 124 | } 125 | } 126 | }; 127 | 128 | /** 129 | * Your MyLinkedList object will be instantiated and called as such: 130 | * MyLinkedList obj = new MyLinkedList(); 131 | * int param_1 = obj.get(index); 132 | * obj.addAtHead(val); 133 | * obj.addAtTail(val); 134 | * obj.addAtIndex(index,val); 135 | * obj.deleteAtIndex(index); 136 | */ 137 | -------------------------------------------------------------------------------- /C++/Medium/73. Set Matrix Zeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. 3 | You must do it in place. 4 | Example 1: 5 | Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] 6 | Output: [[1,0,1],[0,0,0],[1,0,1]] 7 | Example 2: 8 | Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 9 | Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] 10 | Constraints: 11 | m == matrix.length 12 | n == matrix[0].length 13 | 1 <= m, n <= 200 14 | -231 <= matrix[i][j] <= 231 - 1 15 | */ 16 | 17 | class Solution { 18 | public: 19 | void setZeroes(vector>& matrix) 20 | { 21 | int row = matrix.size(); 22 | int col = matrix[0].size(); 23 | bool isFirstRowZero = false; 24 | bool isFirstColZero = false; 25 | 26 | // For checking if first row contains zero 27 | for(int i = 0; i < row; i++) 28 | { 29 | if(matrix[i][0] == 0) 30 | { 31 | isFirstColZero = true; 32 | break; 33 | } 34 | } 35 | 36 | // For checking if first column contains zero 37 | for(int i = 0; i < col; i++) 38 | { 39 | if(matrix[0][i] == 0) 40 | { 41 | isFirstRowZero = true; 42 | break; 43 | } 44 | } 45 | 46 | // check for 0's except first row and column 47 | for(int i = 1; i < row; i++) 48 | { 49 | for(int j = 1; j < col; j++) 50 | { 51 | if(matrix[i][j] == 0) 52 | { 53 | // mark that row and column in first row and column 54 | matrix[i][0] = 0; 55 | matrix[0][j] = 0; 56 | } 57 | } 58 | } 59 | 60 | // for setting values 61 | for(int i = 1; i < row; i++) 62 | { 63 | for(int j = 1; j < col; j++) 64 | { 65 | // if first row and col contains 0 for that index 66 | if(matrix[i][0] == 0 || matrix[0][j] == 0) 67 | matrix[i][j] = 0; 68 | } 69 | } 70 | 71 | // for first column 72 | if(isFirstColZero == true) 73 | { 74 | for(int i = 0; i < row; i++) 75 | matrix[i][0] = 0; 76 | } 77 | 78 | // for first row 79 | if(isFirstRowZero == true) 80 | { 81 | for(int i = 0; i < col; i++) 82 | matrix[0][i] = 0; 83 | } 84 | } 85 | }; 86 | -------------------------------------------------------------------------------- /C++/Medium/75. Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 3 | We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. 4 | You must solve this problem without using the library's sort function. 5 | 6 | Example 1: 7 | 8 | Input: nums = [2,0,2,1,1,0] 9 | Output: [0,0,1,1,2,2] 10 | 11 | Example 2: 12 | 13 | Input: nums = [2,0,1] 14 | Output: [0,1,2] 15 | 16 | Constraints: 17 | 18 | n == nums.length 19 | 1 <= n <= 300 20 | nums[i] is either 0, 1, or 2. 21 | */ 22 | 23 | class Solution { 24 | public: 25 | void sortColors(vector& nums) { 26 | int low = 0; 27 | int mid = 0; 28 | int high = nums.size() - 1; 29 | 30 | while(mid<=high){ 31 | if(nums[mid] == 0){ 32 | swap(nums[low], nums[mid]); 33 | low++; 34 | mid++; 35 | } 36 | else if(nums[mid] == 1){ 37 | mid++; 38 | } 39 | else{ 40 | swap(nums[high], nums[mid]); 41 | high--; 42 | } 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/Medium/81. Search in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). 3 | 4 | Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. 5 | 6 | Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. 7 | 8 | You must decrease the overall operation steps as much as possible. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: nums = [2,5,6,0,0,1,2], target = 0 15 | Output: true 16 | Example 2: 17 | 18 | Input: nums = [2,5,6,0,0,1,2], target = 3 19 | Output: false 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= nums.length <= 5000 25 | -10^4 <= nums[i] <= 10^4 26 | nums is guaranteed to be rotated at some pivot. 27 | -10^4 <= target <= 10^4 28 | */ 29 | 30 | class Solution { 31 | public: 32 | bool search(vector& nums, int target) { 33 | int low=0,high=nums.size()-1; 34 | while(low<=high){ 35 | int mid = (low+high)/2; 36 | if(nums[mid]==target) return true; 37 | 38 | if((nums[low] == nums[mid]) && (nums[high] == nums[mid])) 39 | { 40 | low++; 41 | high--; 42 | } 43 | 44 | else if(nums[mid]>=nums[low]){ 45 | //left half is sorted 46 | if(target>=nums[low] && targetnums[mid] && target<=nums[high]) 54 | low = mid+1; 55 | else 56 | high = mid-1; 57 | } 58 | } 59 | return false; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /C++/Medium/852. Peak Index in a Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | An array arr a mountain if the following properties hold: 3 | 4 | arr.length >= 3 5 | There exists some i with 0 < i < arr.length - 1 such that: 6 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 7 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 8 | Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. 9 | 10 | You must solve it in O(log(arr.length)) time complexity. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: arr = [0,1,0] 17 | Output: 1 18 | Example 2: 19 | 20 | Input: arr = [0,2,1,0] 21 | Output: 1 22 | Example 3: 23 | 24 | Input: arr = [0,10,5,2] 25 | Output: 1 26 | 27 | 28 | Constraints: 29 | 30 | 3 <= arr.length <= 105 31 | 0 <= arr[i] <= 106 32 | arr is guaranteed to be a mountain array. 33 | */ 34 | 35 | class Solution { 36 | public: 37 | int peakIndexInMountainArray(vector& arr) { 38 | int i = 0; 39 | while(arr[i+1] > arr[i] && (i < arr.size())){ 40 | i++; 41 | } 42 | return i; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /C++/Medium/875. Koko Eating Bananas.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. 3 | 4 | Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. 5 | 6 | Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. 7 | 8 | Return the minimum integer k such that she can eat all the bananas within h hours. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: piles = [3,6,7,11], h = 8 15 | Output: 4 16 | Example 2: 17 | 18 | Input: piles = [30,11,23,4,20], h = 5 19 | Output: 30 20 | Example 3: 21 | 22 | Input: piles = [30,11,23,4,20], h = 6 23 | Output: 23 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= piles.length <= 104 29 | piles.length <= h <= 109 30 | 1 <= piles[i] <= 109 31 | */ 32 | 33 | class Solution { 34 | public: 35 | bool findHours(vector piles, long int k, int h){ 36 | long int hours = 0; 37 | for(int pile : piles){ 38 | int div = pile / k; 39 | hours += div; 40 | if(pile % k != 0) hours++; 41 | } 42 | return hours <= h; 43 | } 44 | 45 | int minEatingSpeed(vector& piles, int h) { 46 | sort(piles.begin(), piles.end()); 47 | int n = piles.size(); 48 | long int low = 1; 49 | long int high = piles[n-1]; 50 | 51 | while(low <= high){ 52 | long int mid = low + (high- low)/2; 53 | if(findHours(piles, mid, h)){ 54 | high = mid - 1; 55 | } 56 | else{ 57 | low = mid + 1; 58 | } 59 | } 60 | return low; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /C++/Medium/885. Spiral Matrix III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. 3 | You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. 4 | Return an array of coordinates representing the positions of the grid in the order you visited them. 5 | 6 | 7 | Example 1: 8 | 9 | Input: rows = 1, cols = 4, rStart = 0, cStart = 0 10 | Output: [[0,0],[0,1],[0,2],[0,3]] 11 | 12 | Example 2: 13 | 14 | Input: rows = 5, cols = 6, rStart = 1, cStart = 4 15 | Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= rows, cols <= 100 21 | 0 <= rStart < rows 22 | 0 <= cStart < cols 23 | */ 24 | 25 | class Solution { 26 | public: 27 | bool valid_to_push(int i, int j, int rows, int cols){ 28 | if(i>=0 && i=0 && j> spiralMatrixIII(int rows, int cols, int rStart, int cStart) { 33 | vector> ans; 34 | int counter, direction, checker; 35 | ans.push_back({rStart, cStart}); 36 | counter = 1; 37 | direction = 0; 38 | checker = 1; 39 | 40 | int i = rStart, j = cStart; 41 | while(counter != rows * cols){ 42 | if(direction == 0){ 43 | for(int k = 1; k<= checker; k++){ 44 | j++; 45 | if(valid_to_push(i,j,rows,cols)){ 46 | ans.push_back({i, j}); 47 | counter++; 48 | } 49 | } 50 | direction = 1; 51 | } 52 | if(direction == 1){ 53 | for(int k = 1; k<= checker; k++){ 54 | i++; 55 | if(valid_to_push(i,j,rows,cols)){ 56 | ans.push_back({i, j}); 57 | counter++; 58 | } 59 | } 60 | direction = 2; 61 | } 62 | checker++; 63 | if(direction == 2){ 64 | for(int k = 1; k<= checker; k++){ 65 | j--; 66 | if(valid_to_push(i,j,rows,cols)){ 67 | ans.push_back({i, j}); 68 | counter++; 69 | } 70 | } 71 | direction = 3; 72 | } 73 | if(direction == 3){ 74 | for(int k = 1; k<= checker; k++){ 75 | i--; 76 | if(valid_to_push(i,j,rows,cols)){ 77 | ans.push_back({i, j}); 78 | counter++; 79 | } 80 | } 81 | direction = 0; 82 | } 83 | checker++; 84 | } 85 | 86 | return ans; 87 | } 88 | }; 89 | -------------------------------------------------------------------------------- /C++/Medium/92. Reverse Linked List II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: head = [1,2,3,4,5], left = 2, right = 4 10 | Output: [1,4,3,2,5] 11 | Example 2: 12 | 13 | Input: head = [5], left = 1, right = 1 14 | Output: [5] 15 | 16 | 17 | Constraints: 18 | 19 | The number of nodes in the list is n. 20 | 1 <= n <= 500 21 | -500 <= Node.val <= 500 22 | 1 <= left <= right <= n 23 | 24 | */ 25 | class Solution { 26 | public: 27 | ListNode* reverse(ListNode* start, ListNode* end ){ 28 | 29 | ListNode *curr = start; 30 | ListNode *prev = NULL ; 31 | ListNode *forward = NULL; 32 | 33 | while(curr != end ){ 34 | 35 | forward = curr->next; 36 | curr -> next = prev; 37 | 38 | prev = curr; 39 | curr = forward; 40 | } 41 | 42 | return prev; 43 | } 44 | 45 | ListNode* reverseBetween(ListNode* head, int left, int right) { 46 | 47 | if(head->next==NULL || head==NULL){ 48 | return head; 49 | } 50 | 51 | ListNode *start=head; 52 | ListNode *end = head; 53 | ListNode *temp = start; 54 | ListNode* nextToEnd = NULL; 55 | if(left==1 && right==1){ 56 | return head; 57 | } 58 | int cnt = 1 ; 59 | 60 | while(cntnext; 63 | cnt++; 64 | } 65 | cnt = 1; 66 | while(cntnext; 68 | 69 | cnt++; 70 | } 71 | nextToEnd = end->next ; 72 | //for left = 1 73 | 74 | if(left==1 ){ 75 | head = reverse(start, nextToEnd); 76 | ListNode *tail = head; 77 | 78 | while(tail->next!=NULL){ 79 | tail=tail->next; 80 | } 81 | tail->next = nextToEnd ; 82 | return head; 83 | } 84 | 85 | temp->next = reverse(start, nextToEnd); 86 | 87 | ListNode *tail = head; 88 | 89 | while(tail->next!=NULL){ 90 | tail=tail->next; 91 | } 92 | tail->next = nextToEnd ; 93 | return head; 94 | } 95 | }; 96 | -------------------------------------------------------------------------------- /C++/Medium/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Medium** solved in the `C++` Programming Language 3 | -------------------------------------------------------------------------------- /C/Easy/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Easy** solved in the `C` Programming Language 3 | -------------------------------------------------------------------------------- /C/Hard/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Hard** solved in the `C` Programming Language 3 | -------------------------------------------------------------------------------- /C/Medium/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Medium** solved in the `C` Programming Language 3 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/muhammadanas0716/LeetCodeTorture/7fc9cba42c6bcc6ab5eec3f23d6cbafc51729277/Contributing.md -------------------------------------------------------------------------------- /Java/Easy/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Easy** solved in the `Java` Programming Language 3 | -------------------------------------------------------------------------------- /Java/Hard/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Hard** solved in the `Java` Programming Language 3 | -------------------------------------------------------------------------------- /Java/Medium/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Medium** solved in the `Java` Programming Language 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Muhammad Anas 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 | -------------------------------------------------------------------------------- /Learn.md: -------------------------------------------------------------------------------- 1 | This repo will help you solve some leetcode problems, I try my best to solve atleast one problem a day and I share my progress on Github as well as on Twitter. 2 | 3 | There are 3 folders in the repo, categorised by the LeetCode problem diffuculty level. 4 | * Easy 5 | * Medium 6 | * Hard 7 | 8 | You can always contibute and I'd be very happy if you would! 9 | -------------------------------------------------------------------------------- /Python/Easy/1. Two Sum.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 2 | 3 | # You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | # You can return the answer in any order. 6 | 7 | 8 | # Example: 9 | 10 | # Input: nums = [2,7,11,15], target = 9 11 | # Output: [0,1] 12 | # Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 13 | 14 | # Question Link: https://leetcode.com/problems/two-sum/ 15 | 16 | class Solution: 17 | def twoSum(self, nums, target): 18 | 19 | result_list = [] 20 | #Two for loops for selecting two numbers and check sum equal to target or not 21 | for i in range(len(nums)-1): 22 | for j in range(i, len(nums)): 23 | # j from i + 1; no need to check back elements it covers in i 24 | # Check sum == target or not 25 | if nums[i] + nums[j] == target: 26 | result_list.append(i) 27 | result_list.append(j) 28 | 29 | return result_list[:2] 30 | 31 | sol = Solution() 32 | print(sol.twoSum([2,7,11,15], 11)) 33 | -------------------------------------------------------------------------------- /Python/Easy/13. Roman to Integer.py: -------------------------------------------------------------------------------- 1 | # Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 2 | 3 | # Symbol Value 4 | # I 1 5 | # V 5 6 | # X 10 7 | # L 50 8 | # C 100 9 | # D 500 10 | # M 1000 11 | # For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. 12 | 13 | # Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 14 | 15 | # I can be placed before V (5) and X (10) to make 4 and 9. 16 | # X can be placed before L (50) and C (100) to make 40 and 90. 17 | # C can be placed before D (500) and M (1000) to make 400 and 900. 18 | # Given a roman numeral, convert it to an integer. 19 | 20 | 21 | 22 | # Example 1: 23 | 24 | # Input: s = "III" 25 | # Output: 3 26 | # Explanation: III = 3. 27 | # Example 2: 28 | 29 | # Input: s = "LVIII" 30 | # Output: 58 31 | # Explanation: L = 50, V= 5, III = 3. 32 | # Example 3: 33 | 34 | # Input: s = "MCMXCIV" 35 | # Output: 1994 36 | # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 37 | 38 | # Question Link: https://leetcode.com/problems/roman-to-integer/ 39 | 40 | class Solution: 41 | def romanToInt(self, s: str) -> int: 42 | roman_numerals = { 43 | "I" : 1, 44 | "V" : 5, 45 | "X" : 10, 46 | "L" : 50, 47 | "C" : 100, 48 | "D" : 500, 49 | "M" : 1000, 50 | } 51 | output = 0 52 | for i in range(len(s)): 53 | if i + 1 < len(s) and roman_numerals[s[i]] < roman_numerals[s[i + 1]]: 54 | output -= roman_numerals[s[i]] 55 | else: 56 | output += roman_numerals[s[i]] 57 | 58 | return output 59 | 60 | sol = Solution() 61 | print(sol.romanToInt("IV")) 62 | -------------------------------------------------------------------------------- /Python/Easy/1672. Richest Customer Wealth.py: -------------------------------------------------------------------------------- 1 | # You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. 2 | 3 | # A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: accounts = [[1,2,3],[3,2,1]] 10 | # Output: 6 11 | # Explanation: 12 | # 1st customer has wealth = 1 + 2 + 3 = 6 13 | # 2nd customer has wealth = 3 + 2 + 1 = 6 14 | # Both customers are considered the richest with a wealth of 6 each, so return 6. 15 | # Example 2: 16 | 17 | # Input: accounts = [[1,5],[7,3],[3,5]] 18 | # Output: 10 19 | # Explanation: 20 | # 1st customer has wealth = 6 21 | # 2nd customer has wealth = 10 22 | # 3rd customer has wealth = 8 23 | # The 2nd customer is the richest with a wealth of 10. 24 | 25 | # Question Link: https://leetcode.com/problems/richest-customer-wealth/ 26 | 27 | class Solution: 28 | def maximumWealth(self, accounts: list[list[int]]) -> int: 29 | maximum = [] 30 | for i in range(len(accounts)): 31 | maximum.append(sum(accounts[i])) 32 | return max(maximum) 33 | 34 | 35 | Sol = Solution() 36 | print(Sol.maximumWealth([[1,2,3],[3,2,1]])) -------------------------------------------------------------------------------- /Python/Easy/2259. Remove Digit From Number to Maximize Result.py: -------------------------------------------------------------------------------- 1 | # You are given a string number representing a positive integer and a character digit. 2 | 3 | # Return the resulting string after removing exactly one occurrence of digit from number 4 | # such that the value of the resulting string in decimal form is maximized. 5 | # The test cases are generated such that digit occurs at least once in number. 6 | 7 | # Example 1: 8 | # Input: number = "123", digit = "3" 9 | # Output: "12" 10 | # Explanation: There is only one '3' in "123". After removing '3', the result is "12". 11 | 12 | # Question link: https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/ 13 | 14 | # Solution: 15 | 16 | class Solution: 17 | def removeDigit(self, number: str, digit: str) -> str: 18 | result = 0 19 | n = 0 20 | 21 | for i in range(len(number)): 22 | if number[i] == digit: 23 | n = number[:i] + number[i+1:] 24 | if int(n) > result: 25 | result = int(n) 26 | 27 | return str(result) 28 | 29 | 30 | sol = Solution() 31 | print(sol.removeDigit("123", "3")) 32 | -------------------------------------------------------------------------------- /Python/Easy/26. Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | # Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. 2 | 3 | # Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. 4 | 5 | # Return k after placing the final result in the first k slots of nums. 6 | 7 | # Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | # Custom Judge: 10 | 11 | # The judge will test your solution with the following code: 12 | 13 | # int[] nums = [...]; // Input array 14 | # int[] expectedNums = [...]; // The expected answer with correct length 15 | 16 | # int k = removeDuplicates(nums); // Calls your implementation 17 | 18 | # assert k == expectedNums.length; 19 | # for (int i = 0; i < k; i++) { 20 | # assert nums[i] == expectedNums[i]; 21 | # } 22 | # If all assertions pass, then your solution will be accepted. 23 | 24 | 25 | 26 | # Example 1: 27 | # Input: nums = [1,1,2] 28 | # Output: 2, nums = [1,2,_] 29 | # Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. 30 | # It does not matter what you leave beyond the returned k (hence they are underscores). 31 | 32 | 33 | # Example 2: 34 | # Input: nums = [0,0,1,1,1,2,2,3,3,4] 35 | # Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] 36 | # Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. 37 | # It does not matter what you leave beyond the returned k (hence they are underscores). 38 | 39 | # Question Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array 40 | 41 | class Solution: 42 | def removeDuplicates(self, nums: list[int]) -> int: 43 | j = 1 44 | for i in range(1, len(nums)): 45 | if nums[i] != nums[i-1]: 46 | nums[j] = nums[i] 47 | j += 1 48 | 49 | return j 50 | 51 | 52 | 53 | sol = Solution().removeDuplicates([1, 1, 2]) 54 | print(sol) -------------------------------------------------------------------------------- /Python/Easy/412. Fizz Buzz.py: -------------------------------------------------------------------------------- 1 | # Given an integer n, return a string array answer (1-indexed) where: 2 | 3 | # answer[i] == "FizzBuzz" if i is divisible by 3 and 5. 4 | # answer[i] == "Fizz" if i is divisible by 3. 5 | # answer[i] == "Buzz" if i is divisible by 5. 6 | # answer[i] == i (as a string) if none of the above conditions are true. 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: n = 3 12 | # Output: ["1","2","Fizz"] 13 | # Example 2: 14 | 15 | # Input: n = 5 16 | # Output: ["1","2","Fizz","4","Buzz"] 17 | # Example 3: 18 | 19 | # Input: n = 15 20 | # Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] 21 | 22 | # Question Link: https://leetcode.com/problems/fizz-buzz/ 23 | 24 | class Solution: 25 | def fizzBuzz(self, n: int): 26 | output = [] 27 | for i in range(1, n+1): 28 | if (i % 5 == 0) and (i % 3 == 0): 29 | output.append("FizzBuzz") 30 | elif (i % 3 == 0): 31 | output.append("Fizz") 32 | elif (i % 5 == 0): 33 | output.append("Buzz") 34 | else: 35 | output.append(str(i)) 36 | 37 | return output 38 | 39 | Sol = Solution() 40 | print(Sol.fizzBuzz(15)) -------------------------------------------------------------------------------- /Python/Easy/9. Palindrome Number.py: -------------------------------------------------------------------------------- 1 | # Given an integer x, return true if x is palindrome integer. 2 | 3 | # An integer is a palindrome when it reads the same backward as forward. 4 | 5 | # For example, 121 is a palindrome while 123 is not. 6 | 7 | 8 | # Example 1: 9 | 10 | # Input: x = 121 11 | # Output: true 12 | # Explanation: 121 reads as 121 from left to right and from right to left. 13 | # Example 2: 14 | 15 | # Input: x = -121 16 | # Output: false 17 | # Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 18 | 19 | 20 | # Question Link: https://leetcode.com/problems/palindrome-number/ 21 | 22 | class Solution: 23 | def isPalindrome(self, x: int) -> bool: 24 | # Orginal 25 | x_test = str(x) 26 | 27 | # Reverse the number 28 | x = str(x)[::-1] 29 | 30 | # Logic 31 | if x == x_test: 32 | return "true" 33 | else: 34 | return "false" 35 | 36 | 37 | 38 | sol = Solution() 39 | print(sol.isPalindrome(10)) -------------------------------------------------------------------------------- /Python/Easy/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Easy** solved in the `Python` Programming Language 3 | -------------------------------------------------------------------------------- /Python/Hard/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Hard** solved in the `Python` Programming Language 3 | -------------------------------------------------------------------------------- /Python/Medium/Readme.md: -------------------------------------------------------------------------------- 1 | ## Who am I 2 | I'm a folder dedicated to LeetCode Problems - diffuculty **Medium** solved in the `Python` Programming Language 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Torture 2 | Some LeetCode problems I have solved for fun. No, it's pure torture. 3 | 4 | Here are some of the LeetCode Problems that I have now started solving. I try to solve atleast one problem a day and I thought maybe some of you would benefit from the solutions thats why I started uploading them here. Enjoy! 5 | 6 | 7 | ### Files Description 8 | | Path | Description 9 | | :--- | :---------- 10 | | LeetCodeTorture | Main folder. 11 | | └  Programming Language Name | Specified prgramming language folder for respective code 12 | | Readme.md | The **Readme** file for this project. 13 | | Learn.md | This file contains the main purpose of this project and how you could be a part of this! 14 | | License | The License file for this project, which is the **MIT License** 15 | 16 | **Note:** Each Programming folder contains 3 folders, relating to the 3 diffuculy levels on LeetCode: 17 | * Easy 18 | * Medium 19 | * Hard 20 | 21 | ## Contributing 22 | Currently all of the code here is in Python or C++ Programming language and I'd be very happy if you could solve these problems in other languages too! It'd be really awesome, and I'd heavily appreciate it! 23 | 24 | If you want to start solving LeetCode problems in another programming langauge, please create a folder for it, or request me to do so. Both ways it'll be fine! Looking forward to your contribution. 25 | 26 | ## Connect with me 27 | 28 | [![website](https://img.icons8.com/color/48/000000/twitter--v1.png)](https://twitter.com/MuhammadAnas707#gh-light-mode-only) 29 | [![website](https://img.icons8.com/color/48/000000/twitter--v1.png)](https://twitter.com/MuhammadAnas707#gh-dark-mode-only) 30 |    31 | [![website](https://img.icons8.com/color/48/000000/medium-monogram.png)](https://medium.com/@muhammadanas0716#gh-light-mode-only) 32 | [![website](https://img.icons8.com/color/48/000000/medium-monogram.png)](https://medium.com/@muhammadanas0716#gh-dark-mode-only) 33 |    34 | [![website](https://img.icons8.com/color/48/000000/linkedin.png)](https://www.linkedin.com/in/muhammad-anas-63744b235/#gh-light-mode-only) 35 | [![website](https://img.icons8.com/color/48/000000/linkedin.png)](https://www.linkedin.com/in/muhammad-anas-63744b235/#gh-dark-mode-only) 36 | --------------------------------------------------------------------------------