diff --git a/120.Triangle.cpp b/120.Triangle.cpp new file mode 100644 index 0000000..0e61ce2 --- /dev/null +++ b/120.Triangle.cpp @@ -0,0 +1,89 @@ + + + + +//1. Recursion + + + // Recursion *** Will Give TLE *** + + + int solve(int i, int j, int n, vector>&triangle) { + if(i == n - 1) + return triangle[i][j]; + int bottom = triangle[i][j] + solve(i+1, j, n, triangle); + int bottom_right = triangle[i][j] + solve(i+1, j+1, n, triangle); + return min(bottom, bottom_right); + } + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + return solve(0, 0, n, triangle); + } + + +//2. Memoization + + + // Memoization + int solve(int i, int j, int n, vector>&triangle, vector>&dp) { + if(i == n - 1) + return triangle[i][j]; + if(dp[i][j] != -1) + return dp[i][j]; + int bottom = triangle[i][j] + solve(i+1, j, n, triangle, dp); + int bottom_right = triangle[i][j] + solve(i+1, j+1, n, triangle, dp); + return dp[i][j] = min(bottom, bottom_right); + } + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + vector>dp(n, vector(n, -1)); + return solve(0, 0, n, triangle, dp); + + } + + +// 3. Tabulation + + // Tabulation + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + vector>dp(n, vector(n, -1)); + for(int i = 0; i < n; i++) + dp[n-1][i] = triangle[n-1][i]; + for(int i = n-2; i >= 0; i--) { + for(int j = i; j >= 0; j--) { + int up = triangle[i][j] + dp[i+1][j]; + int up_left = triangle[i][j] + dp[i+1][j+1]; + dp[i][j] = min(up, up_left); + } + } + return dp[0][0]; + } + + +//4. Space Optimal + +// Space Optimization + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + vectornext(n); + for(int i = n-1; i >= 0; i--) { + vectorcurr(n); + for(int j = i; j >= 0; j--) { + if(i == n-1) + curr[j] = triangle[i][j]; + else { + int up = triangle[i][j] + next[j]; + int up_left = triangle[i][j] + next[j+1]; + curr[j] = min(up, up_left); + } + } + next = curr; + } + return next[0]; + } + + + + + diff --git a/140.-Word-Break-II.java b/140.-Word-Break-II.java new file mode 100644 index 0000000..b6278a1 --- /dev/null +++ b/140.-Word-Break-II.java @@ -0,0 +1,29 @@ +public class Solution { + HashMap> dp = new HashMap<>(); + + public List wordBreak(String s, Set wordDict) { + int maxLength = -1; + for(String ss : wordDict) maxLength = Math.max(maxLength, ss.length()); + return addSpaces(s, wordDict, 0, maxLength); + } + + private List addSpaces(String s, Set wordDict, int start, int max){ + List words = new ArrayList<>(); + if(start == s.length()) { + words.add(""); + return words; + } + for(int i = start + 1; i <= max + start && i <= s.length(); i++){ + String temp = s.substring(start, i); + if(wordDict.contains(temp)){ + List ll; + if(dp.containsKey(i)) ll = dp.get(i); + else ll = addSpaces(s, wordDict, i, max); + for(String ss : ll) words.add(temp + (ss.equals("") ? "" : " ") + ss); + } + + } + dp.put(start, words); + return words; + } +} diff --git a/140_Word_Break_II.cpp b/140_Word_Break_II.cpp new file mode 100644 index 0000000..0242124 --- /dev/null +++ b/140_Word_Break_II.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + + void f(int i, int j, string s, vector&wordDict, int n, vector&ans, map&m, string &temp) { + + if(i>=n && j>=n) { + ans.push_back(temp); + return; + } + if(j>=n) return; + string str = s.substr(i, j-i+1); + if(m.find(str)!=m.end()) { + string st = temp; + temp+=str; + if(j!=n-1) temp+=" "; + f(j+1, j+1, s, wordDict, n, ans, m, temp); + temp = st; + } + f(i, j+1, s, wordDict, n, ans, m, temp); + } + + vector wordBreak(string s, vector& wordDict) { + int n = s.size(); + map m; + for(int i=0; i ans; + string temp=""; + f(0, 0, s, wordDict, n, ans, m, temp); + return ans; + } +}; diff --git a/146_LRU_Cache.cpp b/146_LRU_Cache.cpp new file mode 100644 index 0000000..d2dd741 --- /dev/null +++ b/146_LRU_Cache.cpp @@ -0,0 +1,69 @@ +class LRUCache { +public: + class node{ + public: + int k; + int v; + node *prev; + node *next; + node(int kk,int vv){ + k=kk; + v=vv; + } + }; + + node* head=new node(-1,-1); + node* tail=new node(-1,-1); + + + int cap; + unordered_map m; + + LRUCache(int capacity) { + cap=capacity; + head->next=tail; + tail->prev=head; + } + + void insertNode(node* newNode){ + node* temp=head->next; + newNode->next=temp; + newNode->prev=head; + head->next=newNode; + temp->prev=newNode; + } + + void deleteNode(node* delNode){ + node* delPrev=delNode->prev; + node* delNext=delNode->next; + delPrev->next=delNext; + delNext->prev=delPrev; + } + + int get(int key) { + if(m.find(key)!=m.end()){ + node* resNode=m[key]; + int res=resNode->v; + m.erase(key); + deleteNode(resNode); + insertNode(resNode); + m[key]=head->next; + return res; + } + return -1; + } + + void put(int key, int value) { + if(m.find(key)!=m.end()){ + node* exitingNode = m[key]; + m.erase(key); + deleteNode(exitingNode); + } + if(m.size() == cap){ + m.erase(tail->prev->k); + deleteNode(tail-> prev); + } + insertNode(new node(key,value)); + m[key]=head->next; + } +}; diff --git a/1695.Maximum_Erasure_Value.cpp b/1695.Maximum_Erasure_Value.cpp new file mode 100644 index 0000000..086d145 --- /dev/null +++ b/1695.Maximum_Erasure_Value.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int maximumUniqueSubarray(vector& nums) { + int curr_sum=0, res=0; + + //set to store the elements + unordered_set st; + + int i=0,j=0; + while(j0) { + //Removing the ith element untill we reach the repeating element + st.erase(nums[i]); + curr_sum-=nums[i]; + i++; + } + //Add the current element to set and curr_sum value + curr_sum+=nums[j]; + st.insert(nums[j++]); + + //res variable to keep track of largest curr_sum encountered till now... + res = max(res, curr_sum); + } + + return res; + } +}; \ No newline at end of file diff --git a/33. Search in Rotated Sorted Array.py b/33. Search in Rotated Sorted Array.py new file mode 100644 index 0000000..1352e4f --- /dev/null +++ b/33. Search in Rotated Sorted Array.py @@ -0,0 +1,19 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + l,r = 0,len(nums)-1 + while(l<=r): + mid = (l+r)//2 + if target == nums[mid]: + return mid + + if nums[l]<=nums[mid]: + if target > nums[mid] or target < nums[l]: + l = mid + 1 + else: + r = mid - 1 + else: + if target < nums[mid] or target > nums[r]: + r = mid - 1 + else: + l = mid + 1 + return -1 diff --git a/Combination Sum II/combination_sum_II.c b/Combination Sum II/combination_sum_II.c new file mode 100644 index 0000000..b299b22 --- /dev/null +++ b/Combination Sum II/combination_sum_II.c @@ -0,0 +1,66 @@ +/* Sorts the array in ascending order */ +int sortFunc(const void* a, const void* b) { + return *((int*)a) - *((int*)b); +} + +void helper(int* candidates, int candidatesSize, int target, int index, int* current, int currentLength, int* returnSize, int** returnColumnSizes, int*** answer) { + /* Track the previous candidate to avoid duplicate solutions*/ + int prevCan = 0; + + /* Loop through all possible candidates to add to the solution */ + for (int i = index; i < candidatesSize; i++) { + + /* If the candidate matches the target, add to the answer */ + if (candidates[i] == target) { + (*returnSize)++; + + /* Allocate memory for new answer */ + *answer = (int**)realloc(*answer, (*returnSize) * sizeof(int*)); + (*answer)[(*returnSize) - 1] = (int*)malloc((currentLength+1) * sizeof(int)); + + /* Copy data into new answer */ + memcpy((*answer)[(*returnSize) - 1], current, currentLength * sizeof(int)); + (*answer)[(*returnSize) - 1][currentLength] = candidates[i]; + + /* Update the returnColumnSizes array */ + (*returnColumnSizes) = (int*)realloc((*returnColumnSizes), (*returnSize) * sizeof(int)); + (*returnColumnSizes)[(*returnSize) - 1] = currentLength + 1; + + /* Break to avoid duplicate answers */ + /* Since the candidates are sorted, any next candidates will be too large */ + break; + } + + /* If the candidate could possibly work, add it to the current answer and recursively call the helper */ + else if (candidates[i] <= (target / 2) && candidates[i] != prevCan) { + current[currentLength] = candidates[i]; + helper(candidates, candidatesSize, target - candidates[i], i + 1, current, currentLength + 1, returnSize, returnColumnSizes, answer); + prevCan = candidates[i]; + } + + /* Since the list is sorted, break once the candidate is too large */ + else if (candidates[i] > target) break; + } +} + +int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes){ + + /* Sort the candidates to group duplicates together */ + qsort(candidates, candidatesSize, sizeof(int), sortFunc); + + /* Array to store the current solution */ + int* current = (int*)malloc(100*sizeof(int)); + int currentLength = 0; + + /* Allocate initial memory to answer and returnColumnSizes */ + int** answer = (int**)malloc(sizeof(int*)); + (*returnColumnSizes) = (int*)malloc(sizeof(int)); + + (*returnSize) = 0; + + /* Call the helper with our initial conditions */ + helper(candidates, candidatesSize, target, 0, current, currentLength, returnSize, returnColumnSizes, &answer); + + free(current); + return answer; +} \ No newline at end of file diff --git a/Combination Sum II/combination_sum_II.py b/Combination Sum II/combination_sum_II.py new file mode 100644 index 0000000..e69de29 diff --git a/Delete-Operation-for-Two-Strings/CPP Solution.cpp b/Delete-Operation-for-Two-Strings/CPP Solution.cpp new file mode 100644 index 0000000..8bcf2c8 --- /dev/null +++ b/Delete-Operation-for-Two-Strings/CPP Solution.cpp @@ -0,0 +1,33 @@ +#include + +using namespace std; + +class Solution { +public: + int minDistance(string word1, string word2) { + // Bottom up approach + int m, n; + m = word1.length(); + n = word2.length(); + int dp[m + 1][n + 1]; + + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + // we have to add all the remaining char in word2 + if (i == 0) + dp[i][j] = j; + // We have to delete all the remaining characters from word 1 + else if (j == 0) + dp[i][j] = i; + // If in the memo dict return the val + else if (word1[i - 1] == word2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + + else + dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j]); + } + } + + return dp[m][n]; + } +}; \ No newline at end of file diff --git a/Delete-Operation-for-Two-Strings/Delete-Operation-for-Two-Strings Delete-Operation-for-Two-Strings.py b/Delete-Operation-for-Two-Strings/Delete-Operation-for-Two-Strings Delete-Operation-for-Two-Strings.py new file mode 100644 index 0000000..61069c9 --- /dev/null +++ b/Delete-Operation-for-Two-Strings/Delete-Operation-for-Two-Strings Delete-Operation-for-Two-Strings.py @@ -0,0 +1,19 @@ +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + m = len(word1) + n = len(word2) + dp = [0] * (n + 1) + + for j in range(n + 1): + dp[j] = j + + for i in range(1, m + 1): + newDp = [i] + [0] * n + for j in range(1, n + 1): + if word1[i - 1] == word2[j - 1]: + newDp[j] = dp[j - 1] + else: + newDp[j] = min(newDp[j - 1], dp[j]) + 1 + dp = newDp + + return dp[n] diff --git a/Delete-Operation-for-Two-Strings/Delete-Operation-for-Two-Strings.java b/Delete-Operation-for-Two-Strings/Delete-Operation-for-Two-Strings.java new file mode 100644 index 0000000..1d6e2d1 --- /dev/null +++ b/Delete-Operation-for-Two-Strings/Delete-Operation-for-Two-Strings.java @@ -0,0 +1,26 @@ +class Solution { + public int minDistance(String word1, String word2) { + int[][] result = new int[word1.length()][word2.length()]; + for(int[] row : result){ + Arrays.fill(row, -1); + } + return helper(word1, word1.length() -1 ,word2, word2.length() -1, result); + + } + private static int helper(String word1, int idx1, String word2, int idx2, int[][] result) { + if(idx1<0){ + return idx2 +1; + } else if(idx2<0){ + return idx1 +1; + } + if(result[idx1][idx2] == -1){ + if(word1.charAt(idx1) == word2.charAt(idx2)){ + result[idx1][idx2] = helper(word1, idx1-1, word2, idx2-1, result); + } else{ + result[idx1][idx2] = 1+ Math.min(helper(word1, idx1-1, word2, idx2, result), helper(word1, idx1, word2, idx2 -1, result)); + } + + } + return result[idx1][idx2]; + } +} diff --git a/Delete-Operation-for-Two-Strings/DeleteOperationForTwoStrings.java b/Delete-Operation-for-Two-Strings/DeleteOperationForTwoStrings.java new file mode 100644 index 0000000..0a23960 --- /dev/null +++ b/Delete-Operation-for-Two-Strings/DeleteOperationForTwoStrings.java @@ -0,0 +1,28 @@ +class Solution { + int dp[][]; + public int minDistance(String word1, String word2) { + dp = new int[word1.length()+1][word2.length()+1]; + for(int[] temp : dp){ + Arrays.fill(temp,-1); + } + + int common = lcs(word1, word2, word1.length(), word2.length()); + return (word1.length()-common)+(word2.length()-common); + } + + int lcs(String s1, String s2, int len1, int len2){ + if(len1 == 0 || len2 == 0) return 0; + if(dp[len1][len2] != -1) return dp[len1][len2]; + else { + if(s1.charAt(len1-1) == s2.charAt(len2-1)){ +// list.add(s1.charAt(len1-1)); + dp[len1][len2] = 1 + lcs(s1,s2, len1 - 1, len2 - 1); + } + else{ + dp[len1][len2]=Math.max(lcs(s1,s2,len1-1,len2),lcs(s1,s2,len1,len2-1)); + } + + return dp[len1][len2]; + } + } +} \ No newline at end of file diff --git a/Design Linked List.cpp b/Design Linked List.cpp new file mode 100644 index 0000000..f80b358 --- /dev/null +++ b/Design Linked List.cpp @@ -0,0 +1,119 @@ +class MyLinkedList { +public: + MyLinkedList() { + head = tail = nullptr; + size = 0; + } + + ~MyLinkedList() + { + ListNode* tmp; + while (head) + { + tmp = head; + head = head->next; + delete tmp; + } + } + + int get(int index) const { + if (index >= size) + return -1; + + ListNode* curr = head; + while (index--) + curr = curr->next; + + return curr->val; + } + + void addAtHead(int val) { + ListNode* tmp = new ListNode(val); + tmp->next = head; + head = tmp; + + tail = tail == nullptr ? head : tail; + ++size; + } + + void addAtTail(int val) { + ListNode* tmp = new ListNode(val); + + if (tail == nullptr) + tail = head = tmp; + else + tail->next = tmp, tail = tmp; + + ++size; + } + + void addAtIndex(int index, int val) { + if (index <= size) + { + if (index == 0) + addAtHead(val); + + else if (index == size) + addAtTail(val); + + else + { + ListNode* curr = head; + while (--index >= 1) + curr = curr->next; + + ListNode *tmp = new ListNode(val), *nxt = curr->next; + curr->next = tmp; + tmp->next = nxt; + + ++size; + } + + } + } + + void deleteAtIndex(int index) { + if (index < size) + { + ListNode* tmp; + + if (index == 0) + { + tmp = head; + head = head->next; + + if (head == nullptr) + tail = nullptr; + } + + else + { + ListNode* curr = head; + while (--index) + curr = curr->next; + + tmp = curr->next; + curr->next = curr->next->next; + + if (tail == tmp) + tail = curr; + } + + delete tmp; + --size; + } + } + +private: + class ListNode + { + public: + ListNode(const int& _val) :val(_val), next(nullptr) {} + + ListNode* next; + int val; + }; + + int size; + ListNode *head, *tail; +}; diff --git a/Find Median From Data Stream.cpp b/Find Median From Data Stream.cpp new file mode 100644 index 0000000..dcb5441 --- /dev/null +++ b/Find Median From Data Stream.cpp @@ -0,0 +1,35 @@ +class MedianFinder { + +public: + priority_queue small; + priority_queue,greater> large; + MedianFinder() { + + } + + void addNum(int num) { + if(small.empty() || num < (int)small.top()) small.push(num); + else large.push(num); + + if(small.size() > large.size() && small.size() - large.size() > 1) { + int x = small.top(); + large.push(x); + small.pop(); + } + else if(large.size() > small.size() && large.size() - small.size() > 1) { + int x = large.top(); + large.pop(); + small.push(x); + } + return ; + } + + double findMedian() { + int n = large.size() + small.size(); + if(n%2 == 1 ) { + if(small.size() > large.size()) return small.top(); + else return large.top(); + } + return (double)(small.top() + large.top())/2.0; + } +}; diff --git a/First_Missing_Positive.cpp b/First_Missing_Positive.cpp new file mode 100644 index 0000000..da3899b --- /dev/null +++ b/First_Missing_Positive.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int firstMissingPositive(vector& nums) { + unordered_map mp; + int ans; + int mx=0; + for(int i=0;i interval[1]) { + result.push(interval) + } else if(newInterval[1] < interval[0]) { + result = result.concat([newInterval], intervals.slice(i)) + isFinished = true + break; + } else { + newInterval[0] = Math.min(newInterval[0], interval[0]) + newInterval[1] = Math.max(newInterval[1], interval[1]) + } + } + + if(!isFinished) result.push(newInterval) + + return result +} + +/* + intervals = [[1, 3], [6, 9]] + newInterval = [2, 5] + console.log(insertInterval(intervals, newInterval)) // [[1, 5], [6, 9]] +*/ diff --git a/Insert-Interval/Insert-Interval.java b/Insert-Interval/Insert-Interval.java new file mode 100644 index 0000000..8386821 --- /dev/null +++ b/Insert-Interval/Insert-Interval.java @@ -0,0 +1,35 @@ + class Solution +{ + public int[][] insert(int[][] intervals, int[] newInterval) + { + int n = intervals.length; + List r = new ArrayList(); + + for (int[] inter : intervals) + { + if (is_overlap(inter, newInterval)) + { + newInterval[0] = Math.min(newInterval[0], inter[0]); + newInterval[1] = Math.max(newInterval[1], inter[1]); + } + else + { + r.add(inter); + } + } + + r.add(newInterval); + int[][] t = new int[r.size()][2]; + for (int i = 0; i < t.length; ++i) t[i] = r.get(i); + Arrays.sort(t, (a, b) -> a[0] - b[0]); + return t; + } + + boolean is_overlap(int[] a, int[] b) + { + return !(a[1] < b[0] || a[0] > b[1]); + } +} + + + diff --git a/Insert-Interval/Insert_interval.py b/Insert-Interval/Insert_interval.py new file mode 100644 index 0000000..c92a4aa --- /dev/null +++ b/Insert-Interval/Insert_interval.py @@ -0,0 +1,19 @@ +class Solution: + def insert( + self, intervals: List[List[int]], newInterval: List[int] + ) -> List[List[int]]: + res = [] + + for i in range(len(intervals)): + if newInterval[1] < intervals[i][0]: + res.append(newInterval) + return res + intervals[i:] + elif newInterval[0] > intervals[i][1]: + res.append(intervals[i]) + else: + newInterval = [ + min(newInterval[0], intervals[i][0]), + max(newInterval[1], intervals[i][1]), + ] + res.append(newInterval) + return res diff --git a/Insert-Interval/Solution.java b/Insert-Interval/Solution.java new file mode 100644 index 0000000..e4e9200 --- /dev/null +++ b/Insert-Interval/Solution.java @@ -0,0 +1,30 @@ +import java.util.*; + +public class Solution { + public int[][] insert(int[][] intervals, int[] newInterval) { + LinkedList mergedIntervals = new LinkedList<>(); + boolean inserted = false; + + for (int[] interval : intervals) { + if (!inserted && newInterval[0] < interval[0]) { + mergeInterval(mergedIntervals, newInterval); + inserted = true; + } + mergeInterval(mergedIntervals, interval); + } + + if (!inserted) { + mergeInterval(mergedIntervals, newInterval); + } + + return mergedIntervals.toArray(new int[mergedIntervals.size()][]); + } + + private void mergeInterval(LinkedList mergedIntervals, int[] interval) { + if (mergedIntervals.isEmpty() || mergedIntervals.getLast()[1] < interval[0]) { + mergedIntervals.add(interval); + } else { + mergedIntervals.getLast()[1] = Math.max(mergedIntervals.getLast()[1], interval[1]); + } + } +} \ No newline at end of file diff --git a/K Highest Ranked Items Within a Price Range.cpp b/K Highest Ranked Items Within a Price Range.cpp new file mode 100644 index 0000000..39e813b --- /dev/null +++ b/K Highest Ranked Items Within a Price Range.cpp @@ -0,0 +1,80 @@ +vector> highestRankedKItems(vector> &grid, vector &pricing, vector &start, int k) +{ + int n = grid.size(); + int m = grid[0].size(); + // MAKE DP TO CHECK THAT WE DO NOT REVISIT THE SAME INDEX + // IF WE VISIT THAT INDEX WE MAKE IT TRUE + vector> dp(n, vector(m, 0)); + + int array1[4] = {0, 0, 1, -1}; + int array2[4] = {1, -1, 0, 0}; + + // IN THIS ARRAY WE STORE + // ({DISTANCE , PRICE , ROW INDEX , COLUM INDEX }) + vector> v; + int distance = 0; + queue> q; + // PUSH STARTING INDEX IN QUEUE + q.push(make_pair(start[0], start[1])); + int xx = start[0]; + int yy = start[1]; + // CHECKING IF WE PUSH STARING INDEX IN OUR VECTOR + if (xx >= 0 && yy >= 0 && xx < n && yy < m && dp[xx][yy] == 0 && grid[xx][yy] >= pricing[0] && grid[xx][yy] <= pricing[1]) + { + + v.push_back({0, grid[xx][yy], xx, yy}); + } + // MAKING OUR STARTING INDEX TRUE IN OUT DP ARRAY + dp[start[0]][start[1]] = 1; + + // SIMPLE BFS AND CHECKING THE SAME CONDITION THAT WE CHECK FOR OUR STARTING INDEX + while (!q.empty()) + { + distance += 1; + + int size = q.size(); + for (int i = 0; i < size; i++) + { + int a = q.front().first; + int b = q.front().second; + q.pop(); + + for (int j = 0; j < 4; j++) + { + int x = a + array1[j]; + int y = b + array2[j]; + // CONDTION CHECK + if (x >= 0 && y >= 0 && x < n && y < m && dp[x][y] == 0 && grid[x][y] >= pricing[0] && grid[x][y] <= pricing[1]) + { + + q.push(make_pair(x, y)); + dp[x][y] = 1; + v.push_back({distance, grid[x][y], x, y}); + + // IF OUR CONDITION IS FAIL + // IF NOT VISITED AND GRID[X][Y] IS NOT EQUAL TO ZERO THAN WE MOVE TO THAT INDEX, THAT'S WHY WE PUSH IT IN QUEUE BUT NOT IN OUR VECTOR v + } + else if (x >= 0 && y >= 0 && x < n && y < m && grid[x][y] != 0 && dp[x][y] == 0) + { + + dp[x][y] = 1; + q.push(make_pair(x, y)); + } + } + } + } + + vector> ans; + // sort our vector v to get our minimum ans according to question conditions + sort(v.begin(), v.end()); + + int tt = v.size(); + + int p = min(k, tt); + for (int i = 0; i < p; i++) + { + ans.push_back({v[i][2], v[i][3]}); + } + + return ans; +} \ No newline at end of file diff --git a/K Highest Ranked Items Within a Price Range/highestRankedKItems.java b/K Highest Ranked Items Within a Price Range/highestRankedKItems.java new file mode 100644 index 0000000..28a23f5 --- /dev/null +++ b/K Highest Ranked Items Within a Price Range/highestRankedKItems.java @@ -0,0 +1,47 @@ +class Solution { + public List> highestRankedKItems(int[][] grid, int[] range, int[] start, int k) { + int n=grid.length, m=grid[0].length; + boolean vis[][] = new boolean[n][m]; + int dir[] = new int[]{0, 1, 0, -1, 0}; + Queue q = new LinkedList<>(); + q.offer(start); + vis[start[0]][start[1]]=true; + List candidate = new ArrayList<>(); // if in [lower, upper] add to list + int dist=0; + while(!q.isEmpty()){ + int size = q.size(); + while(size --> 0){ + int p[] = q.poll(); + int val = grid[p[0]][p[1]]; + if(val > 1 && range[0] <= val && val <= range[1]){ // if value is valid + candidate.add(new int[]{p[0], p[1], dist}); + } + for(int d=0; d<4; d++){ // check all 4 directions + int x = p[0] + dir[d]; + int y = p[1] + dir[d+1]; + if(x>=0 && x=0 && y{ + if(a[2] != b[2]) return Integer.compare(a[2], b[2]); // check distance + int price1=grid[a[0]][a[1]]; + int price2=grid[b[0]][b[1]]; + if(price1 != price2) return Integer.compare(price1, price2); // price + if(a[0] != b[0]) return Integer.compare(a[0], b[0]); // rows + return Integer.compare(a[1], b[1]); // columns + }); + List> res = new ArrayList<>(); + for(int i=0; i 0; i++){ // take atmost k value as result + int p[]=candidate.get(i); + List temp = new ArrayList<>(); + temp.add(p[0]);temp.add(p[1]); + res.add(temp); + } + return res; + } +} \ No newline at end of file diff --git a/K Highest Ranked Items Within a Price Range/kHighestRankedItems.cpp b/K Highest Ranked Items Within a Price Range/kHighestRankedItems.cpp new file mode 100644 index 0000000..81818fc --- /dev/null +++ b/K Highest Ranked Items Within a Price Range/kHighestRankedItems.cpp @@ -0,0 +1,49 @@ +using heapType = pair, pair>; + +class Solution { +public: + vector> highestRankedKItems(vector>& grid, vector& pricing, vector& start, int k) { + // support variables + int qLen = 1, val, x, y, maxX = grid[0].size() - 1, maxY = grid.size() - 1, dist = -1; + queue> q{{{start[1], start[0]}}}; + priority_queue> best; + // BFS routine + while (qLen && best.size() < k) { + // exploring the current layer + while (qLen--) { + // getting the current point and popping it out of q + auto curr = q.front(); + x = curr.first, y = curr.second; + q.pop(); + val = grid[y][x]; + // moving out if we already visited this one + if (val == -1) continue; + // marking as visited + grid[y][x] = -1; + // updating the k best + if (val >= pricing[0] && val <= pricing[1]) { + best.push({{dist, val}, {y, x}}); + if (best.size() > k) { + best.pop(); + } + } + // preparing q for the next run + if (x && grid[y][x - 1] > 0) q.push({x - 1, y}); + if (y && grid[y - 1][x] > 0) q.push({x, y - 1}); + if (x < maxX && grid[y][x + 1] > 0) q.push({x + 1, y}); + if (y < maxY && grid[y + 1][x] > 0) q.push({x, y + 1}); + } + // updating distance and q to check if we still need to run and in case with how many elements + dist++; + qLen = q.size(); + } + // creating and populating res + val = best.size() - 1; + vector> res(best.size()); + while (best.size()) { + res[val--] = {best.top().second.first, best.top().second.second}; + best.pop(); + } + return res; + } +}; diff --git a/LRU-Cache.cpp b/LRU-Cache.cpp new file mode 100644 index 0000000..d2dd741 --- /dev/null +++ b/LRU-Cache.cpp @@ -0,0 +1,69 @@ +class LRUCache { +public: + class node{ + public: + int k; + int v; + node *prev; + node *next; + node(int kk,int vv){ + k=kk; + v=vv; + } + }; + + node* head=new node(-1,-1); + node* tail=new node(-1,-1); + + + int cap; + unordered_map m; + + LRUCache(int capacity) { + cap=capacity; + head->next=tail; + tail->prev=head; + } + + void insertNode(node* newNode){ + node* temp=head->next; + newNode->next=temp; + newNode->prev=head; + head->next=newNode; + temp->prev=newNode; + } + + void deleteNode(node* delNode){ + node* delPrev=delNode->prev; + node* delNext=delNode->next; + delPrev->next=delNext; + delNext->prev=delPrev; + } + + int get(int key) { + if(m.find(key)!=m.end()){ + node* resNode=m[key]; + int res=resNode->v; + m.erase(key); + deleteNode(resNode); + insertNode(resNode); + m[key]=head->next; + return res; + } + return -1; + } + + void put(int key, int value) { + if(m.find(key)!=m.end()){ + node* exitingNode = m[key]; + m.erase(key); + deleteNode(exitingNode); + } + if(m.size() == cap){ + m.erase(tail->prev->k); + deleteNode(tail-> prev); + } + insertNode(new node(key,value)); + m[key]=head->next; + } +}; diff --git a/LRUCache.cpp b/LRUCache_Solutions/LRUCache.cpp similarity index 100% rename from LRUCache.cpp rename to LRUCache_Solutions/LRUCache.cpp diff --git a/LRUCache_Solutions/LRUCache.java b/LRUCache_Solutions/LRUCache.java new file mode 100644 index 0000000..0ed5f38 --- /dev/null +++ b/LRUCache_Solutions/LRUCache.java @@ -0,0 +1,90 @@ +package LinkedList; + +import java.util.HashMap; +import java.util.Map; + +class LRUCache{ + int size = 0; + int capacity = 0; + // the initialization of head and tail in this case is imp bcoz if +// the delete function is called with a node which is currently tail or head +// then it'll throw a null pointer exception. cuz head.prev is null and tail.next is null +// so it's better to use head and tail purely as a pointer mimic +// (since this is java,and we don't have actual pointers :D ) + Node head = new Node(0,0); + Node tail = new Node(0,0); + Map map = new HashMap<>(); + + public LRUCache(int capacity){ + this.capacity = capacity; + head.next = tail; + tail.prev = head; + } + + public int get(int key) { + Node tempNode = map.get(key);//don't use the new keyword unlike in the put function + if(map.containsKey(key)){ + delete(tempNode); + insert(tempNode); + return map.get(key).value; + }else{ + return -1; + } + } + + public void put(int key, int value) { + Node tempNode = new Node(key, value); + if(map.containsKey(key)){ + delete(map.get(key)); + //Don't pass tempNode cuz it's a separate node +// and not a part of the already created doubly linked list + } + if(size == capacity){ + delete(tail.prev); + } + insert(tempNode); + } + + void delete(Node node){ + map.remove(node.key); + node.prev.next = node.next; + node.next.prev = node.prev; + size--; + } + void insert(Node node){ + + node.next = head.next; + node.prev = head; + head.next = node; + node.next.prev = node; + size++; + map.put(node.key,node); + } + class Node{ + int key,value; + Node next, prev; + + Node(int key, int value){ + this.value = value; + this.key = key; + // this.next = null; + // this.prev = null; + } + } + + public void display(){ + Node curr = head.next; + while(curr != null){ + System.out.println("key-> " + curr.key + " val-> " + curr.value); + curr = curr.next; + } + } + +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ \ No newline at end of file diff --git a/Leetcode -14 Days Study Plan to Crack Algo (Solutions)/Study Plan 1 - (Algorithm I)/Day 1/Java/Binary Search.java b/Leetcode -14 Days Study Plan to Crack Algo (Solutions)/Study Plan 1 - (Algorithm I)/Day 1/Java/Binary Search.java new file mode 100644 index 0000000..29ff643 --- /dev/null +++ b/Leetcode -14 Days Study Plan to Crack Algo (Solutions)/Study Plan 1 - (Algorithm I)/Day 1/Java/Binary Search.java @@ -0,0 +1,21 @@ +class Solution { + public int search(int[] nums, int target) { + + int start = 0; + int end = nums.length-1; + + while(start<=end){ + + int mid = start+end>>>1; + + if(nums[mid]==target){ + return mid; + }else if(nums[mid]>>1; + + if(isBadVersion(mid)){ + end = mid; + }else start = mid+1; + + } + + return start; + } +} \ No newline at end of file diff --git a/Leetcode -14 Days Study Plan to Crack Algo (Solutions)/Study Plan 1 - (Algorithm I)/Day 1/Java/Search Insert Position.java b/Leetcode -14 Days Study Plan to Crack Algo (Solutions)/Study Plan 1 - (Algorithm I)/Day 1/Java/Search Insert Position.java new file mode 100644 index 0000000..7a4e39b --- /dev/null +++ b/Leetcode -14 Days Study Plan to Crack Algo (Solutions)/Study Plan 1 - (Algorithm I)/Day 1/Java/Search Insert Position.java @@ -0,0 +1,23 @@ +class Solution { + public int searchInsert(int[] nums, int target) { + + int start = 0; + int end = nums.length-1; + + while(start<=end){ + + int mid = start+end>>>1; + + if(nums[mid]==target) return mid; + else if(targetnext; + q = q->next; + if(NULL != q) q = q->next; + if(NULL == q || NULL == p) return false; + else if(p == q) return true; + } + } +}; diff --git a/Longest Substring Without Repeating Characters/LengthOfLongestSubstring.cs b/Longest Substring Without Repeating Characters/LengthOfLongestSubstring.cs new file mode 100644 index 0000000..8cc05f0 --- /dev/null +++ b/Longest Substring Without Repeating Characters/LengthOfLongestSubstring.cs @@ -0,0 +1,33 @@ +public class Solution { + + // This function returns true if all characters in + // str[i..j] are distinct, otherwise returns false +public static bool areDistinct(string str, int i, int j) + { + + // Note : Default values in visited are false + bool[] visited = new bool[26]; + + for(int k = i; k <= j; k++) + { + if (visited[str[k] - 'a'] == true) + return false; + + visited[str[k] - 'a'] = true; + } + return true; + } + + public int LengthOfLongestSubstring(string s) { + int n = s.Length; + // Result + int res = 0; + + for(int i = 0; i < n; i++) + for(int j = i; j < n; j++) + if (areDistinct(s, i, j)) + res = Math.Max(res, j - i + 1); + + return res; + } +} \ No newline at end of file diff --git a/Longest Substring Without Repeating Characters/main.cpp b/Longest Substring Without Repeating Characters/main.cpp new file mode 100644 index 0000000..6c42835 --- /dev/null +++ b/Longest Substring Without Repeating Characters/main.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +class Solution +{ +public: + int lengthOfLongestSubstring(string s) + { + if (s.length() == 0) + return 0; // if string of length zero comes simply return 0 + unordered_map m; // create map to store frequency,(get to know all unique characters + int i = 0, j = 0, ans = INT_MIN; + while (j < s.length()) + { + m[s[j]]++; // increase the frequency of the element as you traverse the string + if (m.size() == j - i + 1) // whem map size is equal to the window size means suppose window size is 3 and map size is also three that means in map all unique characters are their + { + ans = max(ans, j - i + 1); // compare the length of the maximum window size + } + else if (m.size() < j - i + 1) // if the map size is less than the window size means there is some duplicate present like window size = 3 and map size = 2 means there is a duplicates + { + while (m.size() < j - i + 1) // so till the duplicates are removed completely + { + m[s[i]]--; // remove the duplicates + if (m[s[i]] == 0) // if the frequency becomes zero + { + m.erase(s[i]); // delete it completely + } + i++; // go for next element + } + } + j++; // go for the next element + } + return ans; + } +}; + +int main() +{ + + return 0; +} \ No newline at end of file diff --git a/Longest Substring Without Repeating Characters/main.py b/Longest Substring Without Repeating Characters/main.py new file mode 100644 index 0000000..84102a7 --- /dev/null +++ b/Longest Substring Without Repeating Characters/main.py @@ -0,0 +1,19 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + seen = {} + l = 0 + output = 0 + for r in range(len(s)): +# If s[r] not in seen, we can keep increasing the window size by moving right pointer + if s[r] not in seen: + output = max(output,r-l+1) + else: +# There are two cases if s[r] in seen: +# case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1. +# case2: s[r] is not inside the current window, we can keep increase the window + if seen[s[r]] < l: + output = max(output,r-l+1) + else: + l = seen[s[r]] + 1 + seen[s[r]] = r + return output \ No newline at end of file diff --git a/Longest Valid Parentheses/Longest_Valid_Parentheses.java b/Longest Valid Parentheses/Longest_Valid_Parentheses.java new file mode 100644 index 0000000..f6985d6 --- /dev/null +++ b/Longest Valid Parentheses/Longest_Valid_Parentheses.java @@ -0,0 +1,22 @@ +// Runtime: 1 ms. +// Memory Usage: 41.8 MB. + +class Solution { + private int helper(String s, int start, int end, int shift, char sign){ + int n = 0, maxi = 0, tmp = 0; + + for(int i = start; i != end; i += shift){ + tmp++; + n += s.charAt(i) == sign ? -1 : 1; + + if( n == 0) maxi = Math.max(maxi, tmp); + else if( n < 0 ) n = tmp = 0; + } + + return maxi; + } + + public int longestValidParentheses(String s) { + return Math.max(helper(s, 0, s.length(), 1, ')'), helper(s, s.length() - 1, -1, -1, '(')); + } +} diff --git a/Longest Valid Parentheses/longestValidParentheses.js b/Longest Valid Parentheses/longestValidParentheses.js new file mode 100644 index 0000000..2463f3b --- /dev/null +++ b/Longest Valid Parentheses/longestValidParentheses.js @@ -0,0 +1,28 @@ +const longestValidParentheses = (str) => { + let count = 0, + left = 0, + right = 0; + + for (let i = 0; i < str.length; i++) { + let character = str[i]; + if (character === "(") left++; + if (character === ")") right++; + if (left === right) count = Math.max(count, left + right); + if (right > left) left = right = 0; + } + + left = right = 0; + + for (let i = str.length - 1; i >= 0; i--) { + let character = str[i]; + if (character === "(") left++; + if (character === ")") right++; + if (left === right) count = Math.max(count, left + right); + if (left > right) left = right = 0; + } + return count; +}; + +// console.log(longestValidParentheses("(()")) // Output: 2 +// console.log(longestValidParentheses(")()())")) // Output: 4 +// console.log(longestValidParentheses("")) // Output: 0 diff --git a/Longest Valid Parentheses/longest_valid_parentheses.java b/Longest Valid Parentheses/longest_valid_parentheses.java index a14f244..f6985d6 100644 --- a/Longest Valid Parentheses/longest_valid_parentheses.java +++ b/Longest Valid Parentheses/longest_valid_parentheses.java @@ -1,20 +1,22 @@ +// Runtime: 1 ms. +// Memory Usage: 41.8 MB. + class Solution { - public int longestValidParentheses(String s) { - Stack index=new Stack(); - index.push(-1); - int max=0; - for(int i=0; i set; + + int i = 0, j = 0, n = s.size(), ans = 0; + + while( i int: + result = 0 + + left = right = 0 + for i in range(len(s)): + if s[i] == "(": + left += 1 + else: + right += 1 + + if left == right: + result = max(result, left + right) + elif right > left: + left = right = 0 + + left = right = 0 + for i in range(len(s) - 1, -1, -1): + if s[i] == "(": + left += 1 + else: + right += 1 + + if left == right: + result = max(result, left + right) + elif left > right: + left = right = 0 + + return result diff --git a/Marge k Sorted lists.cpp b/Marge k Sorted lists.cpp new file mode 100644 index 0000000..32d2089 --- /dev/null +++ b/Marge k Sorted lists.cpp @@ -0,0 +1,47 @@ +class cmp +{ +public: + bool operator()(ListNode *a, ListNode *b) + { + return (a->val > b->val); + } +}; + +class Solution +{ +public: + ListNode *mergeKLists(vector &lists) + { + + if (lists.size() == 0) + return NULL; + + ListNode *head = new ListNode(-1); + ListNode *tail_ptr = head; + + // make a min heap + priority_queue, cmp> q; + + for (int i = 0; i < lists.size(); i++) + { + + if (lists[i] != NULL) + q.push(lists[i]); + } + + while (q.size()) + { + auto temp = q.top(); + q.pop(); + + tail_ptr->next = temp; + tail_ptr = temp; + + if (temp->next) + { + q.push(temp->next); + } + } + return head->next; + } +}; \ No newline at end of file diff --git a/Maximum_sliding_problem.cpp b/Maximum_sliding_problem.cpp new file mode 100644 index 0000000..7abbf2f --- /dev/null +++ b/Maximum_sliding_problem.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + + vector maxSlidingWindow(vector& nums, int k) { + dequedq; + + vectorv; + int n = nums.size(); + + for(int i=0;i=k-1) + v.push_back(nums[dq.front()]); + } + return v; + + } +}; diff --git a/Median of Two Sorted ArmedianOfSortedArrays.cpp b/Median of Two Sorted ArmedianOfSortedArrays.cpp new file mode 100644 index 0000000..ac1c2e5 --- /dev/null +++ b/Median of Two Sorted ArmedianOfSortedArrays.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2, nums1); + int n1 = nums1.size(); + int n2 = nums2.size(); + int low =0 , high =n1; + while(low <= high){ + int cut1 = (low + high) >>1; + int cut2 = (n1 + n2 +1)/2 - cut1; + + int left1 = cut1 ==0 ? INT_MIN : nums1[cut1-1]; + int left2 = cut2 ==0 ? INT_MIN : nums2[cut2-1]; + + int right1 = cut1 == n1 ? INT_MAX : nums1[cut1]; + int right2 = cut2 == n2? INT_MAX : nums2[cut2]; + + if(left1 <= right2 && left2 <= right1){ + if((n1+n2)%2 ==0){ + return (max(left1,left2) + min(right1 , right2))/2.0; + } + else{ + return max(left1, left2); + } + } + else if(left1 > right2){ + high = cut1 -1; + } + else { + low = cut1 +1; + } + } + return 0.0; + } +}; diff --git a/Median of Two Sorted Arrays/Median_of_two_sorted_arrays.cpp b/Median of Two Sorted Arrays/Median_of_two_sorted_arrays.cpp new file mode 100644 index 0000000..0095177 --- /dev/null +++ b/Median of Two Sorted Arrays/Median_of_two_sorted_arrays.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + + // Create a single sorted by merging two sorted arrays + int n1=nums1.size(); + int n2=nums2.size(); + int i=0; + int j=0; + int lastindex=-1; + + // Initialize a new array + vectorv(n1+n2,0); + + while(i next and whole l2 list. + if(l1 -> val <= l2 -> val) + { + l1 -> next = mergeTwoLists(l1 -> next, l2); + return l1; + } + // we will call recursive l1 whole list and l2 -> next + else + { + l2 -> next = mergeTwoLists(l1, l2 -> next); + return l2; + } + } +}; diff --git a/Merge-k-Sorted-Lists.cpp b/Merge-k-Sorted-Lists.cpp new file mode 100644 index 0000000..6f8b5f5 --- /dev/null +++ b/Merge-k-Sorted-Lists.cpp @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + vector nums; + for(auto i : lists) + { + ListNode* value = i; + while(value != NULL) + { + nums.push_back(value->val); + value = value -> next; + } + } + sort(nums.begin(), nums.end()); + if(nums.size() == 0) + return NULL; + ListNode* ans = new ListNode(nums[0]); + ListNode* value = ans; + for(int i=1; i next = new ListNode(nums[i]); + value = value -> next; + } + return ans; + } +}; diff --git a/Minimum Operations to Reduce X to Zero/Minimum_Operations_to_Reduce_X_to_Zero.cpp b/Minimum Operations to Reduce X to Zero/Minimum_Operations_to_Reduce_X_to_Zero.cpp new file mode 100644 index 0000000..21a22d8 --- /dev/null +++ b/Minimum Operations to Reduce X to Zero/Minimum_Operations_to_Reduce_X_to_Zero.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int minOperations(vector& nums, int x) { + /* + The idea is, instead of finding the smallest prefix + suffix array + we can find the largest array with total sum of (sum(nums) - x) + This can be done in O(1) time + */ + int left = 0, right = 0; + long long total = 0; + // Get the total + for (int num: nums){ + total += num; + } + total -= x; + // Sliding window technique + long long curTot = 0; + int curL = -1; + for (; right < nums.size(); right++){ + curTot += nums[right]; + // Set up the window size + while ((left <= right) && (curTot > total)){ + curTot -= nums[left]; + left++; + } + // Update the length iff the current solution length is max + if (curTot == total){ + if (right - left + 1 > curL){ + curL = right - left + 1; + } + } + } + // Return -1 if we could not find the solution + if (curL == -1){ + return -1; + } + return nums.size() - curL; + } +}; diff --git a/Minimum Operations to Reduce X to Zero/Minimum_Operations_to_Reduce_X_to_Zero.java b/Minimum Operations to Reduce X to Zero/Minimum_Operations_to_Reduce_X_to_Zero.java new file mode 100644 index 0000000..342015b --- /dev/null +++ b/Minimum Operations to Reduce X to Zero/Minimum_Operations_to_Reduce_X_to_Zero.java @@ -0,0 +1,36 @@ +class Solution +{ + + public int minOperations(int[] nums, int x) + { + int n=nums.length; + int start=0; + long sum=0; + for(int i=0;isum) + { + sum1-=nums[start]; + start++; + } + if(sum==sum1) + { + min=Math.min(nums.length-(end-start+1),min); + } + + } + return min==Integer.MAX_VALUE?-1:min; + } +} diff --git a/Minimum Operations to Reduce X to Zero/Minimum_Operationsto_ReduceX_to_Zero.py b/Minimum Operations to Reduce X to Zero/Minimum_Operationsto_ReduceX_to_Zero.py new file mode 100644 index 0000000..f73ee86 --- /dev/null +++ b/Minimum Operations to Reduce X to Zero/Minimum_Operationsto_ReduceX_to_Zero.py @@ -0,0 +1,24 @@ +class Solution(object): + def minOperations(self, nums, x): + target = sum(nums) - x + + if target == 0: + return len(nums) + + left, right = 0, 0 + curr, cnt = 0, 0 + + while right < len(nums): + curr = curr + nums[right] + + while left < right and curr > target: + curr = curr - nums[left] + left = left + 1 + if curr == target: + cnt = max(cnt, right - left + 1) + right = right + 1 + + if cnt == 0: + return -1 + else: + return len(nums) - cnt diff --git a/Number_of_Dice_Rolls_With_Target_Sum.cpp b/Number_of_Dice_Rolls_With_Target_Sum.cpp new file mode 100644 index 0000000..cca71f0 --- /dev/null +++ b/Number_of_Dice_Rolls_With_Target_Sum.cpp @@ -0,0 +1,21 @@ +#define M 1000000007 +class Solution { +public: + long long int solve(int n, int k, int x, vector>& dp){ + if(x<0) return 0; + if(n==0 && x!=0) return 0; + if(n!=0 && x==0) return 0; + if(n==0 && x==0) return 1; + if(dp[n][x]!=-1) return dp[n][x]; + long long int ans=0; + for(int i=1 ; i<=k ; i++){ + ans+=(solve(n-1, k, x-i, dp)%M); + } + return dp[n][x]=ans; + } + int numRollsToTarget(int n, int k, int target) { + vector> dp(n+1, vector(target+1, -1)); + long long int ans=solve(n,k,target,dp); + return ans%M; + } +}; diff --git a/Optimal Partition Of String/optimalPartitionOfString.cpp b/Optimal Partition Of String/optimalPartitionOfString.cpp new file mode 100644 index 0000000..e9fafb3 --- /dev/null +++ b/Optimal Partition Of String/optimalPartitionOfString.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int partitionString(string s) { + unordered_map mp1; + + int result = 0; + for(int i = 0; i < s.length(); i++) + { + if(mp1.find(s[i]) != mp1.end()) + { +// found element + i--; + result++; + mp1.clear(); + + } + else + { + mp1[s[i]] = 1; + } + } + + return result + 1; + } +}; \ No newline at end of file diff --git a/Optimal Partition Of String/optimalPartitionOfString.js b/Optimal Partition Of String/optimalPartitionOfString.js new file mode 100644 index 0000000..2abf250 --- /dev/null +++ b/Optimal Partition Of String/optimalPartitionOfString.js @@ -0,0 +1,16 @@ +const partitionString = (str) => { + if ([0, 1].includes(str.length)) return str.length; + let count = 1; + let obj = {}; + for (let character of str) { + if (!Object.keys(obj).includes(character)) obj[character] = character; + else { + obj = {}; + obj[character] = character; + count++; + } + } + return count; +}; + +// console.log(partitionString("abacaba")) // Output: 4 diff --git a/Permutations/Permutations.py b/Permutations/Permutations.py new file mode 100644 index 0000000..6c191b9 --- /dev/null +++ b/Permutations/Permutations.py @@ -0,0 +1,19 @@ +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + n = len(nums) + results = [] + subset = [] + + def dfs(): + if len(subset) == n: + results.append(subset.copy()) + return + + for num in nums: + if num not in subset: + subset.append(num) + dfs() + subset.pop() + + dfs() + return results \ No newline at end of file diff --git a/Permutations/permutations.js b/Permutations/permutations.js new file mode 100644 index 0000000..359644e --- /dev/null +++ b/Permutations/permutations.js @@ -0,0 +1,19 @@ +const checkPermutations = (result, permutation, nums) => { + if (permutation.length === nums.length) return result.push([...permutation]); + for (let i = 0; i < nums.length; i++) { + if (permutation.includes(nums[i])) continue; + permutation.push(nums[i]); + checkPermutations(result, permutation, nums); + permutation.pop(); + } +}; + +const permute = (nums) => { + const result = []; + checkPermutations(result, [], nums); + return result; +}; + +// console.log(permute([1, 2, 3])); +// console.log(permute([0, 1])); +// console.log(permute([1])); diff --git a/README.md b/README.md index e099669..0386725 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,14 @@ Hactoberfest contribution - 2022 -1. Add leetcode solutions of given problem in any language. +1. Add leetcode solution of the given problems in any language. 2. The file name should be same as question name. -3. Don't add irrelevant code, it will mark as invalid. +3. Don't add irrelevant code, it will be marked as invalid. 4. Don't raise invalid PR's + + + + +Connect me on LinkedIn - https://www.linkedin.com/in/saritapatel8770/ + + diff --git a/Remove Nth Node From End of List.cpp b/Remove Nth Node From End of List.cpp new file mode 100644 index 0000000..5e4ce96 --- /dev/null +++ b/Remove Nth Node From End of List.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode* fst=head;ListNode* slw=head; + if (n==0) return head; + for(int i=0;inext; + } + if(fst == NULL ) return head->next; + //cout << slw->val; + while(fst->next != NULL){ + //cout <<"hello"; + slw=slw->next; + fst=fst->next; + } + + slw->next=(slw->next)->next ; + + return head; + } +}; diff --git a/Remove Palindromic Subsequences/removePalindromicSubsequences.js b/Remove Palindromic Subsequences/removePalindromicSubsequences.js new file mode 100644 index 0000000..28e79c9 --- /dev/null +++ b/Remove Palindromic Subsequences/removePalindromicSubsequences.js @@ -0,0 +1,15 @@ +/** + * @param {string} s + * @return {number} + */ + function removePalindromeSub(str) { + if (!str) return 0 + for (let i = 0, j = str.length - 1; i < j; i++, j--) + if (str.charAt(i) !== str.charAt(j)) return 2 + return 1 +}; + +/* + console.log(removePalindromeSub("ababa")) // 1 + console.log(removePalindromeSub("abb")) // 2 + */ diff --git a/Reverse Odd Levels of Binary Tree in easiest way b/Reverse Odd Levels of Binary Tree in easiest way new file mode 100644 index 0000000..0d51b32 --- /dev/null +++ b/Reverse Odd Levels of Binary Tree in easiest way @@ -0,0 +1,52 @@ + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* reverseOddLevels(TreeNode* root) { + vector ans; + if(root == NULL) + return root; + queue q; + stack st; + q.push(root); + int l=0; + while(!q.empty()) { + vector level; + int n=q.size(); + for(int i=0;ileft!=NULL) + q.push(Node->left); + if(Node->right!=NULL) + q.push(Node->right); + if(l%2==1){ + st.push(Node); + level.push_back(Node->val); + } + } + if(l%2==1) + { + int sz=level.size(); + int idx=0; + while(!st.empty()) + { + TreeNode* Node=st.top(); + st.pop(); + Node->val=level[idx]; + idx++; + } + } + l++; + } + return root; + } +}; diff --git a/Reverse Odd Levels of Binary Tree/Reverse_Odd_Levels_of_Binary_Tree.cpp b/Reverse Odd Levels of Binary Tree/Reverse_Odd_Levels_of_Binary_Tree.cpp new file mode 100644 index 0000000..959b9da --- /dev/null +++ b/Reverse Odd Levels of Binary Tree/Reverse_Odd_Levels_of_Binary_Tree.cpp @@ -0,0 +1,88 @@ +//Solution using Recursion. time Complexity O(n) and Auxiliary space O(n)for recusion call stack here n is no of nodes in given tree. + +class Solution { +public: + void helper(TreeNode* root1,TreeNode* root2,int count){ + if(!root1&&!root2)return; + + if(count%2!=0){ //for revere of nodes at odd levels + int temp=root1->val; + root1->val=root2->val; + root2->val=temp; + + } + helper(root1->left,root2->right,count+1); + helper(root1->right,root2->left,count+1); + } + + TreeNode* reverseOddLevels(TreeNode* root) { + if(!root)return NULL; + if(!root->left&&!root->right)return root; + int count=1; + helper(root->left,root->right,count); + return root; + } +}; + + +//Iterative Solution using queue data structure time Complexity O(n) and Auxiliary space O(no.of nodes at last level). here n is no of nodes in given tree. +class Solution { +public: + vector traverse; + TreeNode* reverseOddLevels(TreeNode* root) { + bool oddLevel = false; + auto Root = root; + queue q; + q.push({root}); + + while(q.size()) { + int cnt = q.size(); + vector temp; + + while(cnt--) { + auto node = q.front(); + q.pop(); + + temp.push_back(node->val); + if(node->left) q.push(node->left); + if(node->right) q.push(node->right); + } + if(oddLevel) { + reverse(temp.begin(), temp.end()); + for(auto a : temp) traverse.push_back(a); + oddLevel = false; + } else { + for(auto a : temp) traverse.push_back(a); + oddLevel = true; + } + } + + // Create Binary Tree from Vector + queue Q; + Q.push({Root}); + int j = 1; + + while(Q.size() && j < traverse.size()) { + int cnt = Q.size(); + while(cnt--) { + auto node = Q.front(); + Q.pop(); + + if(j < traverse.size()) { + node->left = new TreeNode(traverse[j++]); + } + if(j < traverse.size()) { + node->right = new TreeNode(traverse[j++]); + } + if(node->left) { + Q.push(node->left); + } + if(node->right) { + Q.push(node->right); + } + } + } + return Root; + } +}; + diff --git a/Reverse Odd Levels of Binary Tree/reverseoddbinarytree.py b/Reverse Odd Levels of Binary Tree/reverseoddbinarytree.py new file mode 100644 index 0000000..5ec5f50 --- /dev/null +++ b/Reverse Odd Levels of Binary Tree/reverseoddbinarytree.py @@ -0,0 +1,12 @@ +class Solution: + def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + def dfs(left: Optional[TreeNode], right: Optional[TreeNode], isOddLevel: bool) -> None: + if not left: + return + if isOddLevel: + left.val, right.val = right.val, left.val + dfs(left.left, right.right, not isOddLevel) + dfs(left.right, right.left, not isOddLevel) + + dfs(root.left, root.right, True) + return root \ No newline at end of file diff --git a/Running Sum of 1d Array b/Running Sum of 1d Array new file mode 100644 index 0000000..339f272 --- /dev/null +++ b/Running Sum of 1d Array @@ -0,0 +1,13 @@ +class Solution { +public: + vector runningSum(vector& nums) { + vector v; + int sum=0; + for(int i=0;i bool: + # if the tree ends here -> subtree is equal + if p==None and q==None: + return True + # if sides of the tree don't match -> subtree is different + if (p==None and q!=None) or (p!=None and q==None) or p.val != q.val: + return False + return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) diff --git a/Same Tree/Same_Tree.java b/Same Tree/Same_Tree.java new file mode 100644 index 0000000..3cd8b7e --- /dev/null +++ b/Same Tree/Same_Tree.java @@ -0,0 +1,19 @@ +//Same Tree Leetcode 100 + +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } + + if (p == null || q == null) { + return false; + } + + if (p.val != q.val) { + return false; + } + + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} \ No newline at end of file diff --git a/Surrounded_Regions_Leetcode.cpp b/Surrounded_Regions_Leetcode.cpp new file mode 100644 index 0000000..b43ea5c --- /dev/null +++ b/Surrounded_Regions_Leetcode.cpp @@ -0,0 +1,73 @@ +class Solution { +public: + void DFS(vector>& board, int i, int j, int m, int n) { + if(i<0 or j<0 or i>=m or j>=n or board[i][j] != 'O') return; + board[i][j] = '#'; + DFS(board, i-1, j, m, n); + DFS(board, i+1, j, m, n); + DFS(board, i, j-1, m, n); + DFS(board, i, j+1, m, n); + } + + void solve(vector>& board) { + + //We will use boundary DFS to solve this problem + + // Let's analyze when an 'O' cannot be flipped, + // if it has atleast one 'O' in it's adjacent, AND ultimately this chain of adjacent 'O's is connected to some 'O' which lies on boundary of board + + //consider these two cases for clarity : + /* + O's won't be flipped O's will be flipped + [X O X X X] [X X X X X] + [X O O O X] [X O O O X] + [X O X X X] [X O X X X] + [X X X X X] [X X X X X] + + So we can conclude if a chain of adjacent O's is connected some O on boundary then they cannot be flipped + + */ + + //Steps to Solve : + //1. Move over the boundary of board, and find O's + //2. Every time we find an O, perform DFS from it's position + //3. In DFS convert all 'O' to '#' (why?? so that we can differentiate which 'O' can be flipped and which cannot be) + //4. After all DFSs have been performed, board contains three elements,#,O and X + //5. 'O' are left over elements which are not connected to any boundary O, so flip them to 'X' + //6. '#' are elements which cannot be flipped to 'X', so flip them back to 'O' + //7. finally, Upvote the solution😊 + + + int m = board.size(); + + if(m == 0) return; + + int n = board[0].size(); + + //Moving over firts and last column + for(int i=0; i leftMaxHegith){ + leftMaxHegith = height[left]; + }else{ + trappedWater+= leftMaxHegith - height[left]; + } + left++; + }else{ + if(height[right] > rightMaxHegith){ + rightMaxHegith = height[right]; + }else{ + trappedWater+=rightMaxHegith-height[right]; + } + right--; + } + } + return trappedWater; +}; \ No newline at end of file diff --git a/Trapping Rain Water/trappingRainWater.cpp b/Trapping Rain Water/trappingRainWater.cpp new file mode 100644 index 0000000..879675e --- /dev/null +++ b/Trapping Rain Water/trappingRainWater.cpp @@ -0,0 +1,49 @@ +// BRUTEFORCE APPROACH + +class Solution { +public: + int trap(vector& height) { + int n=height.size(); + int pre[n]; + int suf[n]; + pre[0]=height[0]; + for(int i=1;i=0;i--){ + suf[i]=max(suf[i+1],height[i]); + } + int ans=0; + for(int i=0;iheight[i] && rightMax>height[i]){ + int minm=min(leftMax,rightMax); + ans=ans+minm-height[i]; + } + } + return ans; + } +}; + +//OPTIMISED APPROACH + +class Solution { +public: + int trap(vector& height) { + int n=height.size(); + int left=0,right=n-1,sum=0,mleft=0,mright=0; + for(int i=0;i=mleft?mleft=height[left]:sum+=(mleft-height[left]); + left++; + } + else{ + height[right]>=mright?mright=height[right]:sum+=(mright-height[right]); + right--; + } + } + return sum; + } +}; diff --git a/Trapping Rain Water/trappingRainWater.java b/Trapping Rain Water/trappingRainWater.java new file mode 100644 index 0000000..d41121a --- /dev/null +++ b/Trapping Rain Water/trappingRainWater.java @@ -0,0 +1,23 @@ +class Solution { + public int trap(int[] height) { + int total_water = 0; + int l = 0; + int r = height.length - 1; + int left_max = height[l]; + int right_max = height[r]; + + while(l < r) { + if (left_max < right_max) { + l++; + left_max = Math.max(left_max, height[l]); + total_water += left_max - height[l]; + } else { + r--; + right_max = Math.max(right_max, height[r]); + total_water += right_max - height[r]; + } + } + + return total_water; + } +} \ No newline at end of file diff --git a/Trapping Rain Water/trapping_rain_water.java b/Trapping Rain Water/trapping_rain_water.java new file mode 100644 index 0000000..df40724 --- /dev/null +++ b/Trapping Rain Water/trapping_rain_water.java @@ -0,0 +1,27 @@ +class Solution { + public int trap(int[] height) { + int l = 0; + int r = height.length - 1; + int water = 0; + //initializing + int leftmaxheight = height[l]; + int rightmaxheight = height[r]; + + + while(l +using namespace std; + +class Solution +{ +public: + int minimumTotal(vector> &triangle) + { + int n = triangle.size(); + vector next_row(triangle[n - 1]); + vector curr_row(n, 0); + for (int i = n - 2; i >= 0; i--) + { + for (int j = 0; j < i + 1; j++) + { + int lower_left = triangle[i][j] + next_row[j]; + int lower_right = triangle[i][j] + next_row[j + 1]; + curr_row[j] = min(lower_left, lower_right); + } + swap(curr_row, next_row); + } + return next_row[0]; // because we swapped at last iteration + } +}; + +int main() +{ + int n; + cin >> n; + return 0; +} \ No newline at end of file diff --git a/Triangle/main.cpp b/Triangle/main.cpp new file mode 100644 index 0000000..815e9cc --- /dev/null +++ b/Triangle/main.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +class Solution +{ +public: + int dfs(int i, int j, int n, vector> &triangle, vector> &memo) + { + if (i == n) + return 0; + if (memo[i][j] != -1) + return memo[i][j]; + + int lower_left = triangle[i][j] + dfs(i + 1, j, n, triangle, memo); + int lower_right = triangle[i][j] + dfs(i + 1, j + 1, n, triangle, memo); + memo[i][j] = min(lower_left, lower_right); + + return memo[i][j]; + } + int minimumTotal(vector> &triangle) + { + int n = triangle.size(); + vector> memo(n, vector(n, -1)); + return dfs(0, 0, n, triangle, memo); + } +}; + +int main() +{ + + return 0; +} \ No newline at end of file diff --git a/Triangle/main.py b/Triangle/main.py new file mode 100644 index 0000000..43b135e --- /dev/null +++ b/Triangle/main.py @@ -0,0 +1,15 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + memo = [[-1] * len(triangle) for _ in range(len(triangle))] + def dfs(i, j): + if i == len(triangle): + return 0 + if memo[i][j] != -1: + return memo[i][j] + + lower_left = triangle[i][j] + dfs(i + 1, j) + lower_right = triangle[i][j] + dfs(i + 1, j + 1) + memo[i][j] = min(lower_left, lower_right) + return memo[i][j] + + return dfs(0, 0) \ No newline at end of file diff --git a/Triangle/triangle.cpp b/Triangle/triangle.cpp new file mode 100644 index 0000000..6b36ba3 --- /dev/null +++ b/Triangle/triangle.cpp @@ -0,0 +1,9 @@ +class Solution { + public: + int minimumTotal(vector>& triangle) { + for (int i = triangle.size() - 2; i >= 0; --i) + for (int j = 0; j <= i; ++j) + triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); + return triangle[0][0]; + } +}; \ No newline at end of file diff --git a/Triangle/tringle.py b/Triangle/tringle.py new file mode 100644 index 0000000..96c0773 --- /dev/null +++ b/Triangle/tringle.py @@ -0,0 +1,8 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + for i in reversed(range(len(triangle) - 1)): + for j in range(i + 1): + triangle[i][j] += min(triangle[i + 1][j], + triangle[i + 1][j + 1]) + + return triangle[0][0] diff --git a/Two Sum IV - Input is a BST.java b/Two Sum IV - Input is a BST.java new file mode 100644 index 0000000..cc212d4 --- /dev/null +++ b/Two Sum IV - Input is a BST.java @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean findTarget(TreeNode root, int k) { + + if(root.left==null && root.right==null) return false; + + Set set = new HashSet<>(); + getVals(root,set); + + for(int i:set){ + if(set.contains(k-i) && i!=k-i) return true; + } + + return false; + } + + void getVals(TreeNode root, Set set){ + + if(root==null) return; + + set.add(root.val); + getVals(root.left,set); + getVals(root.right,set); + + } + +} \ No newline at end of file diff --git a/deleteOperationOnTwoStrings.cpp b/deleteOperationOnTwoStrings.cpp new file mode 100644 index 0000000..a2027db --- /dev/null +++ b/deleteOperationOnTwoStrings.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minDistance(string word1, string word2) { + int n1 = word1.length(); + int n2 = word2.length(); + vector> dp (n1+1, vector(n2+1, 0)); + for(int i = 1; i <= n1; i++) { + for(int j = 1; j <= n2; j++) { + if(word1[i-1] == word2[j-1]) { + dp[i][j] = dp[i-1][j-1] + 1; + } + else { + dp[i][j] = max(dp[i-1][j], dp[i][j-1]); + } + } + } + return n1 - dp[n1][n2] + n2 - dp[n1][n2]; + } +}; \ No newline at end of file diff --git a/firstMissingPositive.java b/firstMissingPositive.java new file mode 100644 index 0000000..2fdc557 --- /dev/null +++ b/firstMissingPositive.java @@ -0,0 +1,33 @@ + +//importing the required package +import java.util.*; + +public class firstMissingPositive { + + // creating the function for leetcode + public static int firstMissingPositiveNumber(int[] nums) { + + // sorting the given array to arrange them in ascending order. + Arrays.sort(nums); + + // declaring the required values + int miss = 1; + int n = nums.length; + + // checking for the missing number + for (int i = 0; i < n; i++) { + if (nums[i] > miss) + return miss; + if (nums[i] == miss) + miss++; + } + return miss; + } + + // main function + public static void main(String[] args) { + int[] arr1 = { 3, 4, -1, 1 }; + int ans = firstMissingPositiveNumber(arr1); + System.out.println(ans); + } +} \ No newline at end of file diff --git a/maximum_erasure_value.cpp b/maximum_erasure_value.cpp new file mode 100644 index 0000000..c2e98df --- /dev/null +++ b/maximum_erasure_value.cpp @@ -0,0 +1,25 @@ +class Solution +{ +public: + int maximumUniqueSubarray(vector &nums) + { + int maxSum = 0, currSum = 0; + int n = nums.size(); + unordered_set st; + for (int i = 0, j = 0; i < n;) + { + if (st.count(nums[i])) + { + st.erase(nums[j]); + currSum -= nums[j++]; + } + else + { + st.insert(nums[i]); + currSum += nums[i++]; + } + maxSum = max(maxSum, currSum); + } + return maxSum; + } +}; \ No newline at end of file diff --git a/permutations.cpp b/permutations.cpp new file mode 100644 index 0000000..11a7ee7 --- /dev/null +++ b/permutations.cpp @@ -0,0 +1,25 @@ +class Solution { + void solve(int ind, vector>&ans,vector nums,vectorout){ + + if(ind>=nums.size()){ + ans.push_back(nums); + return; + } + + for(int j=ind;j> permute(vector& nums) { + vector>ans; + vectorout; + + int ind=0; + solve(ind,ans,nums,out); + return ans; + + } +}; diff --git a/sort_people.cpp b/sort_people.cpp new file mode 100644 index 0000000..4cdc7bf --- /dev/null +++ b/sort_people.cpp @@ -0,0 +1,20 @@ +// Leetcode problem - 2418. Sort the People +class Solution { +public: + vector sortPeople(vector& names, vector& heights) { + map mp; + for(int i=0;i ans, ans1; + for(auto val:mp){ + ans.push_back(val.second); + } + for(int i=names.size()-1;i>=0;i--){ + ans1.push_back(ans[i]); + + } + return ans1; + + } +}; \ No newline at end of file