diff --git a/.github/workflows/contributors.yml b/.github/workflows/contributors.yml new file mode 100644 index 00000000..64d7775e --- /dev/null +++ b/.github/workflows/contributors.yml @@ -0,0 +1,23 @@ +name: Add contributors +on: + schedule: + - cron: '20 20 * * *' + push: + branches: + - main + +jobs: + add-contributors: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: BobAnkh/add-contributors@master + with: + CONTRIBUTOR: '### Contributors' + COLUMN_PER_ROW: '6' + ACCESS_TOKEN: ${{secrets.GITHUB_TOKEN}} + IMG_WIDTH: '100' + FONT_SIZE: '14' + PATH: '/README.md' + COMMIT_MESSAGE: 'docs(README): update contributors' + AVATAR_SHAPE: 'round' diff --git a/1048-longest-string-chain/1048-longest-string-chain.java b/1048-longest-string-chain/1048-longest-string-chain.java new file mode 100644 index 00000000..824ff6ce --- /dev/null +++ b/1048-longest-string-chain/1048-longest-string-chain.java @@ -0,0 +1,19 @@ +class Solution { + public int longestStrChain(String[] words) { + Map map = new HashMap<>(); + Arrays.sort(words, (a,b)->a.length() - b.length()); + int res = 0; + for(String word : words) + { + int best = 0; + for(int i=0;i1048. Longest String Chain

Medium


You are given an array of words where each word consists of lowercase English letters.

+ +

wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.

+ +
    +
  • For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
  • +
+ +

A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.

+ +

Return the length of the longest possible word chain with words chosen from the given list of words.

+ +

 

+

Example 1:

+ +
Input: words = ["a","b","ba","bca","bda","bdca"]
+Output: 4
+Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
+
+ +

Example 2:

+ +
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
+Output: 5
+Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
+
+ +

Example 3:

+ +
Input: words = ["abcd","dbqca"]
+Output: 1
+Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
+["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 1000
  • +
  • 1 <= words[i].length <= 16
  • +
  • words[i] only consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp b/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp new file mode 100644 index 00000000..88006722 --- /dev/null +++ b/121 Leetcode/114-flatten-binary-tree-to-linked-list.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + void flatten(TreeNode* root) { + if(!root) return; + while(root) + { + TreeNode* temp = root->right; + root->right = root->left; + root->left = NULL; + TreeNode* node = root; + while(node->right) + { + node = node->right; + } + node->right = temp; + root = root->right; + } + } +}; diff --git a/121 Leetcode/121 leetcode.py b/121 Leetcode/121 leetcode.py new file mode 100644 index 00000000..ea6114e9 --- /dev/null +++ b/121 Leetcode/121 leetcode.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + maxProfit = 0 + currentMax = 0 + + for i in reversed(prices): + currentMax = max(currentMax, i) + profit = currentMax - i + maxProfit = max(profit, maxProfit) + return maxProfit \ No newline at end of file diff --git a/121 Leetcode/word-ladder-ii.cpp b/121 Leetcode/word-ladder-ii.cpp new file mode 100644 index 00000000..86aa76f0 --- /dev/null +++ b/121 Leetcode/word-ladder-ii.cpp @@ -0,0 +1,101 @@ +// BFS gives TLE if we store path while traversing because whenever we find a better visit time for a word, we have to clear/make a new path vector everytime. +// The idea is to first use BFS to search from beginWord to endWord and generate the word-to-children mapping at the same time. +// Then, use DFS (backtracking) to generate the transformation sequences according to the mapping. +// The reverse DFS allows us to only make the shortest paths, never having to clear a whole sequence when we encounter better result in BFS +// No string operations are done, by dealing with indices instead. + + + +class Solution { +public: +bool able(string s,string t){ + int c=0; + for(int i=0;i> &g,vector parent[],int n,int start,int end){ + vector dist(n,1005); + queue q; + q.push(start); + parent[start]={-1}; + dist[start]=0; + while(!q.empty()){ + int x=q.front(); + q.pop(); + for(int u:g[x]){ + if(dist[u]>dist[x]+1){ + dist[u]=dist[x]+1; + q.push(u); + parent[u].clear(); + parent[u].push_back(x); + } + else if(dist[u]==dist[x]+1) + parent[u].push_back(x); + } + } +} +void shortestPaths(vector> &Paths, vector &path, vector parent[],int node){ + if(node==-1){ + // as parent of start was -1, we've completed the backtrack + Paths.push_back(path); + return ; + } + for(auto u:parent[node]){ + path.push_back(u); + shortestPaths(Paths,path,parent,u); + path.pop_back(); + } +} +vector> findLadders(string beginWord, string endWord, vector& wordList) { + // start and end are indices of beginWord and endWord + int n=wordList.size(),start=-1,end=-1; + vector> ANS; + for(int i=0;i> g(n,vector()),Paths; + + // storing possible parents for each word (to backtrack later), path is the current sequence (while backtracking) + vector parent[n],path; + + // creating adjency list for each pair of words in the wordList (including beginword) + for(int i=0;i now; + for(int i=0;i runningSum(vector& nums) { + for(int i=1;i1480. Running Sum of 1d Array

Easy


Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

+ +

Return the running sum of nums.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: [1,3,6,10]
+Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
+ +

Example 2:

+ +
Input: nums = [1,1,1,1,1]
+Output: [1,2,3,4,5]
+Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
+ +

Example 3:

+ +
Input: nums = [3,1,2,10,1]
+Output: [3,4,6,16,17]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -10^6 <= nums[i] <= 10^6
  • +
\ No newline at end of file diff --git a/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java b/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java new file mode 100644 index 00000000..661530e9 --- /dev/null +++ b/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java @@ -0,0 +1,16 @@ +class Solution { + public int furthestBuilding(int[] heights, int bricks, int ladders) { + PriorityQueue pq = new PriorityQueue<>(); + for(int i=0;i0) + pq.add(distance); + if(pq.size()>ladders) + bricks -= pq.poll(); + if(bricks<0) + return i; + } + return heights.length-1; + } +} \ No newline at end of file diff --git a/1642-furthest-building-you-can-reach/NOTES.md b/1642-furthest-building-you-can-reach/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/1642-furthest-building-you-can-reach/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/1642-furthest-building-you-can-reach/README.md b/1642-furthest-building-you-can-reach/README.md new file mode 100644 index 00000000..f99783e6 --- /dev/null +++ b/1642-furthest-building-you-can-reach/README.md @@ -0,0 +1,48 @@ +

1642. Furthest Building You Can Reach

Medium


You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.

+ +

You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

+ +

While moving from building i to building i+1 (0-indexed),

+ +
    +
  • If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
  • +
  • If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
  • +
+ +

Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

+ +

 

+

Example 1:

+ +
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
+Output: 4
+Explanation: Starting at building 0, you can follow these steps:
+- Go to building 1 without using ladders nor bricks since 4 >= 2.
+- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
+- Go to building 3 without using ladders nor bricks since 7 >= 6.
+- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
+It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
+
+ +

Example 2:

+ +
Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
+Output: 7
+
+ +

Example 3:

+ +
Input: heights = [14,3,19,3], bricks = 17, ladders = 0
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= heights.length <= 105
  • +
  • 1 <= heights[i] <= 106
  • +
  • 0 <= bricks <= 109
  • +
  • 0 <= ladders <= heights.length
  • +
+
\ No newline at end of file diff --git a/19-remove-nth-node-from-end-of-list.cpp/19-remove-nth-node-from-end-of-list.cpp b/19-remove-nth-node-from-end-of-list.cpp/19-remove-nth-node-from-end-of-list.cpp new file mode 100644 index 00000000..facd33bc --- /dev/null +++ b/19-remove-nth-node-from-end-of-list.cpp/19-remove-nth-node-from-end-of-list.cpp @@ -0,0 +1,35 @@ +/** + * 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* removeNthFromEnd(ListNode* head, int n) { + int cnt=0; + ListNode* curr=head; + while(curr){ + curr=curr->next; + cnt++; + }curr=head; + if(n==1 && cnt==1) + return NULL; + if(cnt-n==0) + return head->next; + for(int i=1;inext; + } + if(curr->next==NULL) + return head; + if(curr->next->next==NULL) + curr->next=NULL; + else + curr->next=curr->next->next; + return head; + } +}; \ No newline at end of file diff --git a/19-remove-nth-node-from-end-of-list.cpp/README.md b/19-remove-nth-node-from-end-of-list.cpp/README.md new file mode 100644 index 00000000..8d4110a9 --- /dev/null +++ b/19-remove-nth-node-from-end-of-list.cpp/README.md @@ -0,0 +1,34 @@ +

19. Remove Nth Node From End of List

Medium


Given the head of a linked list, remove the nth node from the end of the list and return its head.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], n = 2
+Output: [1,2,3,5]
+
+ +

Example 2:

+ +
Input: head = [1], n = 1
+Output: []
+
+ +

Example 3:

+ +
Input: head = [1,2], n = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is sz.
  • +
  • 1 <= sz <= 30
  • +
  • 0 <= Node.val <= 100
  • +
  • 1 <= n <= sz
  • +
+ +

 

+

Follow up: Could you do this in one pass?

+
\ No newline at end of file diff --git a/56-LEETCODE-SOLUTION-Merge-interval.java b/56-LEETCODE-SOLUTION-Merge-interval.java deleted file mode 100644 index 206067a3..00000000 --- a/56-LEETCODE-SOLUTION-Merge-interval.java +++ /dev/null @@ -1,93 +0,0 @@ -class Solution { - private Map> graph; - private Map> nodesInComp; - private Set visited; - - // return whether two intervals overlap (inclusive) - private boolean overlap(int[] a, int[] b) { - return a[0] <= b[1] && b[0] <= a[1]; - } - - // build a graph where an undirected edge between intervals u and v exists - // iff u and v overlap. - private void buildGraph(int[][] intervals) { - graph = new HashMap<>(); - for (int[] interval : intervals) { - graph.put(interval, new LinkedList<>()); - } - - for (int[] interval1 : intervals) { - for (int[] interval2 : intervals) { - if (overlap(interval1, interval2)) { - graph.get(interval1).add(interval2); - graph.get(interval2).add(interval1); - } - } - } - } - - // merges all of the nodes in this connected component into one interval. - private int[] mergeNodes(List nodes) { - int minStart = nodes.get(0)[0]; - for (int[] node : nodes) { - minStart = Math.min(minStart, node[0]); - } - - int maxEnd = nodes.get(0)[1]; - for (int[] node : nodes) { - maxEnd = Math.max(maxEnd, node[1]); - } - - return new int[] {minStart, maxEnd}; - } - - // use depth-first search to mark all nodes in the same connected component - // with the same integer. - private void markComponentDFS(int[] start, int compNumber) { - Stack stack = new Stack<>(); - stack.add(start); - - while (!stack.isEmpty()) { - int[] node = stack.pop(); - if (!visited.contains(node)) { - visited.add(node); - - if (nodesInComp.get(compNumber) == null) { - nodesInComp.put(compNumber, new LinkedList<>()); - } - nodesInComp.get(compNumber).add(node); - - for (int[] child : graph.get(node)) { - stack.add(child); - } - } - } - } - - // gets the connected components of the interval overlap graph. - private void buildComponents(int[][] intervals) { - nodesInComp = new HashMap<>(); - visited = new HashSet<>(); - int compNumber = 0; - - for (int[] interval : intervals) { - if (!visited.contains(interval)) { - markComponentDFS(interval, compNumber); - compNumber++; - } - } - } - - public int[][] merge(int[][] intervals) { - buildGraph(intervals); - buildComponents(intervals); - - // for each component, merge all intervals into one interval. - List merged = new LinkedList<>(); - for (int comp = 0; comp < nodesInComp.size(); comp++) { - merged.add(mergeNodes(nodesInComp.get(comp))); - } - - return merged.toArray(new int[merged.size()][]); - } -} diff --git a/968-binary-tree-cameras/968-binary-tree-cameras.java b/968-binary-tree-cameras/968-binary-tree-cameras.java new file mode 100644 index 00000000..c062e547 --- /dev/null +++ b/968-binary-tree-cameras/968-binary-tree-cameras.java @@ -0,0 +1,38 @@ +/** + * 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 int minCameraCover(TreeNode root) { + int ans[] = solve(root); + return Math.min(ans[1],ans[2]); + } + + public int[] solve(TreeNode node) + { + if(node == null) + return new int[]{0,0,9999}; + int l[] = solve(node.left); + int r[] = solve(node.right); + + int ml = Math.min(l[1],l[2]); + int mr = Math.min(r[1],r[2]); + + int d0 = l[1]+r[1]; + int d1 = Math.min(l[2]+mr , r[2]+ml); + int d2 = 1+Math.min(l[0],ml) + Math.min(r[0],mr); + + return new int[]{d0,d1,d2}; + } +} \ No newline at end of file diff --git a/968-binary-tree-cameras/NOTES.md b/968-binary-tree-cameras/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/968-binary-tree-cameras/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/968-binary-tree-cameras/README.md b/968-binary-tree-cameras/README.md new file mode 100644 index 00000000..a2846eeb --- /dev/null +++ b/968-binary-tree-cameras/README.md @@ -0,0 +1,27 @@ +

968. Binary Tree Cameras

Hard


You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.

+ +

Return the minimum number of cameras needed to monitor all nodes of the tree.

+ +

 

+

Example 1:

+ +
Input: root = [0,0,null,0,0]
+Output: 1
+Explanation: One camera is enough to monitor all nodes if placed as shown.
+
+ +

Example 2:

+ +
Input: root = [0,0,null,0,null,0,null,null,0]
+Output: 2
+Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • Node.val == 0
  • +
+
\ No newline at end of file diff --git a/Add-digit-dp-problem.java b/Add-digit-dp-problem.java deleted file mode 100644 index 2ea2e8c5..00000000 --- a/Add-digit-dp-problem.java +++ /dev/null @@ -1,166 +0,0 @@ - -import java.util.ArrayList; - -import java.util.Arrays; - -// Given two integers a and b. The task is to print -// sum of all the digits appearing in the -// integers between a and b - -public class AMAN { - - - // Memoization for the state results - - static long dp[][][] = new long[20][180][2]; - - - // Stores the digits in x in a vector digit - - static void getDigits(long x, ArrayList digit) - - { - - while (x != 0) { - - digit.add((int)(x % 10)); - - x /= 10; - - } - - } - - - // Return sum of digits from 1 to integer in - - // digit vector - - static long digitSum(int idx, int sum, int tight, - - ArrayList digit) - - { - - // base case - - if (idx == -1) - - return sum; - - - // checking if already calculated this state - - if (dp[idx][sum][tight] != -1 && tight != 1) - - return dp[idx][sum][tight]; - - - long ret = 0; - - - // calculating range value - - int k = (tight != 0) ? digit.get(idx) : 9; - - - for (int i = 0; i <= k; i++) { - - // calculating newTight value for next state - - int newTight - - = (digit.get(idx) == i) ? tight : 0; - - - // fetching answer from next state - - ret += digitSum(idx - 1, sum + i, newTight, - - digit); - - } - - - if (tight != 0) - - dp[idx][sum][tight] = ret; - - - return ret; - - } - - - // Returns sum of digits in numbers from a to b. - - static int rangeDigitSum(int a, int b) - - { - - // initializing dp with -1 - - for (int i = 0; i < 20; i++) - - for (int j = 0; j < 180; j++) - - for (int k = 0; k < 2; k++) - - dp[i][j][k] = -1; - - - // storing digits of a-1 in digit vector - - ArrayList digitA - - = new ArrayList(); - - getDigits(a - 1, digitA); - - - // Finding sum of digits from 1 to "a-1" which is - - // passed as digitA. - - long ans1 - - = digitSum(digitA.size() - 1, 0, 1, digitA); - - - // Storing digits of b in digit vector - - ArrayList digitB - - = new ArrayList(); - - getDigits(b, digitB); - - - // Finding sum of digits from 1 to "b" which is - - // passed as digitB. - - long ans2 - - = digitSum(digitB.size() - 1, 0, 1, digitB); - - - return (int)(ans2 - ans1); - - } - - - // driver function to call above function - - public static void main(String[] args) - - { - - int a = 123, b = 1024; - - System.out.println("digit sum for given range : " - - + rangeDigitSum(a, b)); - - } -} diff --git a/Arrays/01_static_and_dynamicArray.c b/Arrays/01_static_and_dynamicArray.c new file mode 100644 index 00000000..1ff30400 --- /dev/null +++ b/Arrays/01_static_and_dynamicArray.c @@ -0,0 +1,25 @@ +#include +#include +int main() +{ + int A[5] = { 1,2,3,4,5 }; // this is allocated inside stack memory + int* p; // pointer of array + int i; + p = (int*)malloc(5 * sizeof(int)); // dynamically createing array inside heap + p[0] = 1; // initializing all the terms in array + p[1] = 2; + p[2] = 3; + p[3] = 4; + p[4] = 5; + + for (i = 0; i < 5; i++) // iteration for normal array + { + printf("%d ", A[i]); + } + printf("\n"); + for (i = 0; i < 5; i++) // iteration for the dynamic array + { + printf("%d ",p[i]); + } + return 0; +} diff --git a/Arrays/01_static_and_dynamicArray.exe b/Arrays/01_static_and_dynamicArray.exe new file mode 100644 index 00000000..c44a5844 Binary files /dev/null and b/Arrays/01_static_and_dynamicArray.exe differ diff --git a/Arrays/02_increasing_size_of_array_using_heap.cpp b/Arrays/02_increasing_size_of_array_using_heap.cpp new file mode 100644 index 00000000..99f0b2e7 --- /dev/null +++ b/Arrays/02_increasing_size_of_array_using_heap.cpp @@ -0,0 +1,26 @@ +/* Normal array is created in stack +and stack used memory array cannot be change +tht is we can not incresae the size of array */ + +#include +#include +int main () +{ + int *p,*q; // Taking two pointers + int i; + p=(int *)malloc(5*sizeof(int)); // array is created in heap memory + p[0]=9;p[1]=7;p[2]=22;p[3]=11;p[4]=12; + + q= (int *) malloc(10*sizeof(int)); // increasing size of array in heap memory + + for (i=0;i<5;i++) + q[i]=p[i]; + + free(p); + p=q; + q=NULL; + + for (i=0;i<5;i++) + printf("%d \n",p[i]); + return 0; +} diff --git a/Arrays/02_increasing_size_of_array_using_heap.exe b/Arrays/02_increasing_size_of_array_using_heap.exe new file mode 100644 index 00000000..11e7300b Binary files /dev/null and b/Arrays/02_increasing_size_of_array_using_heap.exe differ diff --git a/Arrays/03_Creating_2D_array_Accessing.c b/Arrays/03_Creating_2D_array_Accessing.c new file mode 100644 index 00000000..08a2aeaa --- /dev/null +++ b/Arrays/03_Creating_2D_array_Accessing.c @@ -0,0 +1,30 @@ + // Creating 2-D array +#include +#include +int main () +{ // normal delaration and initialization + int A[3][4]={{1,2,3,4},{2,4,6,8},{1,3,5,7}}; // stack memory + + // pointer decleration +int *B[3]; +int **C; // double pointer , completly in heap memory +int i,j; + +B[0]=(int *)malloc(4*sizeof(int)); // Creating memory in heap +B[1]=(int *)malloc(4*sizeof(int)); +B[2]=(int *)malloc(4*sizeof(int)); + +C=(int **)malloc(3*sizeof(int *)); +C[0]=(int *)malloc(4*sizeof(int)); +C[1]=(int *)malloc(4*sizeof(int)); +C[2]=(int *)malloc(4*sizeof(int)); + +for (i=0;i<3;i++) +{ +for (j=0;j<4;j++) +printf("%d ",A[i][j]); +printf("\n"); +} +return 0; +} + diff --git a/Arrays/03_Creating_2D_array_Accessing.exe b/Arrays/03_Creating_2D_array_Accessing.exe new file mode 100644 index 00000000..1d6055e0 Binary files /dev/null and b/Arrays/03_Creating_2D_array_Accessing.exe differ diff --git a/Arrays/04_Array_ADT.c b/Arrays/04_Array_ADT.c new file mode 100644 index 00000000..33fab254 --- /dev/null +++ b/Arrays/04_Array_ADT.c @@ -0,0 +1,40 @@ +#include +#include +struct Array +{ + int* A; + int size; + int length; +}; + +// fxn for display all the elements of the array + +void Display(struct Array arr) +{ + int i; + printf("Elements Are\n"); + for (i = 0; i < arr.length; i++) + printf("%d ",arr.A[i]); // it will display all the elements +} +int main() +{ + struct Array arr; + int n; // how many no is going to be inserted + int i; + printf("Enter size of an array "); + scanf_s("%d", &arr.size); + arr.A = (int*)malloc(arr.size * sizeof(int)); // dynamically created array + arr.length = 0;// intially no elements + printf("Enter number of numbers "); + scanf_s("%d", &n); + printf("Enter All the elements "); + for (i = 0; i < n; i++) + scanf_s("%d", &arr.A[i]); // enter the elements of an array + arr.length = n; // set length as n + + + Display(arr); + + + return 0; +} diff --git a/Arrays/05_inserting_an_element.cpp b/Arrays/05_inserting_an_element.cpp new file mode 100644 index 00000000..7568d0eb --- /dev/null +++ b/Arrays/05_inserting_an_element.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; +struct Array +{ + int A[10]; + int size; + int length; +}; +void Display(struct Array arr) +{ + int i; + cout<<"printing all the elements "<length < arr->size) + arr->A[arr->length++] = x; // increment the size of array and fit the elements // it will take the constant time +} +void Insert(struct Array* arr, int index, int x) // the index at which we want to enter // and the value we want tpo enter +{ + int i; + for (i = arr->length; i > index; i--) // we will strat from last of the array and shift the elements upto the given index + { + arr->A[i] = arr->A[i - 1]; // shifting the elements to next // i is on some index and copy the value from previous index + } + arr->A[index] = x; // set the value at the particular index + arr->length++; // increment the size of length + // work done shifting of elelmets and copying elements + // best case : --------------- min : O(1) // there may be zero shifting + // worst case : --------------- max : O(n)// there may be n shifing + +} + +int main() { + int no; + struct Array arr; + cout << "Enter the size of the array " << endl; + cin >> arr.size; + arr.A = new int[arr.size]; + arr.length = 0; + cout << "Enter the length of array" << endl; + cin >> no; + cout << "Enter all the elements of array" << endl; + for (int i = 0; i < no; i++) + cin >> arr.A[i]; + arr.length = no; + Add(&arr, 10); + Insert(&arr,3,25); + Display(arr); + + return 0; +} diff --git a/Arrays/06_Deleting_element_from_array.c b/Arrays/06_Deleting_element_from_array.c new file mode 100644 index 00000000..7f2fef78 --- /dev/null +++ b/Arrays/06_Deleting_element_from_array.c @@ -0,0 +1,45 @@ +#include + +struct Array +{ + int A[10]; + int length; + int size; +}; + +int Display(struct Array arr) +{ + int i; + printf("Elements Are\n"); + for (i=0;i) operator: + +The Dot(.) operator is used to normally access members of a structure or union. +The Arrow(->) operator exists to access the members of the structure or the unions using pointers. */ +{ + int x=0; + int i; + if (index>=0 && index length) + { + x=arr->A[index]; // first of all take out the element from the particular index you want to del---------------------> taking 1 unit of time + for (i=index;ilength-1;i++) // shift the element in forward direnction and stop at length -1 so that array can not have any vacant space + arr->A[i]=arr->A[i+1]; // at the place of a[i] copy the next element i.e a[i+1] + arr->length--;//at last the length will be decreatmented ----------------> 1 unit of time -------> so best time is 1+1 =2 + + // min shifting is 0 and max shifting is n ----> Best case time is O(1) -> Worst Case time is ----> O(n) + return x; + } + return 0; +} +int main () +{ + struct Array arr1={{1,2,3,4,56,5,2},10,5}; + printf("%d\n",Delete(&arr1,0)); + Display(arr1); + return 0; +} diff --git a/Arrays/07_Linearsearch.c b/Arrays/07_Linearsearch.c new file mode 100644 index 00000000..556cc36a --- /dev/null +++ b/Arrays/07_Linearsearch.c @@ -0,0 +1,31 @@ +#include +struct Array { + int A[20]; + int length; + int size; + +}; +void Display (struct Array arr) +{ + int i; + printf("\nEnter elements\n"); + for (i=0;i +struct Array { + int A[20]; + int length; + int size; + +}; +void Display (struct Array arr) +{ + int i; + printf("\nEnter elements\n"); + for (i=0;ilength;i++) // iterating through the list + { + if(key==arr->A[i]) // checking whether elements is equal to the key elements or not + { + swap(&arr->A[i],&arr->A[0]); // this is move to 1st method // from this we can reduce time to O(1) // when we will search the same element again + return i; + } + } + return -1; +} + +int main () +{ + struct Array arr1= {{2,3,4,2,3,4,5,88,9 },20,5 }; + printf("The element is at %dth index",LinearSearch(&arr1,9)); + Display(arr1); + return 0; +} diff --git a/Arrays/09_Binary_Search_using_loop.c b/Arrays/09_Binary_Search_using_loop.c new file mode 100644 index 00000000..631a0465 --- /dev/null +++ b/Arrays/09_Binary_Search_using_loop.c @@ -0,0 +1,39 @@ +#include +struct Array +{ + int A[10]; + int size; + int length; +}; + void Display(struct Array arr) + { + int i; + printf("\nElements are\n"); + for(i=0;i +struct Array { + int A[10]; + int length; + int size; + +}; +void Display (struct Array arr) +{ + int i; + printf("Enter all the elements "); + for (i=0;i +struct Array +{ + int A[20]; + int length; + int size; +}; +void Display (struct Array arr) +{ + int i; + printf("Enter elements "); + for (i=0;i=0 && index=0 && indexlength) + arr->A[index]=x; + return 0; +} + +int Max (struct Array arr) +{ + int max=arr.A[0]; + int i; + for (i=1;imax) + max=arr.A[i]; + } + return max; +} +int Min (struct Array arr) +{ + int min=arr.A[0]; + int i; + for (i=1;i + +struct Array +{ + int A[20]; + int length; + int size; +}; +void Display (struct Array arr) +{ + int i; + for (i=0;isize]; // creating the required size of array in heap + for (i = arr->length - 1, j = 0; i >= 0; i--, j++) // keeping all the elements from array a to b in reverse order + B[j] = arr->A[i]; // coping element everytime + for (i = 0; i < arr->length; i++) + arr->A[i] = B[i]; // copying back elements to A +} + +void Reverse1(struct Array* arr) +{ + int i, j; + for (i = 0, j = arr->length - 1; i < j; i++, j--) // we will interchange 1st with the last element + Swap(&arr->A[i], &arr->A[j]); // swapping 1st with the last + +} + + +int main() + +{ + struct Array arr1={{2,3,4,56,66,69,98},7,20}; + // Call any one method to execute + Reverse(&arr1); // Shifting + Reverse1(&arr1); // 2nd method by swapping 1st with last i.e rotating + Display(arr1); + return 0; +} diff --git a/Arrays/13_IsSorted .cpp b/Arrays/13_IsSorted .cpp new file mode 100644 index 00000000..94e13501 --- /dev/null +++ b/Arrays/13_IsSorted .cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +struct Array +{ + int* A; + int size; + int length; +}; +void Display(struct Array* arr) +{ + int i; + cout << "the elements of the array is " << endl; + for (i = 0; i < arr->length; i++) + cout <A[i] << " "; +} + +int IsSorted(struct Array* arr) +{ + for (int i = 0; i < arr->length - 1; i++) + { + if (arr->A[i] > arr->A[i + 1]) // if 1st element is greater then 2nd element then it will k/as not sorted so return 0 + return 0; + } + + return 1; // if everything is ok and the element came successfully out of loop means it is sorted return 1 for thet +} +int main() +{ + struct Array arr; + cout << "Enter the size of Array " << endl; + cin >> arr.size; + arr.A = new int[arr.size]; + int no; + cout << "Enter the length of the array " << endl; + cin >> no; + arr.length = 0; + cout << "Enter the elements of the array " << endl; + for (int i = 0; i < no; i++) + cin >> arr.A[i]; + arr.length = no; + cout< +#include +//Merging 2 Arrays +struct Array +{ + int A[10]; + int size; + int length; +}; +void Display(struct Array arr) +{ + int i; + printf("\nElements are\n"); + for(i=0;ilength && jlength) + { + if(arr1->A[i]A[j]) + arr3->A[k++]=arr1->A[i++]; + else + arr3->A[k++]=arr2->A[j++]; + } + for(;ilength;i++) + arr3->A[k++]=arr1->A[i]; + for(;jlength;j++) + arr3->A[k++]=arr2->A[j]; + arr3->length=arr1->length+arr2->length; + arr3->size=10; + + return arr3; +} +int main() +{ + struct Array arr1={{2,9,21,28,35},10,5}; + struct Array arr2={{2,3,16,18,28},10,5}; + struct Array *arr3; +arr3=Merge(&arr1,&arr2); +Display(*arr3); + +return 0; +} + diff --git a/Arrays/14_Mergeing_2_Array.exe b/Arrays/14_Mergeing_2_Array.exe new file mode 100644 index 00000000..441aa426 Binary files /dev/null and b/Arrays/14_Mergeing_2_Array.exe differ diff --git a/Arrays/15_InsertSort .c b/Arrays/15_InsertSort .c new file mode 100644 index 00000000..45d31613 --- /dev/null +++ b/Arrays/15_InsertSort .c @@ -0,0 +1,43 @@ +#include + +struct Array +{ + int A[20]; + int length; + int size; +}; +void Display (struct Array arr) +{ + int i; + for (i=0;ilength-1; + if (arr->length==arr->size) return ; + while (i>=0 && arr->A[i]>x) + { + arr->A[i+1]=arr->A[i]; + i--; + } + + + + arr->A[i+1]=x; + + arr->length++; + +} + + +int main() + +{ + struct Array arr={{2,3,5,10,15},5,20}; + InsertSort(&arr,1); + Display(arr); + return 0; +} diff --git a/Arrays/16_Set_Operation.c b/Arrays/16_Set_Operation.c new file mode 100644 index 00000000..fd1a7c53 --- /dev/null +++ b/Arrays/16_Set_Operation.c @@ -0,0 +1,114 @@ +#include +#include +#include +//Set Operations on Arrays +struct Array +{ + int A[10]; + int size; + int length; +}; +void Display(struct Array arr) +{ + int i; + printf("\nElements are\n"); + for(i=0;ilength && jlength) + { + if(arr1->A[i]A[j]) + arr3->A[k++]=arr1->A[i++]; + else if(arr2->A[j]A[i]) + arr3->A[k++]=arr2->A[j++]; + else + { + arr3->A[k++]=arr1->A[i++]; + j++; + } + } + for(;ilength;i++) + arr3->A[k++]=arr1->A[i]; + for(;jlength;j++) + arr3->A[k++]=arr2->A[j]; + + arr3->length=k; + arr3->size=10; + + return arr3; +} +struct Array* Intersection(struct Array *arr1,struct Array +*arr2) +{ + int i,j,k; + i=j=k=0; + + struct Array *arr3=(struct Array *)malloc(sizeof(struct +Array)); + + while(ilength && jlength) + { + if(arr1->A[i]A[j]) + i++; + else if(arr2->A[j]A[i]) + j++; + else if(arr1->A[i]==arr2->A[j]) + { + arr3->A[k++]=arr1->A[i++]; + j++; + } + } + + arr3->length=k; + arr3->size=10; + + return arr3; +} +struct Array* Difference(struct Array *arr1,struct Array +*arr2) +{ + int i,j,k; + i=j=k=0; + + struct Array *arr3=(struct Array *)malloc(sizeof(struct +Array)); + + while(ilength && jlength) + { + if(arr1->A[i]A[j]) + arr3->A[k++]=arr1->A[i++]; + else if(arr2->A[j]A[i]) + j++; + else + { + i++; + j++; + } + } + for(;ilength;i++) + arr3->A[k++]=arr1->A[i]; + + + arr3->length=k; + arr3->size=10; + + return arr3; +} +int main() +{ + struct Array arr1={{2,9,21,28,35},10,5}; + struct Array arr2={{2,3,9,18,28},10,5}; + struct Array *arr3; +arr3=Union(&arr1,&arr2); +Display(*arr3); + +return 0; +} diff --git a/Arrays/16_Set_Operation.exe b/Arrays/16_Set_Operation.exe new file mode 100644 index 00000000..6538c53e Binary files /dev/null and b/Arrays/16_Set_Operation.exe differ diff --git a/Arrays/17_nsertion_and_Deletion.cpp b/Arrays/17_nsertion_and_Deletion.cpp new file mode 100644 index 00000000..971f322a --- /dev/null +++ b/Arrays/17_nsertion_and_Deletion.cpp @@ -0,0 +1,90 @@ +#include +// Here namespace is having obj like cin and cout ; +using namespace std; +class Array // Creating class +// Class in c++ will have Datamember and member function +{ + private: + int *A; // Creating in heap so that i can dynamically create an array + int size; + int length; + + public: // Member function must be inside public + // Write an constructor + Array () // This is non parameter constructor + { + size=10; + A = new int[10]; // dynamically created array in heap + length=0; + + } + + // parametetrzied Constructor + + Array (int sz) + { + size=sz; + length=0; + A=new int [size]; + } + + +// We must have destructors to release resourses + ~Array() // Creating Destructor + { + delete []A; + } + + // Writting Function + void Display (); // There sud not be parameter cz this is part of Array function + void Insert (int index, int x); + int Delete (int index); + +}; + +void Array :: Display () +{ + for (int i=0; i=0 && index <=length ) + { + for (int i=length-1;i>index;i--) + A[i+1]=A[i]; + A[index]=x; + length++; + } + } + +int Array :: Delete (int index) +{ + int x=0; + if (index>=0 && index +using namespace std; +class Array +{ +private: + int *A; + int size; + int length; + void swap(int *x,int *y); + +public: + Array() + { + size=10; + length=0; + A=new int[size]; + } + Array(int sz) + { + size=sz; + length=0; + A=new int[size]; + } + ~Array() + { + delete []A; + } + void Display(); + void Append(int x); + void Insert(int index,int x); + int Delete(int index); + int LinearSearch(int key); + int BinarySearch(int key); + int Get(int index); + void Set(int index,int x); + int Max(); + int Min(); + int Sum(); + float Avg(); + void Reverse(); + void Reverse2(); + void InsertSort(int x); + int isSorted(); + void Rearrange(); + Array* Merge(Array arr2); + Array* Union(Array arr2); + Array* Diff(Array arr2); + Array* Inter(Array arr2); +}; +void Array::Display() +{ + int i; + cout<<"\nElements are\n"; + for(i=0;i=0 && index <=length) + { + for(i=length;i>index;i--) + A[i]=A[i-1]; + A[index]=x; + length++; + + } +} +int Array::Delete(int index) +{ + int x=0; + int i; + + if(index>=0 && index=0 && index=0 && index< length) + A[index]=x; +} +int Array::Max() +{ + int max=A[0]; + int i; + for(i=1;imax) + max=A[i]; + } + return max; +} +int Array::Min() +{ + int min=A[0]; + int i; + for(i=1;i=0;i--,j++) + B[j]=A[i]; + for(i=0;i=0 && A[i]>x) + { + A[i+1]= A[i]; + i--; + } + A[i+1]=x; + length++; + +} +int Array::isSorted() +{ + int i; + for(i=0;iA[i+1]) + return 0; + } + return 1; +} +void Array::Rearrange() +{ + int i,j; + i=0; + j= length-1; + + while(i=0)j--; + if(iA[k++]=A[i++]; + else + arr3->A[k++]=arr2.A[j++]; + } + for(;iA[k++]=A[i]; + for(;jA[k++]=arr2.A[j]; + arr3->length=length+arr2.length; + + return arr3; +} +Array* Array::Union(Array arr2) +{ + int i,j,k; + i=j=k=0; + + Array *arr3=new Array(length+arr2.length); + + while(iA[k++]=A[i++]; + else if(arr2.A[j]A[k++]=arr2.A[j++]; + else + { + arr3->A[k++]=A[i++]; + j++; + } + } + for(;iA[k++]=A[i]; + for(;jA[k++]=arr2.A[j]; + + arr3->length=k; + + return arr3; +} +Array* Array::Inter(Array arr2) +{ + int i,j,k; + i=j=k=0; + + Array *arr3=new Array(length+arr2.length); + + while(iA[k++]=A[i++]; + j++; + } + } + + arr3->length=k; + + return arr3; +} +Array* Array::Diff(Array arr2) +{ + int i,j,k; + i=j=k=0; + + Array *arr3=new Array(length+arr2.length); + + while(iA[k++]=A[i++]; + else if(arr2.A[j]A[k++]=A[i]; + + + arr3->length=k; + + return arr3; +} +int main() +{ + Array *arr1; + int ch,sz; + int x,index; + + cout<<"Enter Size of Array"; + scanf("%d",&sz); + arr1=new Array(sz); + + do + { + cout<<"\n\nMenu\n"; + cout<<"1. Insert\n"; + cout<<"2. Delete\n"; + cout<<"3. Search\n"; + cout<<"4. Sum\n"; + cout<<"5. Display\n"; + cout<<"6.Exit\n"; + + cout<<"enter you choice "; + cin>>ch; + + switch(ch) + { + case 1: cout<<"Enter an element and index "; + cin>>x>>index; + arr1->Insert(index,x); + break; + case 2: cout<<"Enter index "; + cin>>index; + x=arr1->Delete(index); + cout<<"Deleted Element is"<>x; + index=arr1->LinearSearch(x); + cout<<"Element index "<Sum(); + break; + case 5:arr1->Display(); + + } + + }while(ch<6); + return 0; +} diff --git a/Arrays/19_Single_Missing_Element_in_Sorted_Array.cpp b/Arrays/19_Single_Missing_Element_in_Sorted_Array.cpp new file mode 100644 index 00000000..fc2cfa80 --- /dev/null +++ b/Arrays/19_Single_Missing_Element_in_Sorted_Array.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; +int main() +{ + int a[11] = { 6,7,8,9,10,12,13,14,15,16,17 }; + int n = sizeof(a) / sizeof(int); + int diff = a[0]; //initialising diff with fisrt element of the array + + //We will check the difference between the index element and array index + //Wherever the difference wiil not be equal to diff, an element is missing there + + for (int i = 0; i < n; i++) + { + if (a[i] - i != diff) //checking the difference betweeen the index element and array index if it is equal to diff or not + { + cout << "Missing element is: " << i + diff << endl; + diff++; //incrementing the diff value since from now on difference will be an updated value + } + } + cout << endl; + return 0; +} diff --git a/Arrays/20_Single_Missing_Value_in_a_sorted_array_M2.c b/Arrays/20_Single_Missing_Value_in_a_sorted_array_M2.c new file mode 100644 index 00000000..32c69d54 --- /dev/null +++ b/Arrays/20_Single_Missing_Value_in_a_sorted_array_M2.c @@ -0,0 +1,34 @@ +#include +struct Array +{ + int A[20]; + int length; + int size; +}; + +void Display (struct Array arr) +{ + int i; + for (i=0;i +using namespace std ; +int main () +{ + int A[11]= { 6,7,8,9,11,12,15,16,17,18,19 }; + int diff=A[0]; + int n= sizeof(A)/sizeof(int); + for (int i=0;i +using namespace std; +int main() +{ + int a[8] = { 1,2,3,5,6,8,12,14 }; + int n = sizeof(a) / sizeof(int); + int h[14] = { 0 }; //Hash table with size equal to the largest element present in the array a ie 14 + for (int i = 0; i < n; i++) //for loop to increment values at indices equal to the element in first array + h[a[i]]++; + for (int i = 1; i <= 14; i++) + { + if (h[i] == 0) //to check which indices are 0 so those elements are missing + cout << "Missing element is: " << i << endl; + } + cout << endl; + return 0; +} diff --git a/Arrays/23_Finding_Duplicate_in_Sorted_Array.cpp b/Arrays/23_Finding_Duplicate_in_Sorted_Array.cpp new file mode 100644 index 00000000..659c92c4 --- /dev/null +++ b/Arrays/23_Finding_Duplicate_in_Sorted_Array.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +int main () +{ + int A[10]={3,6,8,8,10,12,15,15,15,20}; + int lastduplicate=0; + int i,no=10; + + cout<<"Duplicate Elements are "< +using namespace std ; +int main () +{ + int i,j; + int A[13]={3,6,8,8,8,10,12,12,12,15,20,20,20}; + + for(i=0;i<13;i++) + { + if (A[i]==A[i+1]) + { + j=i+1; + while (A[j]==A[i]) + j++; + cout< +using namespace std; +int main () +{ + int i; + int A[15]={1,2,4,5,6,7,8,8,8,8,9,10,10,10}; + int H[15]={0}; // Creating A hash table of as all elements As zero + + for (i=0;i<15;i++) // ----------- n + { + H[A[i]]++; + } + for (i=0;i<15;i++) // ----------------n = n+n=2n + { + if (H[i]>1) + cout< +using namespace std; +int main() +{ + + int a[16] = {8,3,6,4,6,5,6,8,2,7,8,55,55,55,99,99}; + for(int i=0;i<15;i++) + { + int count = 1; + if(a[i]!=-1) + { + for(int j=i+1;j<16;j++) + { + if(a[j]==a[i]) + { + count++; + a[j]=-1; + } + } + if(count>1) + cout<<"Duplicate element is: "< +using namespace std; +int main () +{ + int A[10]={1,2,4,5,6,8,10,12,14,15}; + int n =sizeof(A)/sizeof(int); + int k=10 ;// sum of pair of element is 10 + int i,j; + i=0; + j=n-1; + while (i +#include + +struct array +{ + int *A; + int size; + int length; +}; + + +void Display(struct array arr); +void Append(struct array *arr,int x); +void Insert(struct array *arr,int index,int x); +void Delete(struct array *arr,int index); +void swap(int*p,int*q); +void LinearSearch(struct array *arr,int key); +void LinearSearchSwapToPrev(struct array *arr,int key); +void LinearSearchSwapToHead(struct array *arr,int key); +void BinSearch(struct array *arr,int key); +void RevBinSearch(struct array arr,int low,int high,int key); +void Get(struct array arr,int index); +void Set(struct array *arr,int index,int x); +void Max(struct array arr); +void Min(struct array arr); +int Sum(struct array arr); +float Avg(struct array arr); +void Rev1(struct array *arr); +void Rev2(struct array *arr); +void Display(struct array arr); +void lShift(struct array *arr); +void rShift(struct array *arr); +void lRot(struct array *arr); +void rRot(struct array *arr); +void InsertSort(struct array *arr,int x); +void IsSort(struct array arr); +void Arrange(struct array *arr); +struct array* Merge(struct array *arr,struct array *arr2); + + + +// All the functions are here->>>> + +//Swap Function +void swap(int*p,int*q) +{ + int temp; + temp=*p; + *p=*q; + *q=temp; +} + +//Display Function +void Display(struct array arr) +{ + int i; + printf("The elements in the array are: \n"); + for(i=0;ilengthsize) + { + arr->A[arr->length]=x; + arr->length++; + } + else + { + printf("The array has no empty space to append"); + } +} + +//Insert Function +void Insert(struct array *arr,int index,int x) +{ + int i; + if(arr->lengthsize) + { + if(index>=0 && index<=arr->length) + { + for(i=arr->length;i>index;i--) + { + arr->A[i]=arr->A[i-1]; + } + arr->A[index]=x; + arr->length++; + } + else + { + printf("You cannot insert the value due to the invalid index. \n"); + } + } + else + { + printf("The size is not sufficient to insert the element in the array.\n"); + } +} + +//Delete Function +void Delete(struct array *arr,int index) +{ + int i; + if(index>=0 && index<=arr->length) + { + for(i=index;ilength;i++) + { + arr->A[i]=arr->A[i+1]; + } + arr->length--; + } + else + { + printf("You can delete the element due to invalid \n"); + } +} + +//LinearSearch Normal Method Funtion +void LinearSearch(struct array *arr,int key) +{ + int i,x=0; + for(i=0;ilength;i++) + { + if(arr->A[i]==key) + { + printf("The element is found at location %d\n",i); + x=1; + break; + } + } + if(!x) + { + printf("The element is not present in the array\n"); + } +} + +//LinearSearch Move to previous index Function +void LinearSearchSwapToPrev(struct array *arr,int key) +{ + int i,x=0; + for(i=0;ilength;i++) + { + if(arr->A[i]==key) + { + swap(&arr->A[i],&arr->A[i-1]); + printf("The element is found at the location %d\n",i); + x=1; + break; + } + } + if(!x) + { + printf("The element is not present in the array\n"); + } +} + +//LinearSearch Move to Head/First index Function +void LinearSearchSwapToHead(struct array *arr,int key) +{ + int i,x=0; + for(i=0;ilength;i++) + { + if(arr->A[i]==key) + { + swap(&arr->A[i],&arr->A[0]); + printf("The element is found at the location %d\n",i); + x=1; + break; + } + } + if(!x) + { + printf("The element is not present in the array\n"); + } +} + +//Binary Search Normal method Function +void BinSearch(struct array *arr,int key) +{ + int low=0; + int high=arr->length-1; + int mid,x=0; + while(low<=high) + { + mid=(low+high)/2; + if(arr->A[mid]==key) + { + printf("The element is found at index %d",mid); + x=1; + break; + } + else if(keyA[mid]) + { + high=mid-1; + } + else if(key>arr->A[mid]) + { + low=mid+1; + } + } + if(x==0) + { + printf("The element is not found\n"); + } +} + +//Binary Search Recursion method Function +void RevBinSearch(struct array arr,int low,int high,int key) +{ + int mid,x=0; + if(low<=high) + { + mid=(low+high)/2; + if(arr.A[mid]==key) + { + printf("The element is found at location %d\n",mid); + x=1; + } + else if(keyarr.A[mid]) + { + RevBinSearch(arr,mid+1,high,key); + } + } + else + { + printf("The element is not found\n"); + } + +} + +//Get Function +void Get(struct array arr,int index) +{ + if(index>=0 && index=0 && indexlength) + { + arr->A[index]=x; + } + else + { + printf("The given index is not valid"); + } +} + +//Max Function +void Max(struct array arr) +{ + int i; + int max=arr.A[0]; + for(i=0;isize*sizeof(int)); + for(i=arr->length-1,j=0;i>=0,jsize;i--,j++) + { + B[j]=arr->A[i]; + } + for(i=0;isize;i++) + { + arr->A[i]=B[i]; + } +} + +//Reverse the array bby swapping each equidistant element +void Rev2(struct array *arr) +{ + int i,j; + for(i=0,j=arr->length-1;iA[i],&arr->A[j]); + } +} + +//Left Shift Function +void lShift(struct array *arr) +{ + int i; + for(i=0;ilength-1;i++) + { + arr->A[i]=arr->A[i+1]; + } + printf("\nThe elements in the array after left shift are: \n"); + for(i=0;ilength-1;i++) + { + printf("%d ",arr->A[i]); + } +} + +//Right Shift Function +void rShift(struct array *arr) +{ + int i; + for(i=arr->length-1;i>0;i--) + { + arr->A[i]=arr->A[i-1]; + } + printf("\nThe elements in the array after right shift are: \n"); + for(i=1;i<=arr->length-1;i++) + { + printf("%d ",arr->A[i]); + } +} + +//Left Rotation Function +void lRot(struct array *arr) +{ + int i,x; + x=arr->A[0]; + for(i=0;ilength-1;i++) + { + arr->A[i]=arr->A[i+1]; + } + arr->A[arr->length-1]=x; + printf("\nThe elements in the array after left rotation are: \n"); + for(i=0;i<=arr->length-1;i++) + { + printf("%d ",arr->A[i]); + } +} + +//Left Rotation Function +void rRot(struct array *arr) +{ + int i,x; + x=arr->A[arr->length-1]; + for(i=arr->length-1;i>0;i--) + { + arr->A[i]=arr->A[i-1]; + } + arr->A[0]=x; + printf("\nThe elements in the array after right rotation are: \n"); + for(i=0;i<=arr->length-1;i++) + { + printf("%d ",arr->A[i]); + } +} + +//Insert in sorted array Funtion +void InsertSort(struct array *arr,int x) +{ + int i; + if(arr->lengthsize) + { + for(i=arr->length-1;xA[i];i--) + { + arr->A[i+1]=arr->A[i]; + } + arr->A[i+1]=x; + arr->length++; + } + else + { + printf("The elements canot be inserted due to no empty spaces\n"); + } +} + +//Is sorted or not Function +void IsSort(struct array arr) +{ + int i,x=1; + for(i=0;iarr.A[i+1]) + { + x=0; + break; + } + } + if(x) + { + printf("The elements are in sorted order"); + } + else + { + printf("The elements are not in sorted order"); + } +} + +//-ve on left side and +ve on right side +void Arrange(struct array *arr) +{ + int i=0,j=arr->length-1; + while(arr->A[i]<0) + { + i++; + } + while(arr->A[j]>0) + { + j--; + } + if(iA[i],&arr->A[j]); + } +} + +struct array* Merge(struct array *arr,struct array *arr2) +{ + int i,j,k; + i=j=k=0; + struct array *arr3=(struct array *)malloc(sizeof(struct array)); + while(ilength && jlength) + { + if(arr->A[i]A[j]) + { + arr3->A[k]=arr->A[i]; + i++;k++; + } + else + { + arr3->A[k]=arr2->A[j]; + j++;k++; + } + } + for(;ilength;i++) + { + arr3->A[k]=arr->A[i]; + k++; + } + for(;jlength;j++) + { + arr3->A[k]=arr2->A[j]; + k++; + } + arr3->size=arr->size+arr2->size; + arr3->length=arr->length+arr2->length; + return arr3; +} + + + + + +//Main Function +int main() +{ + int i,ch,n,m,x,index; + struct array arr,arr2,*arr3; + printf("Enter the size of the array: \n"); + scanf("%d",&arr.size); + arr.A=(int*)malloc(arr.size*sizeof(int)); + arr.length=0; + printf("Enter the numner of element you want in the array: \n"); + scanf("%d",&n); + arr.length=n; + printf("Enter the elements in the array: \n"); + for(i=0;i> &matrix, int target) + { + // nrows---> Number of rows, mcols---> Number of columns + int nrows = matrix.size(); + int mcols = matrix[0].size(); // Because, No. of columns = length of any particular row + + int start = 0; + int end = nrows * mcols - 1; + int mid = (start + end) / 2; // Finding mid index + + while (start <= end) + { + mid = (start + end) / 2; + + int element = matrix[mid / mcols][mid % mcols]; // Finding the element at mid index + + if (element == target) + { + return true; + } + else if (element < target) + { + start = mid + 1; + } + else //(element > target) + { + end = mid - 1; + } + } + return 0; + } +}; \ No newline at end of file diff --git a/Arrays/32_Leaders_in_Array.cpp b/Arrays/32_Leaders_in_Array.cpp new file mode 100644 index 00000000..9a4a9c9f --- /dev/null +++ b/Arrays/32_Leaders_in_Array.cpp @@ -0,0 +1,57 @@ +/* +Given an integer array A of size n. +Find and print all the leaders present in the input array. +An array element A[i] is called Leader, if all the elements following it (i.e. present at its right) are less than or equal to A[i]. +Print all the leader elements separated by space and in the same order they are present in the input array. + +Input Format : +Line 1 : Integer n, size of array +Line 2 : Array A elements (separated by space) +Output Format : leaders of array (separated by space) + +Constraints : 1 <= n <= 10^6 +Sample Input 1 : 6 3 12 34 2 0 -1 +Sample Output 1 : 34 2 0 -1 + +Sample Input 2 : 5 13 17 5 4 6 +Sample Output 2 : 17 6 +*/ +#include +#include +using namespace std; +void Leaders(int* arr,int len) +{ + for(int i=0;i=arr[j])){ + isbig=false; + break; + } + // if they are arranged as they should be as in the case of leaders then change the flag to true + // Or you can leave the flag unchanged as it is ....! + // In the below codes are added for better understanding and Workflow. + else{ + isbig=true; + continue; + } + } + if(isbig){ + // Print the element for Leaders..! + cout<>len; + int *arr = new int[len + 1]; + + for(int i=0;i>arr[i]; + } + Leaders(arr,len); +} \ No newline at end of file diff --git a/Arrays/32_Operations_on_arrays.c b/Arrays/32_Operations_on_arrays.c new file mode 100644 index 00000000..2649bfff --- /dev/null +++ b/Arrays/32_Operations_on_arrays.c @@ -0,0 +1,314 @@ +// header files +#include +#include + +// global variables +int menuOption, process = 0; + +// array and its properties +struct array +{ + int counter; + int array1[10]; +} a1; + +// setting value of variables inside the struct +void setValues() +{ + a1.counter = 0; +} + +// main menu +int menu() +{ + printf("Press 1 for insertion\n"); + printf("Press 2 for deletion\n"); + printf("Press 3 for traversing\n"); + printf("Press 4 for linear search\n"); + printf("Press 5 for selection sort\n"); + printf("Press 9 to exit\n"); + scanf("%d", &menuOption); +} + +int menu1() +{ + printf("Press 1 for insertion\n"); + printf("Press 9 to exit\n"); + scanf("%d", &menuOption); +} + +// operation functions +void printArr() +{ + if (a1.counter == 0) + { + printf("The array is empty\n"); + } + else + { + printf("The array is : "); + for (int i = 0; i < a1.counter - 1; i++) + { + printf("%d, ", a1.array1[i]); + } + printf("%d\n", a1.array1[a1.counter - 1]); + } + printf("\n"); +} + +int insertion() +{ + int element, index, choice; + int beginning() + { + printf("Enter element to insert at the beginnning\n"); + scanf("%d", &element); + if (a1.counter>0) + { + for (int i = a1.counter; i >=0 ; i--) + { + a1.array1[i] = a1.array1[i-1]; + } + } + a1.array1[0] = element; + a1.counter++; + printArr(); + } + int atIndex() + { + printf("Enter the index: "); + scanf("%d", &index); + if (index<=a1.counter) + { + printf("Enter element to insert at the index:%d\n", index); + scanf("%d", &element); + + for (int i = a1.counter; i > index; i--) + { + a1.array1[i] = a1.array1[i-1]; + } + a1.array1[index] = element; + a1.counter++; + printArr(); + } + // checks + else + { + printf("Please enter correct index"); + } + + } + int end() + { + printf("Enter element to insert at the end\n"); + scanf("%d", &element); + a1.array1[a1.counter] = element; + a1.counter++; + printArr(); + } +insertOneCheckpoint: + switch (a1.counter) + { + case 0: + beginning(); + break; + + case 2 ... 9: + printf("Enter 1 to enter in the beginning\n"); + printf("Enter 2 to enter in the end\n"); + printf("Enter 3 to enter at a specific index\n"); + scanf("%d", &choice); + if (choice == 1) + { + beginning(); + } + else if (choice == 2) + { + end(); + } + else if (choice == 3) + { + atIndex(); + } + else + { + printf("Choice out of range\n"); + goto insertOneCheckpoint; + } + break; + default: + printf("Index out of bounds\n"); + break; + + case 1: + printf("Enter 1 to enter in the beginning\n"); + printf("Enter 2 to enter in the end\n"); + scanf("%d", &choice); + if (choice == 1) + { + beginning(); + } + else if (choice == 2) + { + end(); + } + else + { + printf("Choice out of range\n"); + goto insertOneCheckpoint; + } + break; + } +} + +int deletion() +{ + int index; +insertDeleteCheckpoint: + printf("Enter the index of the element you want to delete\n"); + scanf("%d", &index); + if (index >= 0 && index <= a1.counter) + { + for (int i = index; i <= a1.counter; i++) + { + a1.array1[i] = a1.array1[i + 1]; + } + a1.counter--; + printArr(); + } + else + { + printf("Index out of range\n"); + goto insertDeleteCheckpoint; + } +} + +int traversing() +{ + int index; +insertTraverseCheckpoint: + printf("Enter the index of the element\n"); + scanf("%d", &index); + if (index >= 0 && index <= a1.counter) + { + printf("%d", a1.array1[index]); + } + else + { + printf("Index out of range"); + goto insertTraverseCheckpoint; + } + printArr(); +} + +int traversing2(){ + for (int i = 0; i < a1.counter; i++) + { + printf("%d\n",i); + } + printArr(); +} + +int searching() +{ + int element, crash = -1; +insertSearchingCheckpoint: + printf("Enter the element you want to search for: \n"); + scanf("%d", &element); + for (int i = 0; i < a1.counter; i++) + { + if (a1.array1[i] == element) + { + crash = i; + } + } + if (crash >= 0) + { + printf("The index of %d is %d\n", element, crash); + } + else + { + printf("No element found\n"); + goto insertSearchingCheckpoint; + } +} + +int sorting() +{ + int min, crash, temp; + for (int i = 0; i < a1.counter; i++) + { + min = a1.array1[i]; + for (int j = i + 1; j < a1.counter; j++) + { + if (a1.array1[j] < min) + { + min = a1.array1[j]; + crash = j; + } + } + temp = a1.array1[i]; + a1.array1[i] = min; + a1.array1[crash] = temp; + } + printArr(); +} + +// main function +int main() +{ + setValues(); + printArr(); +showMenu: + if (a1.counter == 0) + { + menu1(); + switch (menuOption) + { + case 1: + insertion(); + break; + case 9: + exit(0); + break; + default: + printf("Please enter correct input\n"); + goto showMenu; + break; + } + } + + else + { + menu(); + switch (menuOption) + { + case 1: + insertion(); + break; + case 2: + deletion(); + break; + case 3: + traversing2(); + break; + case 4: + searching(); + break; + case 5: + sorting(); + break; + case 9: + exit(0); + break; + default: + printf("Please enter correct input\n"); + goto showMenu; + break; + } + } + + // making sure our menu runs inside a loop + goto showMenu; + return 0; +} \ No newline at end of file diff --git a/Arrays/33_Sort_0_1_2.cpp b/Arrays/33_Sort_0_1_2.cpp new file mode 100644 index 00000000..0a75829c --- /dev/null +++ b/Arrays/33_Sort_0_1_2.cpp @@ -0,0 +1,81 @@ +/* + +You are given an integer array/list(ARR) of size N. +It contains only 0s, 1s and 2s. +Write a solution to sort this array/list in a 'single scan'. +'Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once. +Note: You need to change in the given array/list itself. +Hence, no need to return or print anything. + +Input format : The first line contains an Integer 't' which denotes the number of test cases or queries to be run. +Then the test cases follow. + +First line of each test case or query contains an integer 'N' representing the size of the array/list. + +Second line contains 'N' single space separated integers(all 0s, 1s and 2s) representing the elements in the array/list. Output Format : For each test case, print the sorted array/list elements in a row separated by a single space. + +Output for every test case will be printed in a separate line. +Constraints : +1 <= t <= 10^2 0 <= N <= 10^5 +Time Limit: 1 sec + +Sample Input 1: 1 7 0 1 2 0 2 0 1 +Sample Output 1: 0 0 0 1 1 2 2 + +Sample Input 2: 2 5 2 2 0 1 1 7 0 1 2 0 1 2 0 +Sample Output 2: 0 1 1 2 2 0 0 0 1 1 2 2 + +*/ +#include +using namespace std; + +void simplifiedsort012(int *arr, int n){ + + int i=0,nz=0,nt=n-1; + while(i>n; + int *arr=new int[n]; + cout<<"Enter Elements in the Array "<>arr[i]; + } + simplifiedsort012(arr,n); + return 0; +} + +/* +Explanation +👉🏼Take two variables as starting(nz) and ending(nt) depicting position of 0's and 2's to be swapped respectively + +👉🏼Initialize nz as Starting Index i.e 0 and increment it after every swap + +👉🏼Initialize nt as Ending Index i.e Size-1 and decrement it after every swap + +Special Attention should be given to the following points :) +✨Swap 0's and increment nz & i + +✨Swap 2's and increment nt but not i (ignore the updation of expression) +*/ \ No newline at end of file diff --git a/Arrays/4.MedianofTwoSortedArray.cpp b/Arrays/4.MedianofTwoSortedArray.cpp new file mode 100644 index 00000000..80a10578 --- /dev/null +++ b/Arrays/4.MedianofTwoSortedArray.cpp @@ -0,0 +1,21 @@ +//Name ;- Pushkar Roy +//Date :- 05-10-2022 + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + for(int i=0; i + +int fact(int n) +{ + if(n==0)return 1; + return fact(n-1)*n; +} +int nCr(int n,int r) +{ + int num,den; + + num=fact(n); + den=fact(r)*fact(n-r); + + return num/den; +} +int NCR(int n,int r) +{ + if(n==r || r==0) + return 1; + return NCR(n-1,r-1)+NCR(n-1,r); + +} +int main() +{ + printf("%d \n",NCR(5,3)); + return 0; +} diff --git a/Arrays/_removeElement.cpp b/Arrays/_removeElement.cpp new file mode 100644 index 00000000..0911d599 --- /dev/null +++ b/Arrays/_removeElement.cpp @@ -0,0 +1,44 @@ +/*Problem You are given an array A=[A1 ,A2 ​ ,…,AN ​ ] consisting of N positive integers. You are also given a constant K, using which you can perform the following operation on AA: Choose two distinct indices ii and jj such that A_i ​ +A_j ​ ≤K, and remove either A_iA i ​ or A_jA j ​ from AA. Is it possible to obtain an array consisting of only one element using several (possibly, zero) such operations? +Input Format The first line of input contains a single integer TT, denoting the number of test cases. The description of T test cases follows. The first line of each test case contains two space-separated integers NN and K. The second line contains N space-separated integers 1 ​ ,A 2 ​ ,…,A N ​ . + Output Format For each test case, print "YES" if it is possible to obtain an array consisting of only one element using the given operation, otherwise print "NO". You may print each character of the string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical).*/ + +#include +using namespace std; +#define ll long long +#define pb push_back + +int main() +{ + ll t; + cin >> t; + while (t--) + { + ll n, k; + cin >> n >> k; + vector v; + for (int i = 0; i < n; i++) + { + int e; + cin >> e; + v.pb(e); + } + if (n == 1) + { + cout << "Yes" << endl; + } + else + { + sort(v.begin(), v.end()); + ll maxi = *max_element(v.begin(), v.end()); + ll mini = *min_element(v.begin(), v.end()); + if (maxi + mini <= k) + { + cout << "Yes" << endl; + } + else + { + cout << "No" << endl; + } + } + } +} \ No newline at end of file diff --git a/Dynamic Programming/Pascal's Triangle.cpp b/Arrays/readme.md similarity index 100% rename from Dynamic Programming/Pascal's Triangle.cpp rename to Arrays/readme.md diff --git a/BFS in C++/BFS.cpp b/BFS in C++/BFS.cpp new file mode 100644 index 00000000..ea69e4e0 --- /dev/null +++ b/BFS in C++/BFS.cpp @@ -0,0 +1,63 @@ +#include +#include + +using namespace std; + +class Graph { + int numVertices; + list* adjLists; + bool* visited; + + public: + Graph(int vertices); + void addEdge(int src, int dest); + void BFS(int startVertex); +}; + +Graph::Graph(int vertices) { + numVertices = vertices; + adjLists = new list[vertices]; +} +void Graph::addEdge(int src, int dest) { + adjLists[src].push_back(dest); + adjLists[dest].push_back(src); +} + +void Graph::BFS(int startVertex) { + visited = new bool[numVertices]; + for (int i = 0; i < numVertices; i++) + visited[i] = false; + + list queue; + + visited[startVertex] = true; + queue.push_back(startVertex); + + list::iterator i; + + while (!queue.empty()) { + int currVertex = queue.front(); + cout << "Visited " << currVertex << " "; + queue.pop_front(); + + for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) { + int adjVertex = *i; + if (!visited[adjVertex]) { + visited[adjVertex] = true; + queue.push_back(adjVertex); + } + } + } +} + +int main() { + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + g.BFS(2); + return 0; +} \ No newline at end of file diff --git a/CPP/AVL Trees/AVL_Trees.cpp b/CPP/AVL Trees/AVL_Trees.cpp new file mode 100755 index 00000000..2959bc8d --- /dev/null +++ b/CPP/AVL Trees/AVL_Trees.cpp @@ -0,0 +1,113 @@ +#include +#define fastIO ios_base::sync_with_stdio(false); cout.tie(0) +#define endl '\n' +using namespace std; +typedef long long ll; +typedef unsigned long long ull; + +template +struct Node{ + struct Node* lchild; + struct Node* rchild; + int height; + T data; +}; + +Node *root = NULL; + +template +int nodeHeight(Node *p){ + int hl, hr; + hl = p && p -> lchild ? p -> lchild -> height : 0; + hr = p && p -> rchild ? p -> rchild -> height : 0; + + return max(hl + 1, hr + 1); +} + + +template +int balanceFactor(Node *p){ + int hl, hr; + hl = p && p -> lchild ? p -> lchild -> height : 0; + hr = p && p -> rchild ? p -> rchild -> height : 0; + + return hl - hr; +} + +template +Node* LLRotation(Node* p){ + Node *pl, *plr; + pl = p -> lchild; + plr = pl -> rchild; + + pl -> rchild = p; + p -> lchild = plr; + p -> height = nodeHeight(p); + pl -> height = nodeHeight(pl); + // plr's height remains same; + + if(root == p) + root = pl; + + return pl; +} + +template +Node* RRRotation(Node* p){ + return NULL; +} + +template +Node* LRRotation(Node* p){ + return NULL; +} + +template +Node* RLRotation(Node* p){ + return NULL; +} + + +template +Node* insert_bst_recursive(Node* p, T key){ + Node* t; + if(p == NULL){ + t = new Node; + t -> data = key; + t -> height = 1; + t -> lchild = NULL; + t -> rchild = NULL; + return t; + } + if(key < p -> data) + p -> lchild = insert_bst_recursive(p -> lchild, key); + else if(key > p -> data) + p -> rchild = insert_bst_recursive(p -> rchild, key); + + p -> height = nodeHeight(p); + + if(balanceFactor(p) == 2 && balanceFactor(p -> lchild) == 1) + return LLRotation(p); + else if(balanceFactor(p) == 2 && balanceFactor(p -> rchild) == -1) + return LRRotation(p); + else if(balanceFactor(p) == -2 && balanceFactor(p -> lchild) == -1) + return RRRotation(p); + else if(balanceFactor(p) == -2 && balanceFactor(p -> lchild) == 1) + return RLRotation(p); + + + return p; +} + +int main(){ + fastIO; + + root = insert_bst_recursive(root, 10); + // cout << root -> data; + insert_bst_recursive(root, 5); + insert_bst_recursive(root, 2); + + cout << root -> data; + + return 0; +} \ No newline at end of file diff --git a/BFS-ALGORITHM-USING-C++ b/CPP/BFS GRAPH ALGO/BFS-GRAPH-ALGO.cpp similarity index 100% rename from BFS-ALGORITHM-USING-C++ rename to CPP/BFS GRAPH ALGO/BFS-GRAPH-ALGO.cpp diff --git a/CPP/BFS_AND_DFS.cpp b/CPP/BFS_AND_DFS.cpp new file mode 100644 index 00000000..7c7e2fa9 --- /dev/null +++ b/CPP/BFS_AND_DFS.cpp @@ -0,0 +1,95 @@ +#include +using namespace std; + +int v; //No. of Vertices + +void Add_edge(vector adj[], int a, int b) +{ + adj[a].push_back(b); +} + +/************************************* ALGORITHM FOR BREADTH FIRST SEARCH ******************************************************/ + +// Take the empty queue and bool type array (visit) initialise with FALSE. +// Push the starting node in the queue and set the value TRUE for this node in visited array. +// Pop out the front node of the queue and print the node. +// Push the adjacent node of pop node in queue which are not visited. Set the value TRUE in visited array of adding node. +// Repeat step 3 and 4 until the queue becomes empty. + +void bfs(int n, vectoradj[]) +{ + vector visit(v,false); + queue q; + q.push(n); + visit[n]=true; + while(!q.empty()) + { + n=q.front(); + cout< adj[]) +{ + vector visit(v,false); + stack s; + s.push(n); + visit[n]=true; + while(!s.empty()) + { + n=s.top(); + cout<>v; + vector adj[v]; + vector visit(v,false); + Add_edge(adj,0,1); + Add_edge(adj,0,2); + Add_edge(adj,1,2); + Add_edge(adj,2,0); + Add_edge(adj,2,3); + Add_edge(adj,3,3); + + int temp; + cout<<"Choose the vertex from you want to start traversing : "; + cin>>temp; + cout<<"\nBFS traversal is"<<" "; + bfs(temp,adj); + cout<<"\nDFS traversal is"<<" "; + dfs(temp,adj); + + return 0; +} \ No newline at end of file diff --git a/CPP/BST/InsertionInABST.cpp b/CPP/BST/InsertionInABST.cpp new file mode 100644 index 00000000..efb61fd0 --- /dev/null +++ b/CPP/BST/InsertionInABST.cpp @@ -0,0 +1,90 @@ +#include +#include +using namespace std; + +struct node { + int data; + struct node *left, *right; +}; + +// Create a node +struct node *createnode(int item) { + struct node *temp = (struct node *)malloc(sizeof(struct node)); + temp->data = item; + temp->left = temp->right = NULL; + return temp; +} +void inorder(struct node *root) { + if (root != NULL) { + inorder(root->left); + cout << root->data << " "; + inorder(root->right); + } +} +int search(struct node *root, int key){ + struct node *prev = NULL; + while(root!=NULL){ + prev = root; + if(key==root->data){ + printf("Cannot insert %d, already in BST", key); + return 1; + } + else if(keydata){ + root = root->left; + } + else{ + root = root->right; + } + } + return 0; +} +struct node *insert(struct node *node, int key) { + if(search(node,key)==0){ + + if (node == NULL){ + return createnode(key); + } + if (key < node->data){ + node->left = insert(node->left, key); + } + else{ + node->right = insert(node->right, key); + } + } + + return node; +} + + +int main() { + struct node *root = NULL; + int ch; + int x; + cout<<"Press 0 to exit else enter 1: "; + cin>>ch; + while(ch!=0) + { + cout<<"\n"<<"1.Insertion"<<"\n"<<"2.View"<<"\n"; + cout<<"\n"<<"Enter choice :"; + cin>>ch; + switch (ch) + { + case 1: + cout<<"Enter the value you want to insert in binary search tree: "; + cin>>x; + root = insert(root, x); + break; + case 2: + cout << "Inorder traversal: "; + inorder(root); + break; + + default: + printf("\nINVALID CHOICE !!"); + break; + } + } +return 0; + + +} diff --git "a/CPP/Brian_Kernighan\342\200\231s_algorithm.cpp" "b/CPP/Brian_Kernighan\342\200\231s_algorithm.cpp" new file mode 100644 index 00000000..75efa15f --- /dev/null +++ "b/CPP/Brian_Kernighan\342\200\231s_algorithm.cpp" @@ -0,0 +1,38 @@ +//BY PRATIK AGRAWAL +//https://github.com/PratikAgrawal02/ + +//Given an integer, count its set bits. + +// We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. The idea is to only consider the set bits of an integer by turning off its rightmost set bit (after counting it), so the next iteration of the loop considers the next rightmost bit. +// The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This works as the expression n-1 flips all the bits after the rightmost set bit of n, including the rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. +// For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set. + +#include +#include +using namespace std; + +// Function to count the total number of set bits in `n` +int countSetBits(int n) +{ + // `count` stores the total bits set in `n` + int count = 0; + + while (n) + { + n = n & (n - 1); // clear the least significant bit set + count++; + } + + return count; +} + +int main() +{ + int n = -1; + + cout << n << " in binary is " << bitset<32>(n) << endl; + cout << "The total number of set bits in " << n << " is " + << countSetBits(n) << endl; + + return 0; +} diff --git a/CPP/DS C++/Binary & Selection sort search on given array list.cpp b/CPP/DS C++/Binary & Selection sort search on given array list.cpp new file mode 100644 index 00000000..eeea1dda --- /dev/null +++ b/CPP/DS C++/Binary & Selection sort search on given array list.cpp @@ -0,0 +1,92 @@ +class search +{ + private: + int a[5]; + int i,n,j,temp; + public: + void getdata(); + void bubble_search(); + void select_search(); + }; + + void search::getdata() + { + cout<<"\n Enter size of array:"; + cin>>n; + cout<<"\n Enter the array elements:"; + + for(i=0;i>a[i]; + } + } + void search::bubble_search() + { + for(i=0;ia[j+1]) + { + temp=a[j]; + a[j]=a[j+1]; + a[j+1]=temp; + } + } + } + +cout<<"\n Array after bubble sort:"; + for(i=0;ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + cout<<"Array after selection sort:\n"; + for(i=0;i>choice; + switch(choice) + { + + + case 'A': + cout<<"Program to implement Bubble sort on a array list:"; + s.getdata(); + s.bubble_search(); + break; + case 'B': + cout<<"Program to implement Selection sort on a array list:"; + s.getdata(); + s.select_search(); + break; + default: cout<<"Enter correct choice:"; + } + getch(); + } diff --git a/CPP/DS C++/Binary Search on Given Array List.cpp b/CPP/DS C++/Binary Search on Given Array List.cpp new file mode 100644 index 00000000..461203c9 --- /dev/null +++ b/CPP/DS C++/Binary Search on Given Array List.cpp @@ -0,0 +1,62 @@ +class search +{ + private: + inta[20],beg,end,mid,item,n; + public: + void getdata(); + void binary_search(); + }; + + void search::getdata() + { + cout<<"Enter the size of array:"; + cin>>n; + cout<<"Enter the array elements:"; + for(int i=1;i<=n;i++) + { + cin>>a[i]; + } + } + void search::binary_search() + { + + cout<<"Enter a number to be search:"; + cin>>item; + beg=0;end=n-1; + mid=(beg+end)/2; + + while((beg<=end)&&(a[mid]!=item)) + { + if(item>no; + cout<<"\n Enter the array elements:"; + for(int i=0;i>a[i]; + } + } + + void insertquick::insertionsort() + { + for(i=1;i<=no-1;i++) + { + for(j=i;j>=1;j--) + { + if(a[j]>no; + cout<<"\n Enter array of element to sort: "; + for(inti=0;i>k[i]; + } +} +void insertquick::sortit(int x[], intlb, intub) +{ + int j; + if(lb>= ub) + return; + show(); + partition(x,lb,ub,j); + sortit(x,lb,j-1); + sortit(x,j+1,ub); +} + +void insertquick::partition(int x[],intlb,intub,int&pj) +{ + int a, down, temp, up; + a = x[lb]; + up = ub; + down = lb; +while(down < up) +{ + while(x[down] <= a) + down++; + while(x[up] > a) + up--; + if(down < up) + { + temp = x[down]; + x[down] = x[up]; + x[up] = temp; + } + } + + x[lb] = x[up]; + x[up] = a; + pj = up; +} + +void insertquick::show() +{ + for(inti=0;i>choice; + + switch(choice) + { + case 'A': + cout<<"\n Program to implement Insertion sort:"; + iq.getdata(); + iq.insertionsort(); + iq.display(); + break; + + case 'B': + cout<<"\n Program to implement Quick sort:"; + iq.getarray(); + iq.sortit(iq.k,0,iq.no-1); + iq.show(); + break; + default: + + cout<<"Enter proper choice:"; + } + getch(); + } diff --git a/CPP/DS C++/Linear Sort Search on Given Array List.cpp b/CPP/DS C++/Linear Sort Search on Given Array List.cpp new file mode 100644 index 00000000..46e227f8 --- /dev/null +++ b/CPP/DS C++/Linear Sort Search on Given Array List.cpp @@ -0,0 +1,46 @@ +class search +{ + public: + inta[5],no,flag; + void getdata(); + void linear(); + }; + +void search::getdata() + { + cout<<"\n Enter the numbers:"; + for(int i=0;i<5;i++) + { + cin>>a[i]; + } + cout<<"Enter the no to be searched:"; + cin>>no; + } + void search::linear() + { + for(int i=0;i<5;i++) + { + if(no==a[i]) + { + flag=1; + break; + } + } + if(flag==1) + { + cout<<"\n The no is found at position:"<>a[i][j]; + } + } + } + + void matrix::calculate() + { + k=0; + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + if(a[i][j]!=0) + { + s[0][k]=i; + s[1][k]=j; + s[2][k]=a[i][j]; + k++; + } + } + } + } + + void matrix::display() + { + cout<<"The separate matrix is:\n"; + + for(i=0;i<3;i++) + { + for(j=0;j<3;j++) + { + cout<<"\t"< +using namespace std; + +void binary(int n){ + if(n==0){ + return; + } + binary(n/2); + cout<<(n%2); +} + +int main(){ + int n; + cin>>n; + binary(n); + return 0; +} diff --git a/Dynamic Programming/0-1_Knapsack.cpp b/CPP/Dynamic Programming/0-1_Knapsack.cpp similarity index 100% rename from Dynamic Programming/0-1_Knapsack.cpp rename to CPP/Dynamic Programming/0-1_Knapsack.cpp diff --git a/Dynamic Programming/5_Check_Palindrome.cpp b/CPP/Dynamic Programming/5_Check_Palindrome.cpp similarity index 94% rename from Dynamic Programming/5_Check_Palindrome.cpp rename to CPP/Dynamic Programming/5_Check_Palindrome.cpp index 0b82ec37..667a6c6b 100644 --- a/Dynamic Programming/5_Check_Palindrome.cpp +++ b/CPP/Dynamic Programming/5_Check_Palindrome.cpp @@ -1,35 +1,35 @@ -#include -using namespace std; - -// Method 1 -bool Palindrome(string s,int start,int end){ - if(start>=end){ - return true; - } - return (s[start]==s[end])&&(Palindrome(s,start+1,end-1)); -} - -// Method 2 -void pal(string s){ - int i=0,j=s.length()-1; - while(i<=j){ - if(s[i]!=s[j]){ - cout<<"String is not Palindrome"; - return ; - } - i++,j--; - } - cout<<"String is palindrome"; - return ; -} - -int main(){ - string s; - cin>>s; - cout< +using namespace std; + +// Method 1 +bool Palindrome(string s,int start,int end){ + if(start>=end){ + return true; + } + return (s[start]==s[end])&&(Palindrome(s,start+1,end-1)); +} + +// Method 2 +void pal(string s){ + int i=0,j=s.length()-1; + while(i<=j){ + if(s[i]!=s[j]){ + cout<<"String is not Palindrome"; + return ; + } + i++,j--; + } + cout<<"String is palindrome"; + return ; +} + +int main(){ + string s; + cin>>s; + cout< +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define type(x) __typeof((x).begin()) +#define foreach(i, x) for(type(x) i = (x).begin(); i != (x).end(); i++) +#define hash ___hash + +typedef long long ll; +typedef pair < int, int > ii; + +const int inf = 1e9 + 333; +const ll linf = 1e18 + 333; + +const int N = 2e6 + 5; + +int n; +char s[N]; +bool h[N]; +int go_odd[N], go_even[N], tmp[N << 1], rad[N << 1], ans[2][N]; + +void manacher() { + memset(tmp, 0, sizeof(tmp)); + memset(rad, 0, sizeof(rad)); + int m = n * 2 + 1; + for(int i = 0; i < m; i++) + tmp[i] = '#'; + for(int i = 0; i < n; i++) + tmp[i * 2 + 1] = s[i + 1]; + int i = 0, j = 0; + while(i < m) { + while(i - j >= 0 and i + j < m and tmp[i - j] == tmp[i + j]) + j++; + rad[i] = j; + int k = 1; + while(rad[i - k] < rad[i] - k) { + rad[i + k] = rad[i - k]; + k++; + } + i += k; + j = max(0, j - k); + } + for(int i = 1; i <= n; i++) + go_odd[i] = rad[(i - 1) * 2 + 1] / 2;//abcba --> go_odd[3] = 3 + for(int i = 1; i <= n; i++) + go_even[i - 1] = rad[(i - 1) * 2] / 2;//abccba --> go_even[3] = 3 +} + +void solveOdd(bool w) { + int oth = 0; + set < ii > go; + for(int i = 1; i <= (n + 1) / 2; i++) { + go.insert({go_odd[i], i}); + } + for(int i = 1; i <= n; i++) { + while(go.size()) { + int x = go.rbegin() -> first; + int id = go.rbegin() -> second; + if(id < i) { + go.erase(*go.rbegin()); + continue; + } + int mx = (id - i + 1) * 2 - 1; + if(x > mx) { + oth = max(oth, id); + go.erase(*go.rbegin()); + continue; + } + break; + } + if(go.size()) + ans[w][i] = max(ans[w][i], go.rbegin() -> first); + if(oth >= i) + ans[w][i] = max(ans[w][i], (oth - i + 1) * 2 - 1); + //printf("ans[%d] = %d oth = %d\n", i, ans[w][i]); + int add = (n + 1) / 2 + i; + go.insert({go_odd[add], add}); + } +} + +int get(int x, int y) { + y -= x - 1; + return min(y, n - y) * 2; +} + +void solveEven(bool w) { + int oth = 0; + set < ii > go; + for(int i = 1; i <= (n + 1) / 2; i++) { + go.insert({go_even[i], i}); + } + for(int i = 1; i <= n; i++) { + while(go.size()) { + int x = go.rbegin() -> first; + int id = go.rbegin() -> second; + if(id < i) { + go.erase(*go.rbegin()); + continue; + } + int mx = get(i, id); + if(x > mx) { + oth = max(oth, id); + go.erase(*go.rbegin()); + continue; + } + break; + } + if(go.size()) + ans[w][i] = max(ans[w][i], go.rbegin() -> first); + if(oth >= i) + ans[w][i] = max(ans[w][i], get(i, oth)); + //printf("ans[%d] = %d\n", i, ans[w][i]); + int add = (n + 1) / 2 + i; + go.insert({go_even[add], add}); + } +} + + +int main () { + + scanf("%d %s", &n, s + 1); + + for(int i = 1; i <= n; i++) + s[i + n] = s[i]; + + + n *= 2; + manacher(); + n /= 2; + + for(int i = 1; i <= n + n; i++) { + go_odd[i] *= 2; + go_odd[i] -= 1; + go_even[i] *= 2; + } + + solveOdd(0); + solveEven(0); + + + + reverse(s + 1, s + n * 2 + 1); + + n *= 2; + manacher(); + n /= 2; + + for(int i = 1; i <= n + n; i++) { + go_odd[i] *= 2; + go_odd[i] -= 1; + go_even[i] *= 2; + } + + solveOdd(1); + solveEven(1); + + printf("%d\n", max(ans[0][1], ans[1][1])); + + for(int i = 2; i <= n; i++) { + printf("%d\n", max(ans[0][i], ans[1][n + 2 - i])); + } + + return 0; + +} + + + + + + + diff --git a/Dynamic Programming/Coin_Change.cpp b/CPP/Dynamic Programming/Coin_Change.cpp similarity index 100% rename from Dynamic Programming/Coin_Change.cpp rename to CPP/Dynamic Programming/Coin_Change.cpp diff --git a/Dynamic Programming/Count_Number_Of_Square_Matrices.cpp b/CPP/Dynamic Programming/Count_Number_Of_Square_Matrices.cpp similarity index 100% rename from Dynamic Programming/Count_Number_Of_Square_Matrices.cpp rename to CPP/Dynamic Programming/Count_Number_Of_Square_Matrices.cpp diff --git a/Dynamic Programming/Edit Distance.cpp b/CPP/Dynamic Programming/Edit Distance.cpp similarity index 100% rename from Dynamic Programming/Edit Distance.cpp rename to CPP/Dynamic Programming/Edit Distance.cpp diff --git a/Dynamic Programming/Egg_Drop.cpp b/CPP/Dynamic Programming/Egg_Drop.cpp similarity index 100% rename from Dynamic Programming/Egg_Drop.cpp rename to CPP/Dynamic Programming/Egg_Drop.cpp diff --git a/Dynamic Programming/House Robber II.cpp b/CPP/Dynamic Programming/House Robber II.cpp similarity index 100% rename from Dynamic Programming/House Robber II.cpp rename to CPP/Dynamic Programming/House Robber II.cpp diff --git a/Dynamic Programming/House Robber.cpp b/CPP/Dynamic Programming/House Robber.cpp similarity index 100% rename from Dynamic Programming/House Robber.cpp rename to CPP/Dynamic Programming/House Robber.cpp diff --git a/Dynamic Programming/Knapsack - State Rotation b/CPP/Dynamic Programming/Knapsack - State Rotation similarity index 100% rename from Dynamic Programming/Knapsack - State Rotation rename to CPP/Dynamic Programming/Knapsack - State Rotation diff --git a/CPP/Dynamic Programming/Longest Increasing Subsequence.cpp b/CPP/Dynamic Programming/Longest Increasing Subsequence.cpp new file mode 100644 index 00000000..0322ffa4 --- /dev/null +++ b/CPP/Dynamic Programming/Longest Increasing Subsequence.cpp @@ -0,0 +1,17 @@ +//problem statement https://leetcode.com/problems/longest-increasing-subsequence/ + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector sub; + for (int x : nums) { + if (sub.empty() || sub[sub.size() - 1] < x) { + sub.push_back(x); + } else { + auto it = lower_bound(sub.begin(), sub.end(), x); // Find the index of the smallest number >= x + *it = x; // Replace that number with x + } + } + return sub.size(); + } +}; diff --git a/CPP/Dynamic Programming/Longest Increasing Subsequences.cpp b/CPP/Dynamic Programming/Longest Increasing Subsequences.cpp new file mode 100644 index 00000000..ebc6232d --- /dev/null +++ b/CPP/Dynamic Programming/Longest Increasing Subsequences.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int solvetab(vector &nums) + { + vector> dp(nums.size()+3,vector(nums.size()+3,0)); + for(int curr= nums.size()-1;curr>=0;curr--) + { + for(int prev=curr-1;prev>=-1;prev--) + { + + int inc=0; + //include + if(prev==-1||nums[curr]>nums[prev]) + { + inc= 1+dp[curr+1][curr+1]; + } + int excl=dp[curr+1][prev+1]; + dp[curr][prev+1]=max(inc,excl); + + } + } + return dp[0][0]; + } + int solve(vector &nums,int i,int prev,vector> &dp) + { + //base condition + if(i>=nums.size()) + { + return 0; + } + if(dp[i][prev+1]!=-1) + { + return dp[i][prev+1]; + } + //exclude + int excl=solve(nums,i+1,prev,dp); + int inc=0; + //include + if(prev==-1||nums[i]>nums[prev]) + { + inc= 1+solve(nums,i+1,i,dp); + } + + return dp[i][prev+1]=max(inc,excl); + + } + int lengthOfLIS(vector& nums) { + // vector> dp(nums.size()+3,vector(nums.size()+3,-1)); + // return solve(nums,0,-1,dp); + return solvetab(nums); + + } +}; \ No newline at end of file diff --git a/Dynamic Programming/Longest path - DP b/CPP/Dynamic Programming/Longest path - DP similarity index 100% rename from Dynamic Programming/Longest path - DP rename to CPP/Dynamic Programming/Longest path - DP diff --git a/Dynamic Programming/Longest-Palindromic-Subsequence.cpp b/CPP/Dynamic Programming/Longest-Palindromic-Subsequence.cpp similarity index 100% rename from Dynamic Programming/Longest-Palindromic-Subsequence.cpp rename to CPP/Dynamic Programming/Longest-Palindromic-Subsequence.cpp diff --git a/Dynamic Programming/Longest-Palindromic-Substring.cpp b/CPP/Dynamic Programming/Longest-Palindromic-Substring.cpp similarity index 100% rename from Dynamic Programming/Longest-Palindromic-Substring.cpp rename to CPP/Dynamic Programming/Longest-Palindromic-Substring.cpp diff --git a/Dynamic Programming/Longest_Common_Subsequence.cpp b/CPP/Dynamic Programming/Longest_Common_Subsequence.cpp similarity index 100% rename from Dynamic Programming/Longest_Common_Subsequence.cpp rename to CPP/Dynamic Programming/Longest_Common_Subsequence.cpp diff --git a/Dynamic Programming/Longest_Increasing_Subsequence.cpp b/CPP/Dynamic Programming/Longest_Increasing_Subsequence.cpp similarity index 100% rename from Dynamic Programming/Longest_Increasing_Subsequence.cpp rename to CPP/Dynamic Programming/Longest_Increasing_Subsequence.cpp diff --git a/Dynamic Programming/Matching - Bitmasking dp b/CPP/Dynamic Programming/Matching - Bitmasking dp similarity index 100% rename from Dynamic Programming/Matching - Bitmasking dp rename to CPP/Dynamic Programming/Matching - Bitmasking dp diff --git a/Dynamic Programming/Maximal Square.cpp b/CPP/Dynamic Programming/Maximal Square.cpp similarity index 100% rename from Dynamic Programming/Maximal Square.cpp rename to CPP/Dynamic Programming/Maximal Square.cpp diff --git a/CPP/Dynamic Programming/Minimum Time to Make Rope Colorful.cpp b/CPP/Dynamic Programming/Minimum Time to Make Rope Colorful.cpp new file mode 100644 index 00000000..542135d9 --- /dev/null +++ b/CPP/Dynamic Programming/Minimum Time to Make Rope Colorful.cpp @@ -0,0 +1,16 @@ +//problem statement https://leetcode.com/problems/minimum-time-to-make-rope-colorful/ +class Solution { +public: + int minCost(string c, vector& nT) { + int n=c.size(); + int sum=0; + int mx=nT[0]; + for(int i=1;i<=n;i++){ + if(c[i]==c[i-1]){ + sum+=min(nT[i-1],nT[i]); + nT[i]=max(nT[i],nT[i-1]); + } + } + return sum; + } +}; diff --git a/Dynamic Programming/Minimum_Digit_Delete.cpp b/CPP/Dynamic Programming/Minimum_Digit_Delete.cpp similarity index 100% rename from Dynamic Programming/Minimum_Digit_Delete.cpp rename to CPP/Dynamic Programming/Minimum_Digit_Delete.cpp diff --git a/Dynamic Programming/Number of Islands.cpp b/CPP/Dynamic Programming/Number of Islands.cpp similarity index 100% rename from Dynamic Programming/Number of Islands.cpp rename to CPP/Dynamic Programming/Number of Islands.cpp diff --git a/Dynamic Programming/PaintingHouses.cpp b/CPP/Dynamic Programming/PaintingHouses.cpp similarity index 100% rename from Dynamic Programming/PaintingHouses.cpp rename to CPP/Dynamic Programming/PaintingHouses.cpp diff --git a/Dynamic Programming/Palindrome Partitioning II.cpp b/CPP/Dynamic Programming/Palindrome Partitioning II.cpp similarity index 100% rename from Dynamic Programming/Palindrome Partitioning II.cpp rename to CPP/Dynamic Programming/Palindrome Partitioning II.cpp diff --git a/CPP/Dynamic Programming/Pascal's Triangle.cpp b/CPP/Dynamic Programming/Pascal's Triangle.cpp new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/CPP/Dynamic Programming/Pascal's Triangle.cpp @@ -0,0 +1 @@ + diff --git a/Dynamic Programming/Printing LCS b/CPP/Dynamic Programming/Printing LCS similarity index 100% rename from Dynamic Programming/Printing LCS rename to CPP/Dynamic Programming/Printing LCS diff --git a/Dynamic Programming/Rod-Cutting.cpp b/CPP/Dynamic Programming/Rod-Cutting.cpp similarity index 100% rename from Dynamic Programming/Rod-Cutting.cpp rename to CPP/Dynamic Programming/Rod-Cutting.cpp diff --git a/CPP/Dynamic Programming/Russian Doll.cpp b/CPP/Dynamic Programming/Russian Doll.cpp new file mode 100644 index 00000000..ebc6232d --- /dev/null +++ b/CPP/Dynamic Programming/Russian Doll.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int solvetab(vector &nums) + { + vector> dp(nums.size()+3,vector(nums.size()+3,0)); + for(int curr= nums.size()-1;curr>=0;curr--) + { + for(int prev=curr-1;prev>=-1;prev--) + { + + int inc=0; + //include + if(prev==-1||nums[curr]>nums[prev]) + { + inc= 1+dp[curr+1][curr+1]; + } + int excl=dp[curr+1][prev+1]; + dp[curr][prev+1]=max(inc,excl); + + } + } + return dp[0][0]; + } + int solve(vector &nums,int i,int prev,vector> &dp) + { + //base condition + if(i>=nums.size()) + { + return 0; + } + if(dp[i][prev+1]!=-1) + { + return dp[i][prev+1]; + } + //exclude + int excl=solve(nums,i+1,prev,dp); + int inc=0; + //include + if(prev==-1||nums[i]>nums[prev]) + { + inc= 1+solve(nums,i+1,i,dp); + } + + return dp[i][prev+1]=max(inc,excl); + + } + int lengthOfLIS(vector& nums) { + // vector> dp(nums.size()+3,vector(nums.size()+3,-1)); + // return solve(nums,0,-1,dp); + return solvetab(nums); + + } +}; \ No newline at end of file diff --git a/Dynamic Programming/Traping Rain Water.cpp b/CPP/Dynamic Programming/Traping Rain Water.cpp similarity index 100% rename from Dynamic Programming/Traping Rain Water.cpp rename to CPP/Dynamic Programming/Traping Rain Water.cpp diff --git a/CPP/Dynamic Programming/burstBalloons.cpp b/CPP/Dynamic Programming/burstBalloons.cpp new file mode 100644 index 00000000..60dc3dcd --- /dev/null +++ b/CPP/Dynamic Programming/burstBalloons.cpp @@ -0,0 +1,56 @@ +// this is hard level DP problem on lc +// https://leetcode.com/problems/burst-balloons/ + +// both memoization and tabulation approaches +class Solution +{ + // private: + // int solve(int i, int j, vector&nums,vector>&dp){ + // //base case + // if(i>j){ + // return 0; + // } + // if(dp[i][j]!=-1){ + // return dp[i][j]; + // } + // int ans = INT_MIN; + // for(int ind = i;ind<=j;ind++){ + // //think in terms as we are bursting last balloon + // int cost = nums[ind]*nums[i-1]*nums[j+1] + solve(i,ind-1,nums,dp) + solve(ind+1,j,nums,dp); + // ans = max(ans,cost); + // } + // return dp[i][j] = ans; + // } +public: + int maxCoins(vector &nums) + { + // mcm as we are given according to ordering and maxi so use dp + nums.push_back(1); + nums.insert(nums.begin(), 1); + //[1,3,1,5,8,1] + int n = nums.size(); + // vector>dp(n,vector(n,-1)); + // return solve(1,n-2,nums,dp); + vector> dp(n + 2, vector(n + 2, 0)); + + // think in terms of reverse of memo + for (int i = n - 2; i >= 1; i--) + { + for (int j = 1; j <= n - 2; j++) + { + if (i > j) + { + continue; + } + int ans = INT_MIN; + for (int ind = i; ind <= j; ind++) + { + int cost = nums[ind] * nums[i - 1] * nums[j + 1] + dp[i][ind - 1] + dp[ind + 1][j]; + ans = max(ans, cost); + } + dp[i][j] = ans; + } + } + return dp[1][n - 2]; + } +}; \ No newline at end of file diff --git a/Dynamic Programming/climbingStairs.cpp b/CPP/Dynamic Programming/climbingStairs.cpp similarity index 100% rename from Dynamic Programming/climbingStairs.cpp rename to CPP/Dynamic Programming/climbingStairs.cpp diff --git a/Dynamic Programming/fibonacci Num.cpp b/CPP/Dynamic Programming/fibonacci Num.cpp similarity index 100% rename from Dynamic Programming/fibonacci Num.cpp rename to CPP/Dynamic Programming/fibonacci Num.cpp diff --git a/Dynamic Programming/minimumPointsToReachDestination.cpp b/CPP/Dynamic Programming/minimumPointsToReachDestination.cpp similarity index 100% rename from Dynamic Programming/minimumPointsToReachDestination.cpp rename to CPP/Dynamic Programming/minimumPointsToReachDestination.cpp diff --git a/CPP/Dynamic Programming/number_of_dice_rolls_with_target_sum.cpp b/CPP/Dynamic Programming/number_of_dice_rolls_with_target_sum.cpp new file mode 100644 index 00000000..14ee230f --- /dev/null +++ b/CPP/Dynamic Programming/number_of_dice_rolls_with_target_sum.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; +int dp[31][1001] = {0}; // Table of n * target sum ; This is used to save the results in bottom up approach +int numRollsToTarget(int n, int k, int target) { + dp[0][0] = 1; // When you have 0 dices and target sum = 0; the number of ways to get the answer is 1 + + for(int i = 1;i<=target;i++){ // when you have 0 dices; [1,targetsum] numbers there are zero ways to get the answer + dp[0][i] = 0; + } + for(int i=1;i<=n;i++){ // when you have 0 target; n =[1,n] dices there are zero ways to get the answer + dp[i][0] = 0; + } + + /* + The below loop has Time complexity = O(n*targetSum*k) + It finds the answer for smaller target sums and build up to find the solution of the targetSum + */ + for(int i=1;i<=n;i++){ + for(int j=1;j<=target;j++){ + long long res = 0; + for(int x=1;x<=k;x++){ + if(j>=x){ + res = (res % 1000000007) + (dp[i-1][j-x] % 1000000007); + // res = res % 1000000007; + } + } + dp[i][j] = res ; + } + } + return dp[n][target] % 1000000007; +} + +int main(){ + + int n = 7,k=6,target = 30; + cout< +#include +#include +using namespace std; + +void wordBreak(vector const &dict, string word, string out) +{ + if (word.size() == 0) + { + cout << out << endl; + return; + } + + for (int i = 1; i <= word.size(); i++) + { + + string prefix = word.substr(0, i); + + + if (find(dict.begin(), dict.end(), prefix) != dict.end()) { + wordBreak(dict, word.substr(i), out + " " + prefix); + } + } +} + +int main() +{ + + vector dict = { "this", "th", "is", "famous", "Word", "break", + "b", "r", "e", "a", "k", "br", "bre", "brea", "ak", "problem" }; + + string word = "Wordbreakproblem"; + + wordBreak(dict, word, ""); + + return 0; +} diff --git a/CPP/Edit distance leetcode b/CPP/Edit distance leetcode new file mode 100644 index 00000000..e7967d56 --- /dev/null +++ b/CPP/Edit distance leetcode @@ -0,0 +1,22 @@ +//link: https://leetcode.com/problems/edit-distance/description/ + +int solve(int i, int j, string s1, string s2,vector>& dp){ + //base case + if(j<0) return i+1; + if(i<0) return j+1; + + if(dp[i][j]!=-1) return dp[i][j]; + if(s1[i] == s2[j]){ + return dp[i][j] = solve(i-1,j-1,s1,s2,dp); + } + int del = solve(i-1,j,s1,s2,dp); + int rp = solve(i-1,j-1,s1,s2,dp); + int ins = solve(i,j-1,s1,s2,dp); + return dp[i][j] =1+ min({del,rp,ins}); + } + int minDistance(string word1, string word2) { + int n = word1.length(); + int m = word2.length(); + vector> dp(n+1,vector(m+1,-1)); + return solve(n-1,m-1,word1,word2,dp); + } diff --git a/CPP/Geek and Strings.cpp b/CPP/Geek and Strings.cpp new file mode 100644 index 00000000..582da629 --- /dev/null +++ b/CPP/Geek and Strings.cpp @@ -0,0 +1,24 @@ +class Solution{ +public: + vector prefixCount(int N, int Q, string li[], string query[]) + { + unordered_map mp; + + for(int i=0;i ans(Q, 0); + for(int i=0;i +using namespace std; + +// DSU data structure +// path compression + rank by union + +class DSU { + int* parent; + int* rank; + +public: + DSU(int n) + { + parent = new int[n]; + rank = new int[n]; + + for (int i = 0; i < n; i++) { + parent[i] = -1; + rank[i] = 1; + } + } + + // Find function + int find(int i) + { + if (parent[i] == -1) + return i; + + return parent[i] = find(parent[i]); + } + + // Union function + void unite(int x, int y) + { + int s1 = find(x); + int s2 = find(y); + + if (s1 != s2) { + if (rank[s1] < rank[s2]) { + parent[s1] = s2; + rank[s2] += rank[s1]; + } + else { + parent[s2] = s1; + rank[s1] += rank[s2]; + } + } + } +}; + +class Graph { + vector > edgelist; + int V; + +public: + Graph(int V) { this->V = V; } + + void addEdge(int x, int y, int w) + { + edgelist.push_back({ w, x, y }); + } + + void kruskals_mst() + { + // 1. Sort all edges + sort(edgelist.begin(), edgelist.end()); + + // Initialize the DSU + DSU s(V); + int ans = 0; + cout << "Following are the edges in the " + "constructed MST" + << endl; + for (auto edge : edgelist) { + int w = edge[0]; + int x = edge[1]; + int y = edge[2]; + + // Take this edge in MST if it does + // not forms a cycle + if (s.find(x) != s.find(y)) { + s.unite(x, y); + ans += w; + cout << x << " -- " << y << " == " << w + << endl; + } + } + + cout << "Minimum Cost Spanning Tree: " << ans; + } +}; + +// Driver's code +int main() +{ + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + Graph g(4); + g.addEdge(0, 1, 10); + g.addEdge(1, 3, 15); + g.addEdge(2, 3, 4); + g.addEdge(2, 0, 6); + g.addEdge(0, 3, 5); + + // Function call + g.kruskals_mst(); + return 0; +} diff --git a/CPP/LINKED LIST/CIRCULAR LINKED LIST/test4.bin b/CPP/LINKED LIST/CIRCULAR LINKED LIST/test4.bin deleted file mode 100644 index 3c1f1237..00000000 Binary files a/CPP/LINKED LIST/CIRCULAR LINKED LIST/test4.bin and /dev/null differ diff --git a/CPP/LINKED LIST/DOUBLY LINKED LIST/doublylinkedlistpractice.bin b/CPP/LINKED LIST/DOUBLY LINKED LIST/doublylinkedlistpractice.bin deleted file mode 100644 index 603bf451..00000000 Binary files a/CPP/LINKED LIST/DOUBLY LINKED LIST/doublylinkedlistpractice.bin and /dev/null differ diff --git a/CPP/LINKED LIST/Linked_list.cpp b/CPP/LINKED LIST/Linked_list.cpp new file mode 100644 index 00000000..d6b467e7 --- /dev/null +++ b/CPP/LINKED LIST/Linked_list.cpp @@ -0,0 +1,144 @@ +#include +using namespace std; + +struct Node +{ + int data; + struct Node *next; + +} *first = NULL; +// initialised first as null + +void createList(int arr[], int n) +{ + struct Node *t; + struct Node *last; + + // setup a new node + first = new struct Node; + first->data = arr[0]; + first->next = NULL; + + // last is first as 1 element only + last = first; + + for (int i = 1; i < n; i++) + { + // setup a new node + t = new struct Node; + t->data = arr[i]; + t->next = NULL; + + // make current last point to new node + last->next = t; + + // update last + last = t; + } +}; + +void printList(struct Node *p) +{ + // while address of next block is not null + while (p != NULL) + { + cout << (p->data) << " "; + p = p->next; + } + + cout << endl; +} + +// time : O(n) +// space : O(1) +int countNodes(struct Node *p) +{ + // while address of next block is not null + int count = 0; + + while (p != NULL) + { + count++; + p = p->next; + } + + return count; +} + +void insert(struct Node *p, int index, int data) +{ + // new node in heap + struct Node *newNode; + newNode = new struct Node; + newNode->data = data; + + if (index == 0) + { + // linking + newNode->next = first; + first = newNode; + } + + else + { + for (int i = 0; i < index - 1; i++) + { + p = p->next; + } + + newNode->next = p->next; + p->next = newNode; + } + +} + +void deleteList(struct Node *p , int index) +{ + struct Node *prev; + + if(index == 0){ + + // pointing to 1st node + prev = first; + + // pointing to 2nd node + first = first->next; + + delete prev; + } + + else{ + + for (int i = 0; i < index-1; i++) + { + prev = p; + p = p->next; + } + + prev->next = p->next; + delete p; + + } +} + +struct Node *searchList(struct Node *p, int target) +{ + while (p != 0) + { + if (p->data == target) + { + // returns address of that node which have data == target + return p; + } + p = p->next; + } + + return NULL; +} + + + +int main() +{ + +} \ No newline at end of file diff --git a/CPP/LINKED LIST/SINGLY LINKED LIST/Insertion of node at tail of LinkedList.cpp b/CPP/LINKED LIST/SINGLY LINKED LIST/Insertion of node at tail of LinkedList.cpp new file mode 100644 index 00000000..f45b8544 --- /dev/null +++ b/CPP/LINKED LIST/SINGLY LINKED LIST/Insertion of node at tail of LinkedList.cpp @@ -0,0 +1,65 @@ + +#include + +using namespace std; + + + +struct Node +{ + int data; + struct Node *next; +}; + +struct Node *head; + +void +Insert (int data) +{ + struct Node *temp = (struct Node *) malloc (sizeof (struct Node *)); + + + temp->data = data; + temp->next = NULL; + + if (head == NULL) + { + head = temp; + return; + } + + struct Node *temp2 = head; + while (temp2->next != NULL) + { + temp2 = temp2->next; + } + temp2->next = temp; +} + +void +Print () +{ + struct Node *temp = head; + while (temp != NULL) + { + printf (" %d", temp->data); + temp = temp->next; + } + printf ("\n"); + +} + + +int +main () +{ + head = NULL; + Insert (4); + Insert (6); + Insert (8); + Insert (2); + Print (); + + return 0; +} + diff --git a/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/Sliding Window Problem/subarraysum.bin b/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/Sliding Window Problem/subarraysum.bin deleted file mode 100644 index 5082267c..00000000 Binary files a/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/Sliding Window Problem/subarraysum.bin and /dev/null differ diff --git a/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/Sliding Window Problem/subarraysum.exe b/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/Sliding Window Problem/subarraysum.exe deleted file mode 100644 index 828a476d..00000000 Binary files a/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/Sliding Window Problem/subarraysum.exe and /dev/null differ diff --git a/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/powerfunc.bin b/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/powerfunc.bin deleted file mode 100644 index b36443f4..00000000 Binary files a/CPP/LINKED LIST/SINGLY LINKED LIST/Maths For DSA/powerfunc.bin and /dev/null differ diff --git a/CPP/LINKED LIST/SOME LEET CODE QUESTIONS/leetcode_206.cpp b/CPP/LINKED LIST/SOME LEET CODE QUESTIONS/leetcode_206.cpp new file mode 100644 index 00000000..8942979f --- /dev/null +++ b/CPP/LINKED LIST/SOME LEET CODE QUESTIONS/leetcode_206.cpp @@ -0,0 +1,25 @@ +/** + * 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* reverseList(ListNode* head) { + ListNode* dummy=NULL; + ListNode* next; + while(head != NULL) { + next=head->next; + head->next=dummy; + dummy=head; + head=next; + } + + return dummy; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1-two-sum/1-two-sum.cpp b/CPP/Leetcode/1-two-sum/1-two-sum.cpp new file mode 100644 index 00000000..e514e0c3 --- /dev/null +++ b/CPP/Leetcode/1-two-sum/1-two-sum.cpp @@ -0,0 +1,36 @@ +class Solution +{ +public: + vector twoSum(vector& nums, int target) + { + vector v; + int z=0; + for(int i=0;i1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

+ +

You may assume that each input would have exactly one solution, and you may not use the same element twice.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [2,7,11,15], target = 9
+Output: [0,1]
+Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
+
+ +

Example 2:

+ +
Input: nums = [3,2,4], target = 6
+Output: [1,2]
+
+ +

Example 3:

+ +
Input: nums = [3,3], target = 6
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
  • Only one valid answer exists.
  • +
+ +

 

+Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?
\ No newline at end of file diff --git a/CPP/Leetcode/1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.cpp b/CPP/Leetcode/1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.cpp new file mode 100644 index 00000000..59153316 --- /dev/null +++ b/CPP/Leetcode/1004-max-consecutive-ones-iii/1004-max-consecutive-ones-iii.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + int i=0,j=0; + while(i1004. Max Consecutive Ones III

Medium


Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
+Output: 6
+Explanation: [1,1,1,0,0,1,1,1,1,1,1]
+Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
+Output: 10
+Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
+Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
  • 0 <= k <= nums.length
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1021-remove-outermost-parentheses/1021-remove-outermost-parentheses.cpp b/CPP/Leetcode/1021-remove-outermost-parentheses/1021-remove-outermost-parentheses.cpp new file mode 100644 index 00000000..4a9431f8 --- /dev/null +++ b/CPP/Leetcode/1021-remove-outermost-parentheses/1021-remove-outermost-parentheses.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + string removeOuterParentheses(string s) { + int cnt=0; + string k=""; + for(int i=0;i bool: + if root is None: return False + + if root.left is None and root.right is None and root.val == targetSum: return True + + return (self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum - root.val) ) \ No newline at end of file diff --git a/CPP/Leetcode/112-path-sum/README.md b/CPP/Leetcode/112-path-sum/README.md new file mode 100644 index 00000000..848e1189 --- /dev/null +++ b/CPP/Leetcode/112-path-sum/README.md @@ -0,0 +1,38 @@ +

112. Path Sum

Easy


Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
+Output: true
+Explanation: The root-to-leaf path with the target sum is shown.
+
+ +

Example 2:

+ +
Input: root = [1,2,3], targetSum = 5
+Output: false
+Explanation: There two root-to-leaf paths in the tree:
+(1 --> 2): The sum is 3.
+(1 --> 3): The sum is 4.
+There is no root-to-leaf path with sum = 5.
+
+ +

Example 3:

+ +
Input: root = [], targetSum = 0
+Output: false
+Explanation: Since the tree is empty, there are no root-to-leaf paths.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/118-pascals-triangle/118-pascals-triangle.cpp b/CPP/Leetcode/118-pascals-triangle/118-pascals-triangle.cpp new file mode 100644 index 00000000..00a1337b --- /dev/null +++ b/CPP/Leetcode/118-pascals-triangle/118-pascals-triangle.cpp @@ -0,0 +1,26 @@ +class Solution { + private: + vector> printPascal(int n) + { + vector b; + for (int line = 1; line <= n; line++) + { + int C = 1; + for (int i = 1; i <= line; i++) + { + b.push_back(C); + C = C * (line - i) / i; + } + v.push_back(b); + b.clear(); + + } + return v; +} +public: + vector> v; + vector> generate(int numRows) + { + return printPascal(numRows); + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/118-pascals-triangle/NOTES.md b/CPP/Leetcode/118-pascals-triangle/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/118-pascals-triangle/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/118-pascals-triangle/README.md b/CPP/Leetcode/118-pascals-triangle/README.md new file mode 100644 index 00000000..9750c83b --- /dev/null +++ b/CPP/Leetcode/118-pascals-triangle/README.md @@ -0,0 +1,19 @@ +

118. Pascal's Triangle

Easy


Given an integer numRows, return the first numRows of Pascal's triangle.

+ +

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

+ +

 

+

Example 1:

+
Input: numRows = 5
+Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
+

Example 2:

+
Input: numRows = 1
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= numRows <= 30
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp b/CPP/Leetcode/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp new file mode 100644 index 00000000..c5a266ac --- /dev/null +++ b/CPP/Leetcode/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int low=INT_MAX; + int profit=0; + for(int i=0;iprofit) + { + profit=cnt; + } + + } + return profit; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/121-best-time-to-buy-and-sell-stock/README.md b/CPP/Leetcode/121-best-time-to-buy-and-sell-stock/README.md new file mode 100644 index 00000000..9350a49a --- /dev/null +++ b/CPP/Leetcode/121-best-time-to-buy-and-sell-stock/README.md @@ -0,0 +1,30 @@ +

121. Best Time to Buy and Sell Stock

Easy


You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

+ +

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

+ +

 

+

Example 1:

+ +
Input: prices = [7,1,5,3,6,4]
+Output: 5
+Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
+Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
+
+ +

Example 2:

+ +
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transactions are done and the max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 104
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1227-airplane-seat-assignment-probability/1227-airplane-seat-assignment-probability.cpp b/CPP/Leetcode/1227-airplane-seat-assignment-probability/1227-airplane-seat-assignment-probability.cpp new file mode 100644 index 00000000..3e80b831 --- /dev/null +++ b/CPP/Leetcode/1227-airplane-seat-assignment-probability/1227-airplane-seat-assignment-probability.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + double nthPersonGetsNthSeat(int n) { + if(n==1) return 1.0; + else return 0.5; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1227-airplane-seat-assignment-probability/NOTES.md b/CPP/Leetcode/1227-airplane-seat-assignment-probability/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1227-airplane-seat-assignment-probability/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1227-airplane-seat-assignment-probability/README.md b/CPP/Leetcode/1227-airplane-seat-assignment-probability/README.md new file mode 100644 index 00000000..3ad94fad --- /dev/null +++ b/CPP/Leetcode/1227-airplane-seat-assignment-probability/README.md @@ -0,0 +1,30 @@ +

1227. Airplane Seat Assignment Probability

Medium


n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:

+ +
    +
  • Take their own seat if it is still available, and
  • +
  • Pick other seats randomly when they find their seat occupied
  • +
+ +

Return the probability that the nth person gets his own seat.

+ +

 

+

Example 1:

+ +
Input: n = 1
+Output: 1.00000
+Explanation: The first person can only get the first seat.
+ +

Example 2:

+ +
Input: n = 2
+Output: 0.50000
+Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/125-valid-palindrome/125-valid-palindrome.cpp b/CPP/Leetcode/125-valid-palindrome/125-valid-palindrome.cpp new file mode 100644 index 00000000..10d0ac26 --- /dev/null +++ b/CPP/Leetcode/125-valid-palindrome/125-valid-palindrome.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + bool isPalindrome(string s) { + int n=s.length(); + string k=""; + transform(s.begin(), s.end(), s.begin(), ::tolower); + for(int i=0;i='a' && s[i]<='z') || (s[i]>='0' && s[i]<='9')) k+=s[i]; + } + + n=k.length(); + int l=0; + int r=n-1; + while(l125. Valid Palindrome

Easy


A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

+ +

Given a string s, return true if it is a palindrome, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: s = "A man, a plan, a canal: Panama"
+Output: true
+Explanation: "amanaplanacanalpanama" is a palindrome.
+
+ +

Example 2:

+ +
Input: s = "race a car"
+Output: false
+Explanation: "raceacar" is not a palindrome.
+
+ +

Example 3:

+ +
Input: s = " "
+Output: true
+Explanation: s is an empty string "" after removing non-alphanumeric characters.
+Since an empty string reads the same forward and backward, it is a palindrome.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2 * 105
  • +
  • s consists only of printable ASCII characters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1290-convert-binary-number-in-a-linked-list-to-integer/1290-convert-binary-number-in-a-linked-list-to-integer.cpp b/CPP/Leetcode/1290-convert-binary-number-in-a-linked-list-to-integer/1290-convert-binary-number-in-a-linked-list-to-integer.cpp new file mode 100644 index 00000000..11a4cd5b --- /dev/null +++ b/CPP/Leetcode/1290-convert-binary-number-in-a-linked-list-to-integer/1290-convert-binary-number-in-a-linked-list-to-integer.cpp @@ -0,0 +1,31 @@ +/** + * 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: + int getDecimalValue(ListNode* head) { + ListNode *curr=head; + int n=0; + while(head->next!=NULL) + { + n++; + head=head->next; + } + int res=0; + head=curr; + while(head!=NULL) + { + res=res+((head->val)<next; + } + return res; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1290-convert-binary-number-in-a-linked-list-to-integer/README.md b/CPP/Leetcode/1290-convert-binary-number-in-a-linked-list-to-integer/README.md new file mode 100644 index 00000000..f6278f64 --- /dev/null +++ b/CPP/Leetcode/1290-convert-binary-number-in-a-linked-list-to-integer/README.md @@ -0,0 +1,29 @@ +

1290. Convert Binary Number in a Linked List to Integer

Easy


Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

+ +

Return the decimal value of the number in the linked list.

+ +

The most significant bit is at the head of the linked list.

+ +

 

+

Example 1:

+ +
Input: head = [1,0,1]
+Output: 5
+Explanation: (101) in base 2 = (5) in base 10
+
+ +

Example 2:

+ +
Input: head = [0]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The Linked List is not empty.
  • +
  • Number of nodes will not exceed 30.
  • +
  • Each node's value is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/13-roman-to-integer/13-roman-to-integer.cpp b/CPP/Leetcode/13-roman-to-integer/13-roman-to-integer.cpp new file mode 100644 index 00000000..b888008a --- /dev/null +++ b/CPP/Leetcode/13-roman-to-integer/13-roman-to-integer.cpp @@ -0,0 +1,23 @@ +class Solution { +public: +int romanToInt(string s) { + map mp{ + {'I',1}, + {'V',5}, + {'X',10}, + {'L',50}, + {'C',100}, + {'D',500}, + {'M',1000}, + }; + int ans =0; + for(int i=0;i13. Roman to Integer

Easy


Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

+ +
Symbol       Value
+I             1
+V             5
+X             10
+L             50
+C             100
+D             500
+M             1000
+ +

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.

+ +

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:

+ +
    +
  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • +
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • +
  • C can be placed before D (500) and M (1000) to make 400 and 900.
  • +
+ +

Given a roman numeral, convert it to an integer.

+ +

 

+

Example 1:

+ +
Input: s = "III"
+Output: 3
+Explanation: III = 3.
+
+ +

Example 2:

+ +
Input: s = "LVIII"
+Output: 58
+Explanation: L = 50, V= 5, III = 3.
+
+ +

Example 3:

+ +
Input: s = "MCMXCIV"
+Output: 1994
+Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 15
  • +
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • +
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp b/CPP/Leetcode/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp new file mode 100644 index 00000000..12c4d3da --- /dev/null +++ b/CPP/Leetcode/1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + int n = mat.size(); + set> s; + for(int i=0;i v; + for(auto x:s) + { + if(k==0) break; + v.push_back(x.second); + k--; + } + return v; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1337-the-k-weakest-rows-in-a-matrix/README.md b/CPP/Leetcode/1337-the-k-weakest-rows-in-a-matrix/README.md new file mode 100644 index 00000000..38d0c1e3 --- /dev/null +++ b/CPP/Leetcode/1337-the-k-weakest-rows-in-a-matrix/README.md @@ -0,0 +1,61 @@ +

1337. The K Weakest Rows in a Matrix

Easy


You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.

+ +

A row i is weaker than a row j if one of the following is true:

+ +
    +
  • The number of soldiers in row i is less than the number of soldiers in row j.
  • +
  • Both rows have the same number of soldiers and i < j.
  • +
+ +

Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

+ +

 

+

Example 1:

+ +
Input: mat = 
+[[1,1,0,0,0],
+ [1,1,1,1,0],
+ [1,0,0,0,0],
+ [1,1,0,0,0],
+ [1,1,1,1,1]], 
+k = 3
+Output: [2,0,3]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 2 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 2 
+- Row 4: 5 
+The rows ordered from weakest to strongest are [2,0,3,1,4].
+
+ +

Example 2:

+ +
Input: mat = 
+[[1,0,0,0],
+ [1,1,1,1],
+ [1,0,0,0],
+ [1,0,0,0]], 
+k = 2
+Output: [0,2]
+Explanation: 
+The number of soldiers in each row is: 
+- Row 0: 1 
+- Row 1: 4 
+- Row 2: 1 
+- Row 3: 1 
+The rows ordered from weakest to strongest are [0,2,3,1].
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 2 <= n, m <= 100
  • +
  • 1 <= k <= m
  • +
  • matrix[i][j] is either 0 or 1.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/1342-number-of-steps-to-reduce-a-number-to-zero.cpp b/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/1342-number-of-steps-to-reduce-a-number-to-zero.cpp new file mode 100644 index 00000000..a5438b21 --- /dev/null +++ b/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/1342-number-of-steps-to-reduce-a-number-to-zero.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int numberOfSteps(int num) { + int cnt=0; + while(num!=0) + { + if(num%2==0) num=num/2; + else num--; + cnt++; + } + return cnt; + + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/NOTES.md b/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/README.md b/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/README.md new file mode 100644 index 00000000..e26168cf --- /dev/null +++ b/CPP/Leetcode/1342-number-of-steps-to-reduce-a-number-to-zero/README.md @@ -0,0 +1,42 @@ +

1342. Number of Steps to Reduce a Number to Zero

Easy


Given an integer num, return the number of steps to reduce it to zero.

+ +

In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

+ +

 

+

Example 1:

+ +
Input: num = 14
+Output: 6
+Explanation: 
+Step 1) 14 is even; divide by 2 and obtain 7. 
+Step 2) 7 is odd; subtract 1 and obtain 6.
+Step 3) 6 is even; divide by 2 and obtain 3. 
+Step 4) 3 is odd; subtract 1 and obtain 2. 
+Step 5) 2 is even; divide by 2 and obtain 1. 
+Step 6) 1 is odd; subtract 1 and obtain 0.
+
+ +

Example 2:

+ +
Input: num = 8
+Output: 4
+Explanation: 
+Step 1) 8 is even; divide by 2 and obtain 4. 
+Step 2) 4 is even; divide by 2 and obtain 2. 
+Step 3) 2 is even; divide by 2 and obtain 1. 
+Step 4) 1 is odd; subtract 1 and obtain 0.
+
+ +

Example 3:

+ +
Input: num = 123
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 106
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1346-check-if-n-and-its-double-exist/1346-check-if-n-and-its-double-exist.cpp b/CPP/Leetcode/1346-check-if-n-and-its-double-exist/1346-check-if-n-and-its-double-exist.cpp new file mode 100644 index 00000000..53860946 --- /dev/null +++ b/CPP/Leetcode/1346-check-if-n-and-its-double-exist/1346-check-if-n-and-its-double-exist.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool checkIfExist(vector& arr) { + unordered_map mp; + for(int i=0;i0 && mp[arr[i]*2]>0 && arr[i]!=0) return true; + if(mp[arr[i]]>=2 && arr[i]==0) return true; + } + return false; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1346-check-if-n-and-its-double-exist/NOTES.md b/CPP/Leetcode/1346-check-if-n-and-its-double-exist/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1346-check-if-n-and-its-double-exist/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/136-single-number/136-single-number.cpp b/CPP/Leetcode/136-single-number/136-single-number.cpp new file mode 100644 index 00000000..1847afe3 --- /dev/null +++ b/CPP/Leetcode/136-single-number/136-single-number.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int singleNumber(vector& nums) { + int k=nums[0]; + for(int i=1;i136. Single Number

Easy


Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

+ +

You must implement a solution with a linear runtime complexity and use only constant extra space.

+ +

 

+

Example 1:

+
Input: nums = [2,2,1]
+Output: 1
+

Example 2:

+
Input: nums = [4,1,2,1,2]
+Output: 4
+

Example 3:

+
Input: nums = [1]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -3 * 104 <= nums[i] <= 3 * 104
  • +
  • Each element in the array appears twice except for one element which appears only once.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/14-longest-common-prefix/14-longest-common-prefix.cpp b/CPP/Leetcode/14-longest-common-prefix/14-longest-common-prefix.cpp new file mode 100644 index 00000000..45850faa --- /dev/null +++ b/CPP/Leetcode/14-longest-common-prefix/14-longest-common-prefix.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string longestCommonPrefix(vector& nums) { + + string res=""; + for(int i=0;i14. Longest Common Prefix

Easy


Write a function to find the longest common prefix string amongst an array of strings.

+ +

If there is no common prefix, return an empty string "".

+ +

 

+

Example 1:

+ +
Input: strs = ["flower","flow","flight"]
+Output: "fl"
+
+ +

Example 2:

+ +
Input: strs = ["dog","racecar","car"]
+Output: ""
+Explanation: There is no common prefix among the input strings.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 200
  • +
  • 0 <= strs[i].length <= 200
  • +
  • strs[i] consists of only lower-case English letters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1433-check-if-a-string-can-break-another-string/1433-check-if-a-string-can-break-another-string.cpp b/CPP/Leetcode/1433-check-if-a-string-can-break-another-string/1433-check-if-a-string-can-break-another-string.cpp new file mode 100644 index 00000000..bb3ffa31 --- /dev/null +++ b/CPP/Leetcode/1433-check-if-a-string-can-break-another-string/1433-check-if-a-string-can-break-another-string.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool checkIfCanBreak(string s1, string s2) { + sort(s1.begin(),s1.end()); + sort(s2.begin(),s2.end()); + int f=0; + for(int i=0;i=s2[i]) continue; + else + { + f=1; + } + } + int g=0; + for(int i=0;i=s1[i]) continue; + else + { + g=1; + } + } + if(f==0 || g==0) return true; + else return false; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1433-check-if-a-string-can-break-another-string/NOTES.md b/CPP/Leetcode/1433-check-if-a-string-can-break-another-string/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1433-check-if-a-string-can-break-another-string/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.cpp b/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.cpp new file mode 100644 index 00000000..915929f7 --- /dev/null +++ b/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.cpp @@ -0,0 +1,34 @@ +/** + * 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: + int cnt=0; + void search(TreeNode *root,int max) + { + if(!root) return; + if(root->val >=max) + { + cnt++; + max=root->val; + } + search(root->left,max); + search(root->right,max); + } + + int goodNodes(TreeNode* root) { + search(root,root->val); + return cnt; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/NOTES.md b/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/README.md b/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/README.md new file mode 100644 index 00000000..e059058c --- /dev/null +++ b/CPP/Leetcode/1448-count-good-nodes-in-binary-tree/README.md @@ -0,0 +1,38 @@ +

1448. Count Good Nodes in Binary Tree

Medium


Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

+ +

Return the number of good nodes in the binary tree.

+ +

 

+

Example 1:

+ +

+ +
Input: root = [3,1,4,3,null,1,5]
+Output: 4
+Explanation: Nodes in blue are good.
+Root Node (3) is always a good node.
+Node 4 -> (3,4) is the maximum value in the path starting from the root.
+Node 5 -> (3,4,5) is the maximum value in the path
+Node 3 -> (3,1,3) is the maximum value in the path.
+ +

Example 2:

+ +

+ +
Input: root = [3,3,null,4,2]
+Output: 3
+Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
+ +

Example 3:

+ +
Input: root = [1]
+Output: 1
+Explanation: Root is considered as good.
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the binary tree is in the range [1, 10^5].
  • +
  • Each node's value is between [-10^4, 10^4].
  • +
\ No newline at end of file diff --git a/CPP/Leetcode/1464-maximum-product-of-two-elements-in-an-array/1464-maximum-product-of-two-elements-in-an-array.cpp b/CPP/Leetcode/1464-maximum-product-of-two-elements-in-an-array/1464-maximum-product-of-two-elements-in-an-array.cpp new file mode 100644 index 00000000..e0f86b1e --- /dev/null +++ b/CPP/Leetcode/1464-maximum-product-of-two-elements-in-an-array/1464-maximum-product-of-two-elements-in-an-array.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int maxProduct(vector& nums) { + sort(nums.begin(),nums.end()); + return (nums[nums.size()-1]-1) * (nums[nums.size()-2]-1) ; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1464-maximum-product-of-two-elements-in-an-array/NOTES.md b/CPP/Leetcode/1464-maximum-product-of-two-elements-in-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1464-maximum-product-of-two-elements-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.cpp b/CPP/Leetcode/1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.cpp new file mode 100644 index 00000000..a74aa846 --- /dev/null +++ b/CPP/Leetcode/1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector runningSum(vector& nums) { + vector v; + int sum=0; + for(int i=0;i1480. Running Sum of 1d Array

Easy


Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

+ +

Return the running sum of nums.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4]
+Output: [1,3,6,10]
+Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
+ +

Example 2:

+ +
Input: nums = [1,1,1,1,1]
+Output: [1,2,3,4,5]
+Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
+ +

Example 3:

+ +
Input: nums = [3,1,2,10,1]
+Output: [3,4,6,16,17]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -10^6 <= nums[i] <= 10^6
  • +
\ No newline at end of file diff --git a/CPP/Leetcode/151-reverse-words-in-a-string/151-reverse-words-in-a-string.cpp b/CPP/Leetcode/151-reverse-words-in-a-string/151-reverse-words-in-a-string.cpp new file mode 100644 index 00000000..421091db --- /dev/null +++ b/CPP/Leetcode/151-reverse-words-in-a-string/151-reverse-words-in-a-string.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + string reverseWords(string s) { + string S=s; + int len = S.length(); + + string res = "", tmp = ""; + + stack ss; + + + + for(int i=0; i 1) + + res += ' '; + + ss.pop(); + + } + + + + return res; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/151-reverse-words-in-a-string/README.md b/CPP/Leetcode/151-reverse-words-in-a-string/README.md new file mode 100644 index 00000000..2ef6f35d --- /dev/null +++ b/CPP/Leetcode/151-reverse-words-in-a-string/README.md @@ -0,0 +1,41 @@ +

151. Reverse Words in a String

Medium


Given an input string s, reverse the order of the words.

+ +

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

+ +

Return a string of the words in reverse order concatenated by a single space.

+ +

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

+ +

 

+

Example 1:

+ +
Input: s = "the sky is blue"
+Output: "blue is sky the"
+
+ +

Example 2:

+ +
Input: s = "  hello world  "
+Output: "world hello"
+Explanation: Your reversed string should not contain leading or trailing spaces.
+
+ +

Example 3:

+ +
Input: s = "a good   example"
+Output: "example good a"
+Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • +
  • There is at least one word in s.
  • +
+ +

 

+

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

+
\ No newline at end of file diff --git a/CPP/Leetcode/1614-maximum-nesting-depth-of-the-parentheses/1614-maximum-nesting-depth-of-the-parentheses.cpp b/CPP/Leetcode/1614-maximum-nesting-depth-of-the-parentheses/1614-maximum-nesting-depth-of-the-parentheses.cpp new file mode 100644 index 00000000..67a5fd83 --- /dev/null +++ b/CPP/Leetcode/1614-maximum-nesting-depth-of-the-parentheses/1614-maximum-nesting-depth-of-the-parentheses.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int maxDepth(string s) { + int cnt=0; + int m=0; + for(int i=0;i next; + index ++; + } + deleted = keep; + + while (index != b + 1) { + keep = keep -> next; + index ++; + } + cat = keep; + deleted -> next = list2; + while (list2 -> next != nullptr) { + list2 = list2 -> next; + } + list2 -> next = cat; + return list1; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1669-merge-in-between-linked-lists/README.md b/CPP/Leetcode/1669-merge-in-between-linked-lists/README.md new file mode 100644 index 00000000..24db7a9d --- /dev/null +++ b/CPP/Leetcode/1669-merge-in-between-linked-lists/README.md @@ -0,0 +1,32 @@ +

1669. Merge In Between Linked Lists

Medium


You are given two linked lists: list1 and list2 of sizes n and m respectively.

+ +

Remove list1's nodes from the ath node to the bth node, and put list2 in their place.

+ +

The blue edges and nodes in the following figure indicate the result:

+ +

Build the result list and return its head.

+ +

 

+

Example 1:

+ +
Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
+Output: [0,1,2,1000000,1000001,1000002,5]
+Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
+
+ +

Example 2:

+ +
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
+Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
+Explanation: The blue edges and nodes in the above figure indicate the result.
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= list1.length <= 104
  • +
  • 1 <= a <= b < list1.length - 1
  • +
  • 1 <= list2.length <= 104
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/167-two-sum-ii-input-array-is-sorted/167-two-sum-ii-input-array-is-sorted.cpp b/CPP/Leetcode/167-two-sum-ii-input-array-is-sorted/167-two-sum-ii-input-array-is-sorted.cpp new file mode 100644 index 00000000..e85c91dd --- /dev/null +++ b/CPP/Leetcode/167-two-sum-ii-input-array-is-sorted/167-two-sum-ii-input-array-is-sorted.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int i=0,j=numbers.size()-1; + vector v; + while(i167. Two Sum II - Input Array Is Sorted

Medium


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.

+ +

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

+ +

The tests are generated such that there is exactly one solution. You may not use the same element twice.

+ +

Your solution must use only constant extra space.

+ +

 

+

Example 1:

+ +
Input: numbers = [2,7,11,15], target = 9
+Output: [1,2]
+Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
+
+ +

Example 2:

+ +
Input: numbers = [2,3,4], target = 6
+Output: [1,3]
+Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
+
+ +

Example 3:

+ +
Input: numbers = [-1,0], target = -1
+Output: [1,2]
+Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= numbers.length <= 3 * 104
  • +
  • -1000 <= numbers[i] <= 1000
  • +
  • numbers is sorted in non-decreasing order.
  • +
  • -1000 <= target <= 1000
  • +
  • The tests are generated such that there is exactly one solution.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1679-max-number-of-k-sum-pairs/1679-max-number-of-k-sum-pairs.cpp b/CPP/Leetcode/1679-max-number-of-k-sum-pairs/1679-max-number-of-k-sum-pairs.cpp new file mode 100644 index 00000000..1b4cf070 --- /dev/null +++ b/CPP/Leetcode/1679-max-number-of-k-sum-pairs/1679-max-number-of-k-sum-pairs.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxOperations(vector& nums, int k) { + unordered_map mp; + int cnt = 0; + for(auto it: nums) + { + int x = k - it; + if(mp[x] > 0){cnt++; mp[x]--;} + else mp[it]++; + } + return cnt; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/1679-max-number-of-k-sum-pairs/NOTES.md b/CPP/Leetcode/1679-max-number-of-k-sum-pairs/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1679-max-number-of-k-sum-pairs/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1679-max-number-of-k-sum-pairs/README.md b/CPP/Leetcode/1679-max-number-of-k-sum-pairs/README.md new file mode 100644 index 00000000..2de99b4a --- /dev/null +++ b/CPP/Leetcode/1679-max-number-of-k-sum-pairs/README.md @@ -0,0 +1,33 @@ +

1679. Max Number of K-Sum Pairs

Medium


You are given an integer array nums and an integer k.

+ +

In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

+ +

Return the maximum number of operations you can perform on the array.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4], k = 5
+Output: 2
+Explanation: Starting with nums = [1,2,3,4]:
+- Remove numbers 1 and 4, then nums = [2,3]
+- Remove numbers 2 and 3, then nums = []
+There are no more pairs that sum up to 5, hence a total of 2 operations.
+ +

Example 2:

+ +
Input: nums = [3,1,3,4,3], k = 6
+Output: 1
+Explanation: Starting with nums = [3,1,3,4,3]:
+- Remove the first two 3's, then nums = [1,4,3]
+There are no more pairs that sum up to 6, hence a total of 1 operation.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 109
  • +
  • 1 <= k <= 109
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.cpp b/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.cpp new file mode 100644 index 00000000..47968dda --- /dev/null +++ b/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.cpp @@ -0,0 +1,46 @@ +/** + * 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* swapNodes(ListNode* head, int k) { + ListNode *curr=head; + ListNode *node=head; + ListNode *hehe=head; + int n=0; + while(hehe->next!=NULL) + { + hehe=hehe->next; + n++; + } + int i=1; + while(i!=k) + { + curr=curr->next; + i++; + } + i=0; + while(i!=(n-k+1)) + { + node=node->next; + i++; + } + int temp=curr->val; + curr->val=node->val; + node->val=temp; + return head; + + + } +}; + + + + \ No newline at end of file diff --git a/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/NOTES.md b/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/README.md b/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/README.md new file mode 100644 index 00000000..e84ddbb8 --- /dev/null +++ b/CPP/Leetcode/1721-swapping-nodes-in-a-linked-list/README.md @@ -0,0 +1,26 @@ +

1721. Swapping Nodes in a Linked List

Medium


You are given the head of a linked list, and an integer k.

+ +

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], k = 2
+Output: [1,4,3,2,5]
+
+ +

Example 2:

+ +
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
+Output: [7,9,6,6,8,7,3,0,9,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is n.
  • +
  • 1 <= k <= n <= 105
  • +
  • 0 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1752-check-if-array-is-sorted-and-rotated/README.md b/CPP/Leetcode/1752-check-if-array-is-sorted-and-rotated/README.md new file mode 100644 index 00000000..94dd3a45 --- /dev/null +++ b/CPP/Leetcode/1752-check-if-array-is-sorted-and-rotated/README.md @@ -0,0 +1,38 @@ +

1752. Check if Array Is Sorted and Rotated

Easy


Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.

+ +

There may be duplicates in the original array.

+ +

Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.

+ +

 

+

Example 1:

+ +
Input: nums = [3,4,5,1,2]
+Output: true
+Explanation: [1,2,3,4,5] is the original sorted array.
+You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].
+
+ +

Example 2:

+ +
Input: nums = [2,1,3,4]
+Output: false
+Explanation: There is no sorted array once rotated that can make nums.
+
+ +

Example 3:

+ +
Input: nums = [1,2,3]
+Output: true
+Explanation: [1,2,3] is the original sorted array.
+You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1768-merge-strings-alternately/1768-merge-strings-alternately.cpp b/CPP/Leetcode/1768-merge-strings-alternately/1768-merge-strings-alternately.cpp new file mode 100644 index 00000000..8374cffb --- /dev/null +++ b/CPP/Leetcode/1768-merge-strings-alternately/1768-merge-strings-alternately.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + string mergeAlternately(string word1, string word2) { + string ans=""; + int n=word1.length(); + int m=word2.length(); + int i=0; + for(i=0;i1768. Merge Strings Alternately

Easy


You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

+ +

Return the merged string.

+ +

 

+

Example 1:

+ +
Input: word1 = "abc", word2 = "pqr"
+Output: "apbqcr"
+Explanation: The merged string will be merged as so:
+word1:  a   b   c
+word2:    p   q   r
+merged: a p b q c r
+
+ +

Example 2:

+ +
Input: word1 = "ab", word2 = "pqrs"
+Output: "apbqrs"
+Explanation: Notice that as word2 is longer, "rs" is appended to the end.
+word1:  a   b 
+word2:    p   q   r   s
+merged: a p b q   r   s
+
+ +

Example 3:

+ +
Input: word1 = "abcd", word2 = "pq"
+Output: "apbqcd"
+Explanation: Notice that as word1 is longer, "cd" is appended to the end.
+word1:  a   b   c   d
+word2:    p   q 
+merged: a p b q c   d
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word1.length, word2.length <= 100
  • +
  • word1 and word2 consist of lowercase English letters.
  • +
\ No newline at end of file diff --git a/CPP/Leetcode/1832-check-if-the-sentence-is-pangram/1832-check-if-the-sentence-is-pangram.cpp b/CPP/Leetcode/1832-check-if-the-sentence-is-pangram/1832-check-if-the-sentence-is-pangram.cpp new file mode 100644 index 00000000..44e4fef4 --- /dev/null +++ b/CPP/Leetcode/1832-check-if-the-sentence-is-pangram/1832-check-if-the-sentence-is-pangram.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool checkIfPangram(string sentence) { + unordered_map mp; + for(int i=0;i1832. Check if the Sentence Is Pangram

Easy


A pangram is a sentence where every letter of the English alphabet appears at least once.

+ +

Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

+ +

 

+

Example 1:

+ +
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
+Output: true
+Explanation: sentence contains at least one of every letter of the English alphabet.
+
+ +

Example 2:

+ +
Input: sentence = "leetcode"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= sentence.length <= 1000
  • +
  • sentence consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/1859-sorting-the-sentence/1859-sorting-the-sentence.cpp b/CPP/Leetcode/1859-sorting-the-sentence/1859-sorting-the-sentence.cpp new file mode 100644 index 00000000..8926f33d --- /dev/null +++ b/CPP/Leetcode/1859-sorting-the-sentence/1859-sorting-the-sentence.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string sortSentence(string s) { + vector> v; + string k=""; + for(int i=0;i='1' && s[i]<='9') + { + v.push_back({s[i],k}); + k=""; + i++; + } + else k=k+s[i]; + } + sort(v.begin(),v.end()); + string s1=""; + for(int i=0;i1859. Sorting the Sentence

Easy


A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.

+ +

A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.

+ +
    +
  • For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".
  • +
+ +

Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.

+ +

 

+

Example 1:

+ +
Input: s = "is2 sentence4 This1 a3"
+Output: "This is a sentence"
+Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
+
+ +

Example 2:

+ +
Input: s = "Myself2 Me1 I4 and3"
+Output: "Me Myself and I"
+Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 200
  • +
  • s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
  • +
  • The number of words in s is between 1 and 9.
  • +
  • The words in s are separated by a single space.
  • +
  • s contains no leading or trailing spaces.
  • +
\ No newline at end of file diff --git a/CPP/Leetcode/189-rotate-array/NOTES.md b/CPP/Leetcode/189-rotate-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/189-rotate-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/189-rotate-array/README.md b/CPP/Leetcode/189-rotate-array/README.md new file mode 100644 index 00000000..71648397 --- /dev/null +++ b/CPP/Leetcode/189-rotate-array/README.md @@ -0,0 +1,39 @@ +

189. Rotate Array

Medium


Given an array, rotate the array to the right by k steps, where k is non-negative.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,3,4,5,6,7], k = 3
+Output: [5,6,7,1,2,3,4]
+Explanation:
+rotate 1 steps to the right: [7,1,2,3,4,5,6]
+rotate 2 steps to the right: [6,7,1,2,3,4,5]
+rotate 3 steps to the right: [5,6,7,1,2,3,4]
+
+ +

Example 2:

+ +
Input: nums = [-1,-100,3,99], k = 2
+Output: [3,99,-1,-100]
+Explanation: 
+rotate 1 steps to the right: [99,-1,-100,3]
+rotate 2 steps to the right: [3,99,-1,-100]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • 0 <= k <= 105
  • +
+ +

 

+

Follow up:

+ +
    +
  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • +
  • Could you do it in-place with O(1) extra space?
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.cpp b/CPP/Leetcode/19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.cpp new file mode 100644 index 00000000..619e44e8 --- /dev/null +++ b/CPP/Leetcode/19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.cpp @@ -0,0 +1,40 @@ +/** + * 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* removeNthFromEnd(ListNode* head, int n) { + ListNode* ptr=head; //count the nodes + int k=0; + + while(ptr!=NULL){ + k++; + ptr=ptr->next; + } + + k=k-n; + + //make the pointer to connext the head with dummy node and the ptr to head + ListNode* dum= new ListNode(-1); + dum->next=head; + ptr=dum; + //run the loop until count not zero + while(k!=0){ + ptr=ptr->next; + k--; + } + //make the connection + + ptr->next=ptr->next->next; + + +return dum->next; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/19-remove-nth-node-from-end-of-list/README.md b/CPP/Leetcode/19-remove-nth-node-from-end-of-list/README.md new file mode 100644 index 00000000..8d4110a9 --- /dev/null +++ b/CPP/Leetcode/19-remove-nth-node-from-end-of-list/README.md @@ -0,0 +1,34 @@ +

19. Remove Nth Node From End of List

Medium


Given the head of a linked list, remove the nth node from the end of the list and return its head.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5], n = 2
+Output: [1,2,3,5]
+
+ +

Example 2:

+ +
Input: head = [1], n = 1
+Output: []
+
+ +

Example 3:

+ +
Input: head = [1,2], n = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is sz.
  • +
  • 1 <= sz <= 30
  • +
  • 0 <= Node.val <= 100
  • +
  • 1 <= n <= sz
  • +
+ +

 

+

Follow up: Could you do this in one pass?

+
\ No newline at end of file diff --git a/CPP/Leetcode/191-number-of-1-bits/191-number-of-1-bits.cpp b/CPP/Leetcode/191-number-of-1-bits/191-number-of-1-bits.cpp new file mode 100644 index 00000000..0d0a5e03 --- /dev/null +++ b/CPP/Leetcode/191-number-of-1-bits/191-number-of-1-bits.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int hammingWeight(uint32_t n) { + unsigned int count = 0; + while (n) + { + n &= (n-1) ; + count++; + } + return count; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/191-number-of-1-bits/NOTES.md b/CPP/Leetcode/191-number-of-1-bits/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/191-number-of-1-bits/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/1941-check-if-all-characters-have-equal-number-of-occurrences/1941-check-if-all-characters-have-equal-number-of-occurrences.cpp b/CPP/Leetcode/1941-check-if-all-characters-have-equal-number-of-occurrences/1941-check-if-all-characters-have-equal-number-of-occurrences.cpp new file mode 100644 index 00000000..49edf0ac --- /dev/null +++ b/CPP/Leetcode/1941-check-if-all-characters-have-equal-number-of-occurrences/1941-check-if-all-characters-have-equal-number-of-occurrences.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool areOccurrencesEqual(string s) { + unordered_map mp; + for(int i=0;i1941. Check if All Characters Have Equal Number of Occurrences

Easy


Given a string s, return true if s is a good string, or false otherwise.

+ +

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

+ +

 

+

Example 1:

+ +
Input: s = "abacbc"
+Output: true
+Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
+
+ +

Example 2:

+ +
Input: s = "aaabb"
+Output: false
+Explanation: The characters that appear in s are 'a' and 'b'.
+'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/20-valid-parentheses/20-valid-parentheses.cpp b/CPP/Leetcode/20-valid-parentheses/20-valid-parentheses.cpp new file mode 100644 index 00000000..d69de511 --- /dev/null +++ b/CPP/Leetcode/20-valid-parentheses/20-valid-parentheses.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool isValid(string s) { + stack st; + for(int i=0;i20. Valid Parentheses

Easy


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

+ +

An input string is valid if:

+ +
    +
  1. Open brackets must be closed by the same type of brackets.
  2. +
  3. Open brackets must be closed in the correct order.
  4. +
+ +

 

+

Example 1:

+ +
Input: s = "()"
+Output: true
+
+ +

Example 2:

+ +
Input: s = "()[]{}"
+Output: true
+
+ +

Example 3:

+ +
Input: s = "(]"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of parentheses only '()[]{}'.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2007-find-original-array-from-doubled-array/2007-find-original-array-from-doubled-array.cpp b/CPP/Leetcode/2007-find-original-array-from-doubled-array/2007-find-original-array-from-doubled-array.cpp new file mode 100644 index 00000000..2222bc69 --- /dev/null +++ b/CPP/Leetcode/2007-find-original-array-from-doubled-array/2007-find-original-array-from-doubled-array.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector findOriginalArray(vector& changed) { + vector v; + sort(changed.begin(),changed.end()); + map mp; + for(int i=0;i& operations) { + int x=0; + for(int i=0;i targetIndices(vector& nums, int target) { + sort(nums.begin(),nums.end()); + int n=nums.size(); + vector v; + for(int i=0;i2089. Find Target Indices After Sorting Array

Easy


You are given a 0-indexed integer array nums and a target element target.

+ +

A target index is an index i such that nums[i] == target.

+ +

Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.

+ +

 

+

Example 1:

+ +
Input: nums = [1,2,5,2,3], target = 2
+Output: [1,2]
+Explanation: After sorting, nums is [1,2,2,3,5].
+The indices where nums[i] == 2 are 1 and 2.
+
+ +

Example 2:

+ +
Input: nums = [1,2,5,2,3], target = 3
+Output: [3]
+Explanation: After sorting, nums is [1,2,2,3,5].
+The index where nums[i] == 3 is 3.
+
+ +

Example 3:

+ +
Input: nums = [1,2,5,2,3], target = 5
+Output: [4]
+Explanation: After sorting, nums is [1,2,2,3,5].
+The index where nums[i] == 5 is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i], target <= 100
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2125-number-of-laser-beams-in-a-bank/2125-number-of-laser-beams-in-a-bank.cpp b/CPP/Leetcode/2125-number-of-laser-beams-in-a-bank/2125-number-of-laser-beams-in-a-bank.cpp new file mode 100644 index 00000000..c0f47dae --- /dev/null +++ b/CPP/Leetcode/2125-number-of-laser-beams-in-a-bank/2125-number-of-laser-beams-in-a-bank.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int numberOfBeams(vector& bank) { + int f=0; + vector v; + int cnt=0; + for(int i=0;i2125. Number of Laser Beams in a Bank

Medium


Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.

+ +

There is one laser beam between any two security devices if both conditions are met:

+ +
    +
  • The two devices are located on two different rows: r1 and r2, where r1 < r2.
  • +
  • For each row i where r1 < i < r2, there are no security devices in the ith row.
  • +
+ +

Laser beams are independent, i.e., one beam does not interfere nor join with another.

+ +

Return the total number of laser beams in the bank.

+ +

 

+

Example 1:

+ +
Input: bank = ["011001","000000","010100","001000"]
+Output: 8
+Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams:
+ * bank[0][1] -- bank[2][1]
+ * bank[0][1] -- bank[2][3]
+ * bank[0][2] -- bank[2][1]
+ * bank[0][2] -- bank[2][3]
+ * bank[0][5] -- bank[2][1]
+ * bank[0][5] -- bank[2][3]
+ * bank[2][1] -- bank[3][2]
+ * bank[2][3] -- bank[3][2]
+Note that there is no beam between any device on the 0th row with any on the 3rd row.
+This is because the 2nd row contains security devices, which breaks the second condition.
+
+ +

Example 2:

+ +
Input: bank = ["000","111","000"]
+Output: 0
+Explanation: There does not exist two devices located on two different rows.
+
+ +

 

+

Constraints:

+ +
    +
  • m == bank.length
  • +
  • n == bank[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • bank[i][j] is either '0' or '1'.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2130-maximum-twin-sum-of-a-linked-list/README.md b/CPP/Leetcode/2130-maximum-twin-sum-of-a-linked-list/README.md new file mode 100644 index 00000000..b3543c2a --- /dev/null +++ b/CPP/Leetcode/2130-maximum-twin-sum-of-a-linked-list/README.md @@ -0,0 +1,48 @@ +

2130. Maximum Twin Sum of a Linked List

Medium


In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.

+ +
    +
  • For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
  • +
+ +

The twin sum is defined as the sum of a node and its twin.

+ +

Given the head of a linked list with even length, return the maximum twin sum of the linked list.

+ +

 

+

Example 1:

+ +
Input: head = [5,4,2,1]
+Output: 6
+Explanation:
+Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
+There are no other nodes with twins in the linked list.
+Thus, the maximum twin sum of the linked list is 6. 
+
+ +

Example 2:

+ +
Input: head = [4,2,2,3]
+Output: 7
+Explanation:
+The nodes with twins present in this linked list are:
+- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
+- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
+Thus, the maximum twin sum of the linked list is max(7, 4) = 7. 
+
+ +

Example 3:

+ +
Input: head = [1,100000]
+Output: 100001
+Explanation:
+There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is an even integer in the range [2, 105].
  • +
  • 1 <= Node.val <= 105
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2149-rearrange-array-elements-by-sign/2149-rearrange-array-elements-by-sign.cpp b/CPP/Leetcode/2149-rearrange-array-elements-by-sign/2149-rearrange-array-elements-by-sign.cpp new file mode 100644 index 00000000..c53bec96 --- /dev/null +++ b/CPP/Leetcode/2149-rearrange-array-elements-by-sign/2149-rearrange-array-elements-by-sign.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector rearrangeArray(vector& nums) { + vector neg; + vector pos; + for(int i=0;i v; + for(int i=0;i2149. Rearrange Array Elements by Sign

Medium


You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

+ +

You should rearrange the elements of nums such that the modified array follows the given conditions:

+ +
    +
  1. Every consecutive pair of integers have opposite signs.
  2. +
  3. For all integers with the same sign, the order in which they were present in nums is preserved.
  4. +
  5. The rearranged array begins with a positive integer.
  6. +
+ +

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

+ +

 

+

Example 1:

+ +
Input: nums = [3,1,-2,-5,2,-4]
+Output: [3,-2,1,-5,2,-4]
+Explanation:
+The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
+The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
+Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  
+
+ +

Example 2:

+ +
Input: nums = [-1,1]
+Output: [1,-1]
+Explanation:
+1 is the only positive integer and -1 the only negative integer in nums.
+So nums is rearranged to [1,-1].
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 2 * 105
  • +
  • nums.length is even
  • +
  • 1 <= |nums[i]| <= 105
  • +
  • nums consists of equal number of positive and negative integers.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2150-find-all-lonely-numbers-in-the-array/2150-find-all-lonely-numbers-in-the-array.cpp b/CPP/Leetcode/2150-find-all-lonely-numbers-in-the-array/2150-find-all-lonely-numbers-in-the-array.cpp new file mode 100644 index 00000000..6dbcc3b2 --- /dev/null +++ b/CPP/Leetcode/2150-find-all-lonely-numbers-in-the-array/2150-find-all-lonely-numbers-in-the-array.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector findLonely(vector& nums) { + unordered_map mp; + for(int i=0;i v; + for(int i=0;i2150. Find All Lonely Numbers in the Array

Medium


You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.

+ +

Return all lonely numbers in nums. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [10,6,5,8]
+Output: [10,8]
+Explanation: 
+- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.
+- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.
+- 5 is not a lonely number since 6 appears in nums and vice versa.
+Hence, the lonely numbers in nums are [10, 8].
+Note that [8, 10] may also be returned.
+
+ +

Example 2:

+ +
Input: nums = [1,3,5,3]
+Output: [1,5]
+Explanation: 
+- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.
+- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.
+- 3 is not a lonely number since it appears twice.
+Hence, the lonely numbers in nums are [1, 5].
+Note that [5, 1] may also be returned.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 106
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2164-sort-even-and-odd-indices-independently/README.md b/CPP/Leetcode/2164-sort-even-and-odd-indices-independently/README.md new file mode 100644 index 00000000..5085b16b --- /dev/null +++ b/CPP/Leetcode/2164-sort-even-and-odd-indices-independently/README.md @@ -0,0 +1,48 @@ +

2164. Sort Even and Odd Indices Independently

Easy


You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:

+ +
    +
  1. Sort the values at odd indices of nums in non-increasing order. + +
      +
    • For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order.
    • +
    +
  2. +
  3. Sort the values at even indices of nums in non-decreasing order. +
      +
    • For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order.
    • +
    +
  4. +
+ +

Return the array formed after rearranging the values of nums.

+ +

 

+

Example 1:

+ +
Input: nums = [4,1,2,3]
+Output: [2,3,4,1]
+Explanation: 
+First, we sort the values present at odd indices (1 and 3) in non-increasing order.
+So, nums changes from [4,1,2,3] to [4,3,2,1].
+Next, we sort the values present at even indices (0 and 2) in non-decreasing order.
+So, nums changes from [4,1,2,3] to [2,3,4,1].
+Thus, the array formed after rearranging the values is [2,3,4,1].
+
+ +

Example 2:

+ +
Input: nums = [2,1]
+Output: [2,1]
+Explanation: 
+Since there is exactly one odd index and one even index, no rearrangement of values takes place.
+The resultant array formed is [2,1], which is the same as the initial array. 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i] <= 100
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.cpp b/CPP/Leetcode/2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.cpp new file mode 100644 index 00000000..d6e8c2c4 --- /dev/null +++ b/CPP/Leetcode/2181-merge-nodes-in-between-zeros/2181-merge-nodes-in-between-zeros.cpp @@ -0,0 +1,34 @@ +/** + * 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* mergeNodes(ListNode* head) { + ListNode *curr=head->next; + ListNode *n=head; + int cnt=0; + while(curr!=NULL) + { + if(curr->val!=0) + { + cnt+=curr->val; + } + else + { + n->next=curr; + curr->val=cnt; + cnt=0; + n=curr; + } + curr=curr->next; + } + return head->next; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/2181-merge-nodes-in-between-zeros/README.md b/CPP/Leetcode/2181-merge-nodes-in-between-zeros/README.md new file mode 100644 index 00000000..56a63a52 --- /dev/null +++ b/CPP/Leetcode/2181-merge-nodes-in-between-zeros/README.md @@ -0,0 +1,38 @@ +

2181. Merge Nodes in Between Zeros

Medium


You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.

+ +

For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.

+ +

Return the head of the modified linked list.

+ +

 

+

Example 1:

+ +
Input: head = [0,3,1,0,4,5,2,0]
+Output: [4,11]
+Explanation: 
+The above figure represents the given linked list. The modified list contains
+- The sum of the nodes marked in green: 3 + 1 = 4.
+- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
+
+ +

Example 2:

+ +
Input: head = [0,1,0,3,0,2,2,0]
+Output: [1,3,4]
+Explanation: 
+The above figure represents the given linked list. The modified list contains
+- The sum of the nodes marked in green: 1 = 1.
+- The sum of the nodes marked in red: 3 = 3.
+- The sum of the nodes marked in yellow: 2 + 2 = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [3, 2 * 105].
  • +
  • 0 <= Node.val <= 1000
  • +
  • There are no two consecutive nodes with Node.val == 0.
  • +
  • The beginning and end of the linked list have Node.val == 0.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2296-design-a-text-editor/2296-design-a-text-editor.cpp b/CPP/Leetcode/2296-design-a-text-editor/2296-design-a-text-editor.cpp new file mode 100644 index 00000000..a87faf5b --- /dev/null +++ b/CPP/Leetcode/2296-design-a-text-editor/2296-design-a-text-editor.cpp @@ -0,0 +1,64 @@ +class TextEditor { +private: + lista; + // If delete, will delete position cur - 1, not position cur. + list::iterator cur; +public: + TextEditor() { + a.clear(); + // For convenience. + a.push_back('A'); + cur = a.end(); + } + + void addText(string text) { + a.insert(cur, text.begin(), text.end()); + } + + int deleteText(int k) { + int cnt = 0; + // Move to the position that will be deleted. + cur--; + while(k--){ + if(cur==a.begin())break; + cnt++; + a.erase(cur--); + } + // Adjust the position of the cursor. + cur++; + return cnt; + } + + // Left 10 chars. + string solve() { + auto tt = cur; + tt--; + string ret; + int k = 10; + while(k--){ + if(tt==a.begin())break; + ret += (*(tt--)); + } + reverse(ret.begin(), ret.end()); + return ret; + } + + string cursorLeft(int k) { + while(k--){ + auto nxt = cur; + nxt--; + // Never move the cursor to the first position. + if(nxt==a.begin())break; + cur = nxt; + } + return solve(); + } + + string cursorRight(int k) { + while(k--){ + if(cur==a.end())break; + cur++; + } + return solve(); + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/2296-design-a-text-editor/README.md b/CPP/Leetcode/2296-design-a-text-editor/README.md new file mode 100644 index 00000000..7aeee1f9 --- /dev/null +++ b/CPP/Leetcode/2296-design-a-text-editor/README.md @@ -0,0 +1,67 @@ +

2296. Design a Text Editor

Hard


Design a text editor with a cursor that can do the following:

+ +
    +
  • Add text to where the cursor is.
  • +
  • Delete text from where the cursor is (simulating the backspace key).
  • +
  • Move the cursor either left or right.
  • +
+ +

When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.

+ +

Implement the TextEditor class:

+ +
    +
  • TextEditor() Initializes the object with empty text.
  • +
  • void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
  • +
  • int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
  • +
  • string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
  • +
  • string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
  • +
+ +

 

+

Example 1:

+ +
Input
+["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
+[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
+Output
+[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
+
+Explanation
+TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
+textEditor.addText("leetcode"); // The current text is "leetcode|".
+textEditor.deleteText(4); // return 4
+                          // The current text is "leet|". 
+                          // 4 characters were deleted.
+textEditor.addText("practice"); // The current text is "leetpractice|". 
+textEditor.cursorRight(3); // return "etpractice"
+                           // The current text is "leetpractice|". 
+                           // The cursor cannot be moved beyond the actual text and thus did not move.
+                           // "etpractice" is the last 10 characters to the left of the cursor.
+textEditor.cursorLeft(8); // return "leet"
+                          // The current text is "leet|practice".
+                          // "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
+textEditor.deleteText(10); // return 4
+                           // The current text is "|practice".
+                           // Only 4 characters were deleted.
+textEditor.cursorLeft(2); // return ""
+                          // The current text is "|practice".
+                          // The cursor cannot be moved beyond the actual text and thus did not move. 
+                          // "" is the last min(10, 0) = 0 characters to the left of the cursor.
+textEditor.cursorRight(6); // return "practi"
+                           // The current text is "practi|ce".
+                           // "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= text.length, k <= 40
  • +
  • text consists of lowercase English letters.
  • +
  • At most 2 * 104 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
  • +
+ +

 

+

Follow-up: Could you find a solution with time complexity of O(k) per call?

+
\ No newline at end of file diff --git a/CPP/Leetcode/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp b/CPP/Leetcode/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp new file mode 100644 index 00000000..efdc8676 --- /dev/null +++ b/CPP/Leetcode/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.cpp @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + ListNode *ptr=node; + swap(ptr->val,ptr->next->val); + cout << ptr->val; + ListNode *p2=ptr->next; + ptr->next=ptr->next->next; + delete(p2); + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/237-delete-node-in-a-linked-list/NOTES.md b/CPP/Leetcode/237-delete-node-in-a-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/237-delete-node-in-a-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/237-delete-node-in-a-linked-list/README.md b/CPP/Leetcode/237-delete-node-in-a-linked-list/README.md new file mode 100644 index 00000000..797f85a2 --- /dev/null +++ b/CPP/Leetcode/237-delete-node-in-a-linked-list/README.md @@ -0,0 +1,29 @@ +

237. Delete Node in a Linked List

Easy


Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.

+ +

It is guaranteed that the node to be deleted is not a tail node in the list.

+ +

 

+

Example 1:

+ +
Input: head = [4,5,1,9], node = 5
+Output: [4,1,9]
+Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
+
+ +

Example 2:

+ +
Input: head = [4,5,1,9], node = 1
+Output: [4,5,9]
+Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the given list is in the range [2, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • The value of each node in the list is unique.
  • +
  • The node to be deleted is in the list and is not a tail node
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/2395-find-subarrays-with-equal-sum/2395-find-subarrays-with-equal-sum.cpp b/CPP/Leetcode/2395-find-subarrays-with-equal-sum/2395-find-subarrays-with-equal-sum.cpp new file mode 100644 index 00000000..b324f449 --- /dev/null +++ b/CPP/Leetcode/2395-find-subarrays-with-equal-sum/2395-find-subarrays-with-equal-sum.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool findSubarrays(vector& nums) { + set s; + for(int i=1;i=nums.size()-1) return false; + return true; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/2395-find-subarrays-with-equal-sum/README.md b/CPP/Leetcode/2395-find-subarrays-with-equal-sum/README.md new file mode 100644 index 00000000..07b7f46b --- /dev/null +++ b/CPP/Leetcode/2395-find-subarrays-with-equal-sum/README.md @@ -0,0 +1,37 @@ +

2395. Find Subarrays With Equal Sum

Easy


Given a 0-indexed integer array nums, determine whether there exist two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices.

+ +

Return true if these subarrays exist, and false otherwise.

+ +

A subarray is a contiguous non-empty sequence of elements within an array.

+ +

 

+

Example 1:

+ +
Input: nums = [4,2,4]
+Output: true
+Explanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.
+
+ +

Example 2:

+ +
Input: nums = [1,2,3,4,5]
+Output: false
+Explanation: No two subarrays of size 2 have the same sum.
+
+ +

Example 3:

+ +
Input: nums = [0,0,0]
+Output: true
+Explanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. 
+Note that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 1000
  • +
  • -109 <= nums[i] <= 109
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp b/CPP/Leetcode/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp new file mode 100644 index 00000000..fa7b4c5d --- /dev/null +++ b/CPP/Leetcode/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp @@ -0,0 +1,24 @@ +/** + * 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* swapPairs(ListNode* head) { + if(head == NULL || head -> next == NULL) + { + return head; + } + ListNode* temp; + temp=head->next; + head->next=swapPairs(head->next->next); + temp->next=head; + return temp; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/24-swap-nodes-in-pairs/README.md b/CPP/Leetcode/24-swap-nodes-in-pairs/README.md new file mode 100644 index 00000000..562c3539 --- /dev/null +++ b/CPP/Leetcode/24-swap-nodes-in-pairs/README.md @@ -0,0 +1,29 @@ +

24. Swap Nodes in Pairs

Medium


Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4]
+Output: [2,1,4,3]
+
+ +

Example 2:

+ +
Input: head = []
+Output: []
+
+ +

Example 3:

+ +
Input: head = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 100].
  • +
  • 0 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/242-valid-anagram/242-valid-anagram.cpp b/CPP/Leetcode/242-valid-anagram/242-valid-anagram.cpp new file mode 100644 index 00000000..fe1af101 --- /dev/null +++ b/CPP/Leetcode/242-valid-anagram/242-valid-anagram.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool isAnagram(string s, string t) { + unordered_map m1; + unordered_map m2; + for(int i=0;i242. Valid Anagram

Easy


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

+ +

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

+ +

 

+

Example 1:

+
Input: s = "anagram", t = "nagaram"
+Output: true
+

Example 2:

+
Input: s = "rat", t = "car"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 5 * 104
  • +
  • s and t consist of lowercase English letters.
  • +
+ +

 

+

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

+
\ No newline at end of file diff --git a/CPP/Leetcode/26-remove-duplicates-from-sorted-array/26-remove-duplicates-from-sorted-array.cpp b/CPP/Leetcode/26-remove-duplicates-from-sorted-array/26-remove-duplicates-from-sorted-array.cpp new file mode 100644 index 00000000..efe14afd --- /dev/null +++ b/CPP/Leetcode/26-remove-duplicates-from-sorted-array/26-remove-duplicates-from-sorted-array.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + int cnt=1; + for(int i=0;i26. Remove Duplicates from Sorted Array

Easy


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.

+ +

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.

+ +

Return k after placing the final result in the first k slots of nums.

+ +

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

+ +

Custom Judge:

+ +

The judge will test your solution with the following code:

+ +
int[] nums = [...]; // Input array
+int[] expectedNums = [...]; // The expected answer with correct length
+
+int k = removeDuplicates(nums); // Calls your implementation
+
+assert k == expectedNums.length;
+for (int i = 0; i < k; i++) {
+    assert nums[i] == expectedNums[i];
+}
+
+ +

If all assertions pass, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2]
+Output: 2, nums = [1,2,_]
+Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

Example 2:

+ +
Input: nums = [0,0,1,1,1,2,2,3,3,4]
+Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
+Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -100 <= nums[i] <= 100
  • +
  • nums is sorted in non-decreasing order.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/268-missing-number/268-missing-number.cpp b/CPP/Leetcode/268-missing-number/268-missing-number.cpp new file mode 100644 index 00000000..d904a2b0 --- /dev/null +++ b/CPP/Leetcode/268-missing-number/268-missing-number.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int missingNumber(vector& nums) { + int sum=0; + for(auto it:nums) + { + sum+=it; + } + int n=nums.size(); + sum=((n*(n+1))/2) - sum; + return sum; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/268-missing-number/NOTES.md b/CPP/Leetcode/268-missing-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/268-missing-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/268-missing-number/README.md b/CPP/Leetcode/268-missing-number/README.md new file mode 100644 index 00000000..3a8a33a3 --- /dev/null +++ b/CPP/Leetcode/268-missing-number/README.md @@ -0,0 +1,37 @@ +

268. Missing Number

Easy


Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

+ +

 

+

Example 1:

+ +
Input: nums = [3,0,1]
+Output: 2
+Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
+
+ +

Example 2:

+ +
Input: nums = [0,1]
+Output: 2
+Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
+
+ +

Example 3:

+ +
Input: nums = [9,6,4,2,3,5,7,0,1]
+Output: 8
+Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 104
  • +
  • 0 <= nums[i] <= n
  • +
  • All the numbers of nums are unique.
  • +
+ +

 

+

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

+
\ No newline at end of file diff --git a/CPP/Leetcode/283-move-zeroes/283-move-zeroes.cpp b/CPP/Leetcode/283-move-zeroes/283-move-zeroes.cpp new file mode 100644 index 00000000..dc06a8d1 --- /dev/null +++ b/CPP/Leetcode/283-move-zeroes/283-move-zeroes.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + int m=0; + int n=nums.size(); + for(int i=0;i283. Move Zeroes

Easy


Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

+ +

Note that you must do this in-place without making a copy of the array.

+ +

 

+

Example 1:

+
Input: nums = [0,1,0,3,12]
+Output: [1,3,12,0,0]
+

Example 2:

+
Input: nums = [0]
+Output: [0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Could you minimize the total number of operations done?
\ No newline at end of file diff --git a/CPP/Leetcode/287-find-the-duplicate-number/287-find-the-duplicate-number.cpp b/CPP/Leetcode/287-find-the-duplicate-number/287-find-the-duplicate-number.cpp new file mode 100644 index 00000000..463c3038 --- /dev/null +++ b/CPP/Leetcode/287-find-the-duplicate-number/287-find-the-duplicate-number.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + int slow=nums[0]; + int fast=nums[0]; + do{ + slow=nums[slow]; + fast=nums[nums[fast]]; + }while(slow!=fast); + fast=nums[0]; + while(fast!=slow) + { + slow=nums[slow]; + fast=nums[fast]; + } + return slow; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/287-find-the-duplicate-number/NOTES.md b/CPP/Leetcode/287-find-the-duplicate-number/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/287-find-the-duplicate-number/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/287-find-the-duplicate-number/README.md b/CPP/Leetcode/287-find-the-duplicate-number/README.md new file mode 100644 index 00000000..7e26c348 --- /dev/null +++ b/CPP/Leetcode/287-find-the-duplicate-number/README.md @@ -0,0 +1,37 @@ +

287. Find the Duplicate Number

Medium


Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

+ +

There is only one repeated number in nums, return this repeated number.

+ +

You must solve the problem without modifying the array nums and uses only constant extra space.

+ +

 

+

Example 1:

+ +
Input: nums = [1,3,4,2,2]
+Output: 2
+
+ +

Example 2:

+ +
Input: nums = [3,1,3,4,2]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
  • nums.length == n + 1
  • +
  • 1 <= nums[i] <= n
  • +
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
  • +
+ +

 

+

Follow up:

+ +
    +
  • How can we prove that at least one duplicate number must exist in nums?
  • +
  • Can you solve the problem in linear runtime complexity?
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/300-longest-increasing-subsequence/300-longest-increasing-subsequence.cpp b/CPP/Leetcode/300-longest-increasing-subsequence/300-longest-increasing-subsequence.cpp new file mode 100644 index 00000000..ce55ef2d --- /dev/null +++ b/CPP/Leetcode/300-longest-increasing-subsequence/300-longest-increasing-subsequence.cpp @@ -0,0 +1,47 @@ +class Solution { + private: + int CeilIndex(std::vector& v, int l, int r, int key) +{ + while (r - l > 1) { + int m = l + (r - l) / 2; + if (v[m] >= key) + r = m; + else + l = m; + } + + return r; +} +public: + int lengthOfLIS(vector& v) { + if (v.size() == 0) + return 0; + + std::vector tail(v.size(), 0); + int length = 1; // always points empty slot in tail + + tail[0] = v[0]; + for (size_t i = 1; i < v.size(); i++) { + + // new smallest value + if (v[i] < tail[0]) + tail[0] = v[i]; + + // v[i] extends largest subsequence + else if (v[i] > tail[length - 1]) + tail[length++] = v[i]; + + // v[i] will become end candidate of an existing + // subsequence or Throw away larger elements in all + // LIS, to make room for upcoming greater elements + // than v[i] (and also, v[i] would have already + // appeared in one of LIS, identify the location + // and replace it) + else + tail[CeilIndex(tail, -1, length - 1, v[i])] = v[i]; + } + + return length; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/300-longest-increasing-subsequence/NOTES.md b/CPP/Leetcode/300-longest-increasing-subsequence/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/300-longest-increasing-subsequence/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/300-longest-increasing-subsequence/README.md b/CPP/Leetcode/300-longest-increasing-subsequence/README.md new file mode 100644 index 00000000..9a2c8d6f --- /dev/null +++ b/CPP/Leetcode/300-longest-increasing-subsequence/README.md @@ -0,0 +1,35 @@ +

300. Longest Increasing Subsequence

Medium


Given an integer array nums, return the length of the longest strictly increasing subsequence.

+ +

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

+ +

 

+

Example 1:

+ +
Input: nums = [10,9,2,5,3,7,101,18]
+Output: 4
+Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
+
+ +

Example 2:

+ +
Input: nums = [0,1,0,3,2,3]
+Output: 4
+
+ +

Example 3:

+ +
Input: nums = [7,7,7,7,7,7,7]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2500
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

+
\ No newline at end of file diff --git a/CPP/Leetcode/326-power-of-three/326-power-of-three.cpp b/CPP/Leetcode/326-power-of-three/326-power-of-three.cpp new file mode 100644 index 00000000..6163a9da --- /dev/null +++ b/CPP/Leetcode/326-power-of-three/326-power-of-three.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool isPowerOfThree(int n) { + if(n == 0){ + return false; + } + if(n == 1){ + return true; + } + return (n % 3 == 0) && (isPowerOfThree(n/3)); + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/326-power-of-three/NOTES.md b/CPP/Leetcode/326-power-of-three/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/326-power-of-three/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/33. Search in Rotated Sorted Array/README.md b/CPP/Leetcode/33. Search in Rotated Sorted Array/README.md new file mode 100644 index 00000000..ee9e012f --- /dev/null +++ b/CPP/Leetcode/33. Search in Rotated Sorted Array/README.md @@ -0,0 +1,39 @@ +# 33. Search in Rotated Sorted Array + +There is an integer array nums sorted in ascending order (with distinct values). + +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]. + +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. + +You must write an algorithm with O(log n) runtime complexity. + + + +Example 1: +``` +Input: nums = [4,5,6,7,0,1,2], target = 0 + +Output: 4 +``` + +Example 2: + +``` +Input: nums = [4,5,6,7,0,1,2], target = 3 +Output: -1 +``` + +Example 3: +``` +Input: nums = [1], target = 0 +Output: -1 + ``` + +Constraints: + +- 1 <= nums.length <= 5000 +- -104 <= nums[i] <= 104 +- All values of nums are unique. +- nums is an ascending array that is possibly rotated. +- -104 <= target <= 104 diff --git a/CPP/Leetcode/33. Search in Rotated Sorted Array/Search in Rotated Sorted Array.cpp b/CPP/Leetcode/33. Search in Rotated Sorted Array/Search in Rotated Sorted Array.cpp new file mode 100644 index 00000000..8aa3ba37 --- /dev/null +++ b/CPP/Leetcode/33. Search in Rotated Sorted Array/Search in Rotated Sorted Array.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int binarysearch(vector nums, int target, int low, int high) + { + while(low<=high) + { + int mid=low+(high-low)/2; + if(nums[mid]==target) return mid; + else if(nums[mid]>target) high=mid-1; + else low=mid+1; + } + return -1; + } + int pivotindex(vector nums) + { + int n=nums.size(); + int low=0,high=n-1; + while(low<=high) + { + int mid=low+(high-low)/2; + int prev=mid-1; + int next=mid+1; + if(mid==0){ + prev=(mid+n-1)%n; + } + if(mid==n-1){ + next=(mid+1)%n; + } + if(nums[mid]<=nums[next] && nums[mid]<=nums[prev]) return mid; + else if(nums[mid]>=nums[0]) low=mid+1; + else if(nums[mid]<=nums[n-1]) high=mid-1; + } + return -1; + } + + int search(vector& nums, int target) { + + int n=nums.size(); + if(nums[0]=0) return a; + else if(b>=0) return b; + return -1; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/342-power-of-four/342-power-of-four.cpp b/CPP/Leetcode/342-power-of-four/342-power-of-four.cpp new file mode 100644 index 00000000..010ea52a --- /dev/null +++ b/CPP/Leetcode/342-power-of-four/342-power-of-four.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool isPowerOfFour(int n) { + // Base Cases + if(n == 0){ + return false; + } + if(n == 1){ + return true; + } + + // Check remainder is 0 or not when divided by 3, and recursion call. + return (n % 4 == 0) && (isPowerOfFour(n/4)); + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/342-power-of-four/NOTES.md b/CPP/Leetcode/342-power-of-four/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/342-power-of-four/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/342-power-of-four/README.md b/CPP/Leetcode/342-power-of-four/README.md new file mode 100644 index 00000000..c54783d2 --- /dev/null +++ b/CPP/Leetcode/342-power-of-four/README.md @@ -0,0 +1,24 @@ +

342. Power of Four

Easy


Given an integer n, return true if it is a power of four. Otherwise, return false.

+ +

An integer n is a power of four, if there exists an integer x such that n == 4x.

+ +

 

+

Example 1:

+
Input: n = 16
+Output: true
+

Example 2:

+
Input: n = 5
+Output: false
+

Example 3:

+
Input: n = 1
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion?
\ No newline at end of file diff --git a/CPP/Leetcode/344-reverse-string/344-reverse-string.cpp b/CPP/Leetcode/344-reverse-string/344-reverse-string.cpp new file mode 100644 index 00000000..a08675d5 --- /dev/null +++ b/CPP/Leetcode/344-reverse-string/344-reverse-string.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + void reverseString(vector& s) + { + int l=0; + int r=s.size()-1; + while(l344. Reverse String

Easy


Write a function that reverses a string. The input string is given as an array of characters s.

+ +

You must do this by modifying the input array in-place with O(1) extra memory.

+ +

 

+

Example 1:

+
Input: s = ["h","e","l","l","o"]
+Output: ["o","l","l","e","h"]
+

Example 2:

+
Input: s = ["H","a","n","n","a","h"]
+Output: ["h","a","n","n","a","H"]
+
+

 

+

Constraints:

+ + +
\ No newline at end of file diff --git a/CPP/Leetcode/389-find-the-difference/389-find-the-difference.cpp b/CPP/Leetcode/389-find-the-difference/389-find-the-difference.cpp new file mode 100644 index 00000000..10c3d0f8 --- /dev/null +++ b/CPP/Leetcode/389-find-the-difference/389-find-the-difference.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + char findTheDifference(string s, string t) { + map m1; + map m2; + for(int i=0;i389. Find the Difference

Easy


You are given two strings s and t.

+ +

String t is generated by random shuffling string s and then add one more letter at a random position.

+ +

Return the letter that was added to t.

+ +

 

+

Example 1:

+ +
Input: s = "abcd", t = "abcde"
+Output: "e"
+Explanation: 'e' is the letter that was added.
+
+ +

Example 2:

+ +
Input: s = "", t = "y"
+Output: "y"
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 1000
  • +
  • t.length == s.length + 1
  • +
  • s and t consist of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/448-find-all-numbers-disappeared-in-an-array.cpp b/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/448-find-all-numbers-disappeared-in-an-array.cpp new file mode 100644 index 00000000..9738d727 --- /dev/null +++ b/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/448-find-all-numbers-disappeared-in-an-array.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + vector v; + unordered_map mp; + for(auto it:nums) + { + mp[it]++; + } + int n=nums.size(); + for(int i=1;i<=n;i++) + { + if(mp[i]==0) v.push_back(i); + } + return v; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/NOTES.md b/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/README.md b/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/README.md new file mode 100644 index 00000000..f144bcd0 --- /dev/null +++ b/CPP/Leetcode/448-find-all-numbers-disappeared-in-an-array/README.md @@ -0,0 +1,22 @@ +

448. Find All Numbers Disappeared in an Array

Easy


Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

+ +

 

+

Example 1:

+
Input: nums = [4,3,2,7,8,2,3,1]
+Output: [5,6]
+

Example 2:

+
Input: nums = [1,1]
+Output: [2]
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i] <= n
  • +
+ +

 

+

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

+
\ No newline at end of file diff --git a/CPP/Leetcode/47-permutations-ii/47-permutations-ii.cpp b/CPP/Leetcode/47-permutations-ii/47-permutations-ii.cpp new file mode 100644 index 00000000..41519731 --- /dev/null +++ b/CPP/Leetcode/47-permutations-ii/47-permutations-ii.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector> permuteUnique(vector& nums) + { + set> st; + vector t = nums; + do + { + next_permutation(t.begin(), t.end()); + st.insert(t); + } while (t != nums); + vector> res; + for (auto it: st) + res.push_back(it); + return res; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/47-permutations-ii/README.md b/CPP/Leetcode/47-permutations-ii/README.md new file mode 100644 index 00000000..1158829e --- /dev/null +++ b/CPP/Leetcode/47-permutations-ii/README.md @@ -0,0 +1,26 @@ +

47. Permutations II

Medium


Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

+ +

 

+

Example 1:

+ +
Input: nums = [1,1,2]
+Output:
+[[1,1,2],
+ [1,2,1],
+ [2,1,1]]
+
+ +

Example 2:

+ +
Input: nums = [1,2,3]
+Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 8
  • +
  • -10 <= nums[i] <= 10
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/485-max-consecutive-ones/485-max-consecutive-ones.cpp b/CPP/Leetcode/485-max-consecutive-ones/485-max-consecutive-ones.cpp new file mode 100644 index 00000000..000c39a0 --- /dev/null +++ b/CPP/Leetcode/485-max-consecutive-ones/485-max-consecutive-ones.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int cnt=0; + int m=0; + for(int i=0;i& nums) { + int maxi=-1e4; + int sum=0; + for(auto it:nums) + { + sum+=it; + maxi=max(maxi,sum); + if(sum<0) sum=0; + } + return maxi; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/53-maximum-subarray/NOTES.md b/CPP/Leetcode/53-maximum-subarray/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/53-maximum-subarray/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/535-encode-and-decode-tinyurl/535-encode-and-decode-tinyurl.cpp b/CPP/Leetcode/535-encode-and-decode-tinyurl/535-encode-and-decode-tinyurl.cpp new file mode 100644 index 00000000..43eb40ce --- /dev/null +++ b/CPP/Leetcode/535-encode-and-decode-tinyurl/535-encode-and-decode-tinyurl.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + + unordered_map mp; + string encode(string longUrl) { + mp["enigma"]=longUrl; + return "enigma"; + + } + + // Decodes a shortened URL to its original URL. + string decode(string shortUrl) { + return mp[shortUrl]; + } +}; + +// Your Solution object will be instantiated and called as such: +// Solution solution; +// solution.decode(solution.encode(url)); \ No newline at end of file diff --git a/CPP/Leetcode/535-encode-and-decode-tinyurl/NOTES.md b/CPP/Leetcode/535-encode-and-decode-tinyurl/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/535-encode-and-decode-tinyurl/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/557-reverse-words-in-a-string-iii/557-reverse-words-in-a-string-iii.cpp b/CPP/Leetcode/557-reverse-words-in-a-string-iii/557-reverse-words-in-a-string-iii.cpp new file mode 100644 index 00000000..57d44ce5 --- /dev/null +++ b/CPP/Leetcode/557-reverse-words-in-a-string-iii/557-reverse-words-in-a-string-iii.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string reverseWords(string s) { + string k=""; + string res=""; + for(int i=0;i557. Reverse Words in a String III

Easy


Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

+ +

 

+

Example 1:

+
Input: s = "Let's take LeetCode contest"
+Output: "s'teL ekat edoCteeL tsetnoc"
+

Example 2:

+
Input: s = "God Ding"
+Output: "doG gniD"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s contains printable ASCII characters.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • There is at least one word in s.
  • +
  • All the words in s are separated by a single space.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/680-valid-palindrome-ii/680-valid-palindrome-ii.cpp b/CPP/Leetcode/680-valid-palindrome-ii/680-valid-palindrome-ii.cpp new file mode 100644 index 00000000..58a13bea --- /dev/null +++ b/CPP/Leetcode/680-valid-palindrome-ii/680-valid-palindrome-ii.cpp @@ -0,0 +1,39 @@ +class Solution { + private: + bool pal(string s,int l,int r) + { + while(l680. Valid Palindrome II

Easy


Given a string s, return true if the s can be palindrome after deleting at most one character from it.

+ +

 

+

Example 1:

+ +
Input: s = "aba"
+Output: true
+
+ +

Example 2:

+ +
Input: s = "abca"
+Output: true
+Explanation: You could delete the character 'c'.
+
+ +

Example 3:

+ +
Input: s = "abc"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/682-baseball-game/682-baseball-game.cpp b/CPP/Leetcode/682-baseball-game/682-baseball-game.cpp new file mode 100644 index 00000000..13e4e00b --- /dev/null +++ b/CPP/Leetcode/682-baseball-game/682-baseball-game.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int calPoints(vector& ops) { + vector v; + + for(int i=0;i682. Baseball Game

Easy


You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.

+ +

At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:

+ +
    +
  1. An integer x - Record a new score of x.
  2. +
  3. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
  4. +
  5. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
  6. +
  7. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
  8. +
+ +

Return the sum of all the scores on the record.

+ +

 

+

Example 1:

+ +
Input: ops = ["5","2","C","D","+"]
+Output: 30
+Explanation:
+"5" - Add 5 to the record, record is now [5].
+"2" - Add 2 to the record, record is now [5, 2].
+"C" - Invalidate and remove the previous score, record is now [5].
+"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
+"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
+The total sum is 5 + 10 + 15 = 30.
+
+ +

Example 2:

+ +
Input: ops = ["5","-2","4","C","D","9","+","+"]
+Output: 27
+Explanation:
+"5" - Add 5 to the record, record is now [5].
+"-2" - Add -2 to the record, record is now [5, -2].
+"4" - Add 4 to the record, record is now [5, -2, 4].
+"C" - Invalidate and remove the previous score, record is now [5, -2].
+"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
+"9" - Add 9 to the record, record is now [5, -2, -4, 9].
+"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
+"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
+The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
+
+ +

Example 3:

+ +
Input: ops = ["1"]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= ops.length <= 1000
  • +
  • ops[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104].
  • +
  • For operation "+", there will always be at least two previous scores on the record.
  • +
  • For operations "C" and "D", there will always be at least one previous score on the record.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/7-reverse-integer/7-reverse-integer.cpp b/CPP/Leetcode/7-reverse-integer/7-reverse-integer.cpp new file mode 100644 index 00000000..0e09e2cd --- /dev/null +++ b/CPP/Leetcode/7-reverse-integer/7-reverse-integer.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int reverse(int x) { + int cnt=0; + while(x!=0) + { + int d=x%10; + if(cnt>INT_MAX/10 || cnt& nums, int target) { + int n=nums.size(); + int l = 0, h = n-1; + int mid = 0; + + while(l <= h) + { + mid = l + (h-l)/2; + + if(nums[mid] == target) + return mid; + + else if(nums[mid] > target) + h = mid-1; + else l = mid + 1; + } + return -1; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/704-binary-search/NOTES.md b/CPP/Leetcode/704-binary-search/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/704-binary-search/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/804-unique-morse-code-words/804-unique-morse-code-words.cpp b/CPP/Leetcode/804-unique-morse-code-words/804-unique-morse-code-words.cpp new file mode 100644 index 00000000..6edb376f --- /dev/null +++ b/CPP/Leetcode/804-unique-morse-code-words/804-unique-morse-code-words.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int uniqueMorseRepresentations(vector& words) { + string s[26]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; + set s1; + for(int i=0;i804. Unique Morse Code Words

Easy


International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:

+ +
    +
  • 'a' maps to ".-",
  • +
  • 'b' maps to "-...",
  • +
  • 'c' maps to "-.-.", and so on.
  • +
+ +

For convenience, the full table for the 26 letters of the English alphabet is given below:

+ +
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
+ +

Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.

+ +
    +
  • For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.
  • +
+ +

Return the number of different transformations among all words we have.

+ +

 

+

Example 1:

+ +
Input: words = ["gin","zen","gig","msg"]
+Output: 2
+Explanation: The transformation of each word is:
+"gin" -> "--...-."
+"zen" -> "--...-."
+"gig" -> "--...--."
+"msg" -> "--...--."
+There are 2 different transformations: "--...-." and "--...--.".
+
+ +

Example 2:

+ +
Input: words = ["a"]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 12
  • +
  • words[i] consists of lowercase English letters.
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.cpp b/CPP/Leetcode/81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.cpp new file mode 100644 index 00000000..ba1d9c44 --- /dev/null +++ b/CPP/Leetcode/81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.cpp @@ -0,0 +1,14 @@ +#include +class Solution { +public: + bool search(vector& nums, int target) { + std::vector::iterator it; + it = std::find (nums.begin(), nums.end(), target); + if (it != nums.end()) + { + return true; + } + else return false; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/81-search-in-rotated-sorted-array-ii/README.md b/CPP/Leetcode/81-search-in-rotated-sorted-array-ii/README.md new file mode 100644 index 00000000..aa3c0b4b --- /dev/null +++ b/CPP/Leetcode/81-search-in-rotated-sorted-array-ii/README.md @@ -0,0 +1,29 @@ +

81. Search in Rotated Sorted Array II

Medium


There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

+ +

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].

+ +

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.

+ +

You must decrease the overall operation steps as much as possible.

+ +

 

+

Example 1:

+
Input: nums = [2,5,6,0,0,1,2], target = 0
+Output: true
+

Example 2:

+
Input: nums = [2,5,6,0,0,1,2], target = 3
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is guaranteed to be rotated at some pivot.
  • +
  • -104 <= target <= 104
  • +
+ +

 

+

Follow up: This problem is similar to Search in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?

+
\ No newline at end of file diff --git a/CPP/Leetcode/844-backspace-string-compare/844-backspace-string-compare.cpp b/CPP/Leetcode/844-backspace-string-compare/844-backspace-string-compare.cpp new file mode 100644 index 00000000..85512588 --- /dev/null +++ b/CPP/Leetcode/844-backspace-string-compare/844-backspace-string-compare.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + bool backspaceCompare(string s, string t) { + int n=s.length(); + int m=t.length(); + int cnt=0; + string a="",b=""; + for(int i=n-1;i>=0;i--) + { + if(s[i]=='#') cnt++; + else + { + if(cnt==0) + { + a=a+s[i]; + } + else cnt--; + } + } + cnt=0; + for(int i=m-1;i>=0;i--) + { + if(t[i]=='#') cnt++; + else + { + if(cnt==0) + { + b=b+t[i]; + } + else cnt--; + } + } + if(a==b) return true; + else return false; + + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/844-backspace-string-compare/NOTES.md b/CPP/Leetcode/844-backspace-string-compare/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/844-backspace-string-compare/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/844-backspace-string-compare/README.md b/CPP/Leetcode/844-backspace-string-compare/README.md new file mode 100644 index 00000000..60b4a9fb --- /dev/null +++ b/CPP/Leetcode/844-backspace-string-compare/README.md @@ -0,0 +1,37 @@ +

844. Backspace String Compare

Easy


Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

+ +

Note that after backspacing an empty text, the text will continue empty.

+ +

 

+

Example 1:

+ +
Input: s = "ab#c", t = "ad#c"
+Output: true
+Explanation: Both s and t become "ac".
+
+ +

Example 2:

+ +
Input: s = "ab##", t = "c#d#"
+Output: true
+Explanation: Both s and t become "".
+
+ +

Example 3:

+ +
Input: s = "a#c", t = "b"
+Output: false
+Explanation: s becomes "c" while t becomes "b".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 200
  • +
  • s and t only contain lowercase letters and '#' characters.
  • +
+ +

 

+

Follow up: Can you solve it in O(n) time and O(1) space?

+
\ No newline at end of file diff --git a/CPP/Leetcode/867-transpose-matrix/867-transpose-matrix.cpp b/CPP/Leetcode/867-transpose-matrix/867-transpose-matrix.cpp new file mode 100644 index 00000000..5a127a44 --- /dev/null +++ b/CPP/Leetcode/867-transpose-matrix/867-transpose-matrix.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector> transpose(vector>& matrix) { + int n = matrix.size(); + int m = matrix[0].size(); + + vector> res(m,vector (n,0)); + for(int i=0;i867. Transpose Matrix

Easy


Given a 2D integer array matrix, return the transpose of matrix.

+ +

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

+ +

+ +

 

+

Example 1:

+ +
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [[1,4,7],[2,5,8],[3,6,9]]
+
+ +

Example 2:

+ +
Input: matrix = [[1,2,3],[4,5,6]]
+Output: [[1,4],[2,5],[3,6]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 1000
  • +
  • 1 <= m * n <= 105
  • +
  • -109 <= matrix[i][j] <= 109
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp b/CPP/Leetcode/876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp new file mode 100644 index 00000000..bd72c6da --- /dev/null +++ b/CPP/Leetcode/876-middle-of-the-linked-list/876-middle-of-the-linked-list.cpp @@ -0,0 +1,24 @@ +/** + * 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* middleNode(ListNode* head) { + ListNode* p1=head; + ListNode* p2=head; + while(p2->next!=NULL && p2->next->next!=NULL) + { + p1=p1->next; + p2=p2->next->next; + } + if(p2->next!=NULL && p2->next->next==NULL) return p1->next; + else return p1; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/876-middle-of-the-linked-list/NOTES.md b/CPP/Leetcode/876-middle-of-the-linked-list/NOTES.md new file mode 100644 index 00000000..38c1374a --- /dev/null +++ b/CPP/Leetcode/876-middle-of-the-linked-list/NOTES.md @@ -0,0 +1 @@ +​ \ No newline at end of file diff --git a/CPP/Leetcode/876-middle-of-the-linked-list/README.md b/CPP/Leetcode/876-middle-of-the-linked-list/README.md new file mode 100644 index 00000000..264fadb1 --- /dev/null +++ b/CPP/Leetcode/876-middle-of-the-linked-list/README.md @@ -0,0 +1,27 @@ +

876. Middle of the Linked List

Easy


Given the head of a singly linked list, return the middle node of the linked list.

+ +

If there are two middle nodes, return the second middle node.

+ +

 

+

Example 1:

+ +
Input: head = [1,2,3,4,5]
+Output: [3,4,5]
+Explanation: The middle node of the list is node 3.
+
+ +

Example 2:

+ +
Input: head = [1,2,3,4,5,6]
+Output: [4,5,6]
+Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 100].
  • +
  • 1 <= Node.val <= 100
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/88-merge-sorted-array/88-merge-sorted-array.cpp b/CPP/Leetcode/88-merge-sorted-array/88-merge-sorted-array.cpp new file mode 100644 index 00000000..71e23611 --- /dev/null +++ b/CPP/Leetcode/88-merge-sorted-array/88-merge-sorted-array.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + vector v; + int i=0,j=0; + while(inums2[j]) + { + v.push_back(nums2[j]);j++; + } + else + { + v.push_back(nums1[i]);i++; + v.push_back(nums2[j]);j++; + } + } + while(i88. Merge Sorted Array

Easy


You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

+ +

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

+ +

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.

+ +

 

+

Example 1:

+ +
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
+Output: [1,2,2,3,5,6]
+Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
+The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
+
+ +

Example 2:

+ +
Input: nums1 = [1], m = 1, nums2 = [], n = 0
+Output: [1]
+Explanation: The arrays we are merging are [1] and [].
+The result of the merge is [1].
+
+ +

Example 3:

+ +
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
+Output: [1]
+Explanation: The arrays we are merging are [] and [1].
+The result of the merge is [1].
+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.
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m + n
  • +
  • nums2.length == n
  • +
  • 0 <= m, n <= 200
  • +
  • 1 <= m + n <= 200
  • +
  • -109 <= nums1[i], nums2[j] <= 109
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

+
\ No newline at end of file diff --git a/CPP/Leetcode/905-sort-array-by-parity/905-sort-array-by-parity.cpp b/CPP/Leetcode/905-sort-array-by-parity/905-sort-array-by-parity.cpp new file mode 100644 index 00000000..643410b1 --- /dev/null +++ b/CPP/Leetcode/905-sort-array-by-parity/905-sort-array-by-parity.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector sortArrayByParity(vector& nums) { + vector odd; + vector even; + for(auto it:nums) + { + if(it%2==0) even.push_back(it); + else odd.push_back(it); + } + vector v; + for(auto it:even) + { + v.push_back(it); + } + for(auto it:odd) + { + v.push_back(it); + } + return v; + + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/905-sort-array-by-parity/README.md b/CPP/Leetcode/905-sort-array-by-parity/README.md new file mode 100644 index 00000000..74448b33 --- /dev/null +++ b/CPP/Leetcode/905-sort-array-by-parity/README.md @@ -0,0 +1,26 @@ +

905. Sort Array By Parity

Easy


Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

+ +

Return any array that satisfies this condition.

+ +

 

+

Example 1:

+ +
Input: nums = [3,1,2,4]
+Output: [2,4,3,1]
+Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
+
+ +

Example 2:

+ +
Input: nums = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • 0 <= nums[i] <= 5000
  • +
+
\ No newline at end of file diff --git a/CPP/Leetcode/94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.cpp b/CPP/Leetcode/94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.cpp new file mode 100644 index 00000000..985afd7f --- /dev/null +++ b/CPP/Leetcode/94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.cpp @@ -0,0 +1,27 @@ +/** + * 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 { + private: + void printer(TreeNode* root){ + if(root==NULL) {return;} + printer(root->left); + v.push_back(root->val); + printer(root->right); + } + +public: + vector v; + vector inorderTraversal(TreeNode* root) { + printer(root); + return v; + } +}; \ No newline at end of file diff --git a/CPP/Leetcode/94-binary-tree-inorder-traversal/README.md b/CPP/Leetcode/94-binary-tree-inorder-traversal/README.md new file mode 100644 index 00000000..e6ca03ee --- /dev/null +++ b/CPP/Leetcode/94-binary-tree-inorder-traversal/README.md @@ -0,0 +1,31 @@ +

94. Binary Tree Inorder Traversal

Easy


Given the root of a binary tree, return the inorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
Input: root = [1,null,2,3]
+Output: [1,3,2]
+
+ +

Example 2:

+ +
Input: root = []
+Output: []
+
+ +

Example 3:

+ +
Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Recursive solution is trivial, could you do it iteratively?
\ No newline at end of file diff --git a/CPP/Leetcode/Matrix Exponentiation - GFG/README.md b/CPP/Leetcode/Matrix Exponentiation - GFG/README.md new file mode 100644 index 00000000..2a742f8e --- /dev/null +++ b/CPP/Leetcode/Matrix Exponentiation - GFG/README.md @@ -0,0 +1,35 @@ +# Matrix Exponentiation +## Medium +
+

Given an equation of the form f(n) = f(n-1) + f(n-2) where f(0) = 1, F(1) = 1 , the task is to find the nth term of this sequence.

+ +

Example 1:

+ +
Input: n = 3
+Output: 3
+Explanation: f(3) = f(2) + f(1) = 3
+
+
+ +

Example 2:

+ +
Input: n = 2
+Output: 2
+Explanation: f(2) = f(1) + f(0) = 2
+
+ +

 

+ +

Yout Task:
+You don't need to read or print anything. Your task is to complete the function FindNthTerm() which takes n as input parameter and returns nth term mod 10^9+7 .

+ +


+Expected Time Compelxity: O(log(n))
+Expected Space Complexity: O(K) where K is constant.

+ +

Constraints:
+1 <= n <= 109

+

+
\ No newline at end of file diff --git a/CPP/Leetcode/Matrix Exponentiation - GFG/matrix-exponentiation.cpp b/CPP/Leetcode/Matrix Exponentiation - GFG/matrix-exponentiation.cpp new file mode 100644 index 00000000..8dbe2b9a --- /dev/null +++ b/CPP/Leetcode/Matrix Exponentiation - GFG/matrix-exponentiation.cpp @@ -0,0 +1,48 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution { + + + private: int M = 1000000007; + vector> multi(vector> &a, vector> &b) { + vector> c = {{0,0},{0,0}}; + for(int i = 0; i < 2; i++) { + for(int j = 0; j < 2; j++) { + for(int k = 0; k < 2; k++) { + c[i][j] += ((a[i][k]%M)*(b[k][j]%M))%M; + } + } + } + return c; + } + + public : int FindNthTerm(long long int n) { + vector> mat = {{1,1},{1,0}}; + vector> res = {{1,1},{1,0}}; + + while(n) { + if(n%2 == 1) + res = multi(mat,res); + + mat = multi(mat,mat); + n = n>>1; + } + return res[0][1]%M; + } +}; +// { Driver Code Starts. +int main(){ + int tc; + cin >> tc; + while(tc--){ + long long int n; + cin >> n; + Solution obj; + int ans = obj.FindNthTerm(n); + cout << ans << "\n"; + } + return 0; +} // } Driver Code Ends \ No newline at end of file diff --git a/CPP/Leetcode/README.md b/CPP/Leetcode/README.md new file mode 100644 index 00000000..e2674cd8 --- /dev/null +++ b/CPP/Leetcode/README.md @@ -0,0 +1,2 @@ +# LeetCode-CPP +Collection of LeetCode questions to ace the coding interview! - Created using [LeetHub](https://github.com/QasimWani/LeetHub) diff --git a/CPP/LinkedList/all_singly_linkedlist.py b/CPP/LinkedList/all_singly_linkedlist.py new file mode 100644 index 00000000..3d469e60 --- /dev/null +++ b/CPP/LinkedList/all_singly_linkedlist.py @@ -0,0 +1,130 @@ +class Node: + def __init__(self,data): + self.data = data # here nodes data is data + self.ref = None # it stores the refrence of none or NULL + +# now to link this individual node +class LinkedList: + def __init__(self): + self.head = None #this is the empty linked list (initializing linked list) + + # traversing the LL + def print_LL(self): + if self.head==None: + print("Linked list is empty") + else: + n = self.head + while n!=None: + print(n.data , end=" ") + n = n.ref + + # adding new node at beginning of LL + def add_beginning(self,data): + new_node = Node(data) # creating a new node from node class ## here a node will be created having some data(i.e. the data field) and link field is Null + new_node.ref = self.head + self.head = new_node + + # add at the end + def add_end(self,data): + new_node = Node(data) + if self.head == None : + self.head = new_node + else: + n = self.head + while n.ref!=None: # we are using this while loop to go to the last node + n = n.ref + n.ref = new_node + + # adding after a given node + def add_after(self,data,x): + n = self.head + while n!=None: + if x==n.data: + break + n = n.ref + if n==None: + print("Node is not present in Linked List") + else: + new_node = Node(data) + new_node.ref = n.ref + n.ref = new_node + + #adding before given node + def add_before(self,data,x): + # if linked list is empty + if self.head==None: + print("LL is empty") + return + # if x is first node + if self.head.data==x: + new_node = Node(data) + new_node.ref = self.head + self.head = new_node + return + # rest cases + n = self.head + while n.ref!=None: + if n.ref.data==x: + break + n = n.ref + if(n.ref==None): + print("x is not in LL") + new_node = Node(data) + new_node.ref = n.ref + n.ref = new_node + + # inserting element in empty LL + def insert_when_empty(self,data): + if self.head==None: + new_node = Node(data) + self.head=new_node + else: + print("LL is not empty") + + # deletion at the beginning + def delete_beginning(self): + if self.head!=None: + self.head = self.head.ref + else: + print("LL is empty, we cannot delete first node") + + # deletion at the end + def delete_end(self): + if self.head==None: + print("LL is empty, we cannot delete last node") + elif self.head.ref==None: # when only 1 node is present + self.head = None + elif self.head!=None: + n = self.head + while n!=None: # or directly we can take while n.ref.ref!=None: + if n.ref.ref == None: # n = n.ref + break + n = n.ref + n.ref = None + + # deletion of given value + def delete_given(self,x): + if self.head==None: + print("LL is empty, we cannot delete given node") + elif x==self.head.data: + self.head = self.head.ref + elif self.head!=None: + n = self.head + while n.ref!=None: # here we took n.ref because when we reach the last node (jab hum n!=none lete) there n is not equal to none toh jab hum if condition ke n.ref.data ko check karenge toh waha n.ref is none toh none.data is not defined. issliye hum last node pe hi loop break kr rahe. + if n.ref.data==x: + break + n = n.ref + if n.ref==None: + print("Given node is not present in LL") + else: + n.ref = n.ref.ref + +LL1 = LinkedList() +LL1.add_beginning(3) +LL1.add_beginning(24) +LL1.add_end(52) +LL1.add_beginning(66) +LL1.add_end(43) +LL1.delete_given(20) +LL1.delete_given(52) +LL1.print_LL() \ No newline at end of file diff --git a/Maths/ArrayStabilization.cpp b/CPP/Maths/ArrayStabilization.cpp similarity index 100% rename from Maths/ArrayStabilization.cpp rename to CPP/Maths/ArrayStabilization.cpp diff --git a/Maths/CountDigit.cpp b/CPP/Maths/CountDigit.cpp similarity index 100% rename from Maths/CountDigit.cpp rename to CPP/Maths/CountDigit.cpp diff --git a/Maths/EvenArray.cpp b/CPP/Maths/EvenArray.cpp similarity index 100% rename from Maths/EvenArray.cpp rename to CPP/Maths/EvenArray.cpp diff --git a/Maths/EvenOdds.cpp b/CPP/Maths/EvenOdds.cpp similarity index 100% rename from Maths/EvenOdds.cpp rename to CPP/Maths/EvenOdds.cpp diff --git a/Maths/ModularExponentiation.cpp b/CPP/Maths/ModularExponentiation.cpp similarity index 100% rename from Maths/ModularExponentiation.cpp rename to CPP/Maths/ModularExponentiation.cpp diff --git a/Maths/RequiredRemainder.cpp b/CPP/Maths/RequiredRemainder.cpp similarity index 100% rename from Maths/RequiredRemainder.cpp rename to CPP/Maths/RequiredRemainder.cpp diff --git a/Maths/highest.cpp b/CPP/Maths/highest.cpp similarity index 100% rename from Maths/highest.cpp rename to CPP/Maths/highest.cpp diff --git a/Maths/nextSimilar.cpp b/CPP/Maths/nextSimilar.cpp similarity index 100% rename from Maths/nextSimilar.cpp rename to CPP/Maths/nextSimilar.cpp diff --git a/Maths/nge1_496.cpp b/CPP/Maths/nge1_496.cpp similarity index 96% rename from Maths/nge1_496.cpp rename to CPP/Maths/nge1_496.cpp index 601f123c..b43787f2 100644 --- a/Maths/nge1_496.cpp +++ b/CPP/Maths/nge1_496.cpp @@ -1,25 +1,25 @@ -class Solution { -public: - vector nextGreaterElement(vector& nums1, vector& nums2) { - int n = nums1.size(), m = nums2.size(); - vector res(n, -1); - stack st; - unordered_map mp; - for(int i = 0; i < m; i++){ - int val = nums2[i]; - while(!st.empty() and val > st.top()){ - mp[st.top()] = val; - st.pop(); - } - st.push(val); - } - for(int i = 0; i < n; i++){ - int val = nums1[i]; - if(mp.find(val) != mp.end()){ - int nge = mp[val]; - res[i] = nge; - } - } - return res; - } +class Solution { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + int n = nums1.size(), m = nums2.size(); + vector res(n, -1); + stack st; + unordered_map mp; + for(int i = 0; i < m; i++){ + int val = nums2[i]; + while(!st.empty() and val > st.top()){ + mp[st.top()] = val; + st.pop(); + } + st.push(val); + } + for(int i = 0; i < n; i++){ + int val = nums1[i]; + if(mp.find(val) != mp.end()){ + int nge = mp[val]; + res[i] = nge; + } + } + return res; + } }; \ No newline at end of file diff --git a/Maths/nge2_503.cpp b/CPP/Maths/nge2_503.cpp similarity index 96% rename from Maths/nge2_503.cpp rename to CPP/Maths/nge2_503.cpp index 1b9f180d..ed98961a 100644 --- a/Maths/nge2_503.cpp +++ b/CPP/Maths/nge2_503.cpp @@ -1,19 +1,19 @@ -class Solution { -public: - vector nextGreaterElements(vector& nums) { - int n = nums.size(); - vector res(n, -1); - stack st; - for(int i = 2*n-1; i > -1; i--){ - while(!st.empty() and nums[i%n] >= st.top()){ - st.pop(); - } - if(i < n){ - if(!st.empty()) - res[i] = st.top(); - } - st.push(nums[i%n]); - } - return res; - } +class Solution { +public: + vector nextGreaterElements(vector& nums) { + int n = nums.size(); + vector res(n, -1); + stack st; + for(int i = 2*n-1; i > -1; i--){ + while(!st.empty() and nums[i%n] >= st.top()){ + st.pop(); + } + if(i < n){ + if(!st.empty()) + res[i] = st.top(); + } + st.push(nums[i%n]); + } + return res; + } }; \ No newline at end of file diff --git a/Maths/nge3_556.cpp b/CPP/Maths/nge3_556.cpp similarity index 96% rename from Maths/nge3_556.cpp rename to CPP/Maths/nge3_556.cpp index a46ccc01..732e2a08 100644 --- a/Maths/nge3_556.cpp +++ b/CPP/Maths/nge3_556.cpp @@ -1,20 +1,20 @@ -class Solution { -public: - int nextGreaterElement(int num) { - vector v; - while(num){ - v.push_back(num%10); - num /= 10; - } - if(is_sorted(v.begin(), v.end())) - return -1; - reverse(v.begin(), v.end()); - next_permutation(v.begin(), v.end()); - long long temp = 0; - for(int i = 0; i < v.size(); i++){ - temp = temp*10 + v[i]; - } - if(temp > INT_MAX) return -1; - return temp; - } +class Solution { +public: + int nextGreaterElement(int num) { + vector v; + while(num){ + v.push_back(num%10); + num /= 10; + } + if(is_sorted(v.begin(), v.end())) + return -1; + reverse(v.begin(), v.end()); + next_permutation(v.begin(), v.end()); + long long temp = 0; + for(int i = 0; i < v.size(); i++){ + temp = temp*10 + v[i]; + } + if(temp > INT_MAX) return -1; + return temp; + } }; \ No newline at end of file diff --git a/Maths/power.cpp b/CPP/Maths/power.cpp similarity index 100% rename from Maths/power.cpp rename to CPP/Maths/power.cpp diff --git a/Maths/powerIterative.cpp b/CPP/Maths/powerIterative.cpp similarity index 100% rename from Maths/powerIterative.cpp rename to CPP/Maths/powerIterative.cpp diff --git a/Maths/primeFactor.cpp b/CPP/Maths/primeFactor.cpp similarity index 100% rename from Maths/primeFactor.cpp rename to CPP/Maths/primeFactor.cpp diff --git a/Maths/primeNo.cpp b/CPP/Maths/primeNo.cpp similarity index 100% rename from Maths/primeNo.cpp rename to CPP/Maths/primeNo.cpp diff --git a/Maths/reordered_power_of_2_869.cpp b/CPP/Maths/reordered_power_of_2_869.cpp similarity index 96% rename from Maths/reordered_power_of_2_869.cpp rename to CPP/Maths/reordered_power_of_2_869.cpp index 2c441144..4b0076ea 100644 --- a/Maths/reordered_power_of_2_869.cpp +++ b/CPP/Maths/reordered_power_of_2_869.cpp @@ -1,17 +1,17 @@ -class Solution { -public: - bool reorderedPowerOf2(int n) { - map mp; - mp["1"]++; - int num = 1; - while(mp.size() != 30){ - num *= 2; - string s = to_string(num); - sort(s.begin(), s.end()); - mp[s]++; - } - string s = to_string(n); - sort(s.begin(), s.end()); - return (mp.find(s) != mp.end()); - } +class Solution { +public: + bool reorderedPowerOf2(int n) { + map mp; + mp["1"]++; + int num = 1; + while(mp.size() != 30){ + num *= 2; + string s = to_string(num); + sort(s.begin(), s.end()); + mp[s]++; + } + string s = to_string(n); + sort(s.begin(), s.end()); + return (mp.find(s) != mp.end()); + } }; \ No newline at end of file diff --git a/Maths/reverseInteger.cpp b/CPP/Maths/reverseInteger.cpp similarity index 100% rename from Maths/reverseInteger.cpp rename to CPP/Maths/reverseInteger.cpp diff --git a/Maths/seiveOfEratothenes.cpp b/CPP/Maths/seiveOfEratothenes.cpp similarity index 100% rename from Maths/seiveOfEratothenes.cpp rename to CPP/Maths/seiveOfEratothenes.cpp diff --git a/Maths/trailingZeroInFactorial.cpp b/CPP/Maths/trailingZeroInFactorial.cpp similarity index 100% rename from Maths/trailingZeroInFactorial.cpp rename to CPP/Maths/trailingZeroInFactorial.cpp diff --git a/Maths/xor_sum_of_all_pairs_and_1835.cpp b/CPP/Maths/xor_sum_of_all_pairs_and_1835.cpp similarity index 95% rename from Maths/xor_sum_of_all_pairs_and_1835.cpp rename to CPP/Maths/xor_sum_of_all_pairs_and_1835.cpp index ae8f414f..a3213d3b 100644 --- a/Maths/xor_sum_of_all_pairs_and_1835.cpp +++ b/CPP/Maths/xor_sum_of_all_pairs_and_1835.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int getXORSum(vector& arr1, vector& arr2) { - int a = 0, b = 0; - for(auto i : arr1) - a = a ^ i; - for(auto j : arr2) - b = b ^ j; - return a & b; - } +class Solution { +public: + int getXORSum(vector& arr1, vector& arr2) { + int a = 0, b = 0; + for(auto i : arr1) + a = a ^ i; + for(auto j : arr2) + b = b ^ j; + return a & b; + } }; \ No newline at end of file diff --git a/CPP/OptimizedExponentOfTwoCheck.cpp b/CPP/OptimizedExponentOfTwoCheck.cpp new file mode 100644 index 00000000..e2a5abec --- /dev/null +++ b/CPP/OptimizedExponentOfTwoCheck.cpp @@ -0,0 +1,13 @@ +#include +using namespace std; + +bool isAnExponentOfTwo(int n) { + return ((n & (n-1)) == 0); +} + +int main() { + int n; + cin >> n; + cout << (isAnExponentOfTwo(n) ? "YES" : "NO") << endl; + return 0; +} \ No newline at end of file diff --git a/CPP/Problems/1_INDIAN_COIN_CHANGE_PROBLEM.CPP b/CPP/Problems/1_INDIAN_COIN_CHANGE_PROBLEM.CPP new file mode 100644 index 00000000..eed528eb --- /dev/null +++ b/CPP/Problems/1_INDIAN_COIN_CHANGE_PROBLEM.CPP @@ -0,0 +1,33 @@ +// INDIAN COIN CHANGE PROBLEM +// FROM AN ARRAY OF DENOMINATION AND FOR VALUE X , FIND MININUM NUMBER OF COINS TO MAKE VALUE X + +#include +#include +#include +using namespace std; + +int main() +{ + int n,x; + cin>>n>>x; + + + vector v(n); + + for(int i=0;i>v[i]; + } + + sort(v.begin(),v.end(),greater()); + int coin=0; + + for(int i=0;i +#include +#include +using namespace std; + +// bool compare(pair p1,pair p2) +// { +// return p1.second>n; + +// vector> v; + +// for(int i=0;i>start>>end; + +// v.push_back(make_pair(start,end)); + +// } + +// sort(v.begin(),v.end(),compare); + +// int task=1; +// int new_end=v[0].second; + +// for(int i=1;i=new_end) +// { +// task++; +// new_end=v[i].second; +// } +// } + +// cout< &a,vector &b) + { + return a[1]>n; + + vector> v; + + for(int i=0;i>start>>end; + + v.push_back({start,end}); + + } + + // sort(v.begin(),v.end(),[&](vector &a,vector &b) + // { + // return a[1]=new_end) + { + task++; + new_end=v[i][1]; + } + } + + cout< +#include +#include +using namespace std; + +bool compare(pair p1,pair p2) +{ + return ((double)p1.first/p1.second)>((double)p2.first/p2.second); +} + +int main() +{ + int n; + cin>>n; + + vector> v(n); + + for(int i=0;i>v[i].first>>v[i].second; + } + + int w; + cin>>w; + + sort(v.begin(),v.end(),compare); + + int ans=0; + + for(int i=0;i=v[i].second) + { + ans+=v[i].first; + w-=v[i].second; + } + else + { + double vw=((double)v[i].first/v[i].second); + ans+= vw*w; + w=0; + break; + } + } + + cout< +#include +#include +using namespace std; + + +int main() +{ + + int n; + cin>>n; + + vector v(n); + + for(int i=0;i>v[i]; + } + + + + priority_queue,greater> pq(v.begin(),v.end()); + + int ans=0; + + while(pq.size()>1) + { + int a=pq.top(); + pq.pop(); + int b=pq.top(); + pq.pop(); + + int new_time=(a+b); + ans+=new_time; + pq.push(new_time); + } + + cout< +using namespace std; +unordered_map umap; +long long coin(int n){ + if (!n) return 0; + if (umap[n]) return umap[n]; + long long sum = coin(n/2)+coin(n/3)+coin(n/4); + if (n>sum) umap[n]=n; + else umap[n] = sum; + return umap[n]; +} +int main() { + while (true){ + int n=-1; + cin>>n; + if (n==-1) break; + long long ans = coin(n); + cout<& arr) { + vector> ans; + unordered_map m; + for(auto x:arr) + m[x]++; + for(auto x:m) + ans.push_back({x.second,x.first}); + sort(ans.begin(),ans.end(),greater>()); + int fans=0,temp=0,n=arr.size()/2; + for(int i=0;i=n) + return fans; + } + return 0; + } +}; diff --git a/CPP/Problems/Leetcode 15-3SumProblem.cpp b/CPP/Problems/Leetcode 15-3SumProblem.cpp new file mode 100644 index 00000000..41b46a51 --- /dev/null +++ b/CPP/Problems/Leetcode 15-3SumProblem.cpp @@ -0,0 +1,45 @@ +// Problem link:https://leetcode.com/problems/3sum/description/ + +class Solution { +public: + vector> threeSum(vector& nums) { + sort(nums.begin(),nums.end()); + int n=nums.size(); + vector> ans; + set> st; + for(int i=0;i check; + int find=-(nums[i]); + int l=i+1,r=n-1; + while(r>l){ + int sum=(nums[l]+nums[r]); + if(sum==find){ + check.push_back(nums[i]); + check.push_back(nums[l]); + check.push_back(nums[r]); + st.insert(check); + if(check.size()==3){ + check.clear(); + } + l++;r--; + } + else if(sum>find){ + r--; + } + else{ + l++; + } + } + } + + for(auto el:st){ + vector check1; + for(int i=0;i& nums, int goal) { - unordered_map m; - m[0]=1; - int ans=0,s=0; - for(auto x:nums) - { - s+=x; - if(m.find(s-goal)!=m.end()) - ans+=m[s-goal]; - m[s]++; - } - return ans; - } -}; \ No newline at end of file +class Solution { +public: + int numSubarraysWithSum(vector& nums, int goal) { + unordered_map m; + m[0]=1; + int ans=0,s=0; + for(auto x:nums) + { + s+=x; + if(m.find(s-goal)!=m.end()) + ans+=m[s-goal]; + m[s]++; + } + return ans; + } +}; diff --git a/CPP/Problems/Leetcode-1254-NumberOfClosedIslands.cpp b/CPP/Problems/Leetcode-1254-NumberOfClosedIslands.cpp new file mode 100644 index 00000000..322e7c4c --- /dev/null +++ b/CPP/Problems/Leetcode-1254-NumberOfClosedIslands.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +//https://leetcode.com/problems/number-of-closed-islands/ + +class Solution { +public: + void dfs(int i, int j, vector> &grid, int n, int m) { + if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 1) { + return; + } + + grid[i][j] = 1; + dfs(i + 1, j, grid, n, m); + dfs(i, j + 1, grid, n, m); + dfs(i - 1, j, grid, n, m); + dfs(i, j - 1, grid, n, m); + } + + int closedIsland(vector>& grid) { + int n = grid.size(), m = grid[0].size(); + + for(int i = 0; i < n; i++) { + dfs(i, 0, grid, n, m); + dfs(i, m - 1, grid, n, m); + } + for(int j = 0; j < m; j++) { + dfs(0, j, grid, n, m); + dfs(n - 1, j, grid, n, m); + } + + int count = 0; + for(int i = 0; i < n; i++) { + for(int j = 0; j < m; j++) { + if(grid[i][j] == 0) { + count++; + dfs(i, j, grid, n, m); + } + } + } + + return count; + } +}; \ No newline at end of file diff --git a/CPP/Problems/Leetcode-42-Trapping-Rain-Water.cpp b/CPP/Problems/Leetcode-42-Trapping-Rain-Water.cpp new file mode 100644 index 00000000..c923c88b --- /dev/null +++ b/CPP/Problems/Leetcode-42-Trapping-Rain-Water.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int trap(vector& height) { + int n=height.size(); + vectorml(n,-1),mr(n,-1); + for(int i=n-2;i>=0;i--) + { + int x=max(mr[i+1],height[i+1]); + if(x>height[i]) + mr[i]=x; + } + for(int i=1;iheight[i]) + ml[i]=x; + } + + int ans=0; + for(int i=0;i +using namespace std; + +//https://leetcode.com/problems/flood-fill/ + +class Solution { +public: + void dfs(int sr, int sc, int initColor, int newColor, vector>& grid, + vector>& image, int deltaRow[], int deltaCol[]) + { + grid[sr][sc] = newColor; + int n = grid.size(); + int m = grid[0].size(); + + for(int i = 0; i < 4; i++) { + int newRow = sr + deltaRow[i]; + int newCol = sc + deltaCol[i]; + //check if color is same as initial color and not already changed + if(newRow >= 0 && newRow < n && newCol >= 0 && newCol < m + && image[newRow][newCol] == initColor && grid[newRow][newCol] != newColor) { + dfs(newRow, newCol, initColor, newColor, grid, image, deltaRow, deltaCol); + } + } + } + + vector> floodFill(vector>& image, int sr, int sc, int newColor) { + int initColor = image[sr][sc]; + vector> grid = image; + + //up, right, down, left + int deltaRow[] = {-1, 0, +1, 0}; + int deltaCol[] = {0, +1, 0, -1}; + + dfs(sr, sc, initColor, newColor, grid, image, deltaRow, deltaCol); + + return grid; + } +}; \ No newline at end of file diff --git a/CPP/QUEUE/QueueUsingStack.cpp b/CPP/QUEUE/QueueUsingStack.cpp new file mode 100644 index 00000000..3b708011 --- /dev/null +++ b/CPP/QUEUE/QueueUsingStack.cpp @@ -0,0 +1,61 @@ + +#include +using namespace std; +struct Queue{ + stack s1,s2; + + + void enqueue(int x){ + + s1.push(x); + + } + int dequeue(){ + while(!s1.empty()){ + s2.push(s1.top()); + s1.pop(); + } + int ans=s2.top(); + s2.pop(); + while(!s2.empty()){ + s1.push(s2.top()); + s2.pop(); + + } + return ans; + + } + + +}; +int main(){ + Queue q; + int ch; + int x; + cout<<"Press 0 to exit else enter 1: "; + cin>>ch; + while(ch!=0) + { + cout<<"\n"<<"1.ENQUEUE"<<"\n"<<"2.DEQUQUE"<<"\n"; + cout<<"\n"<<"Enter choice :"; + cin>>ch; + switch (ch) + { + case 1: + cout<<"Enter the value you want to enqueue: "; + cin>>x; + q.enqueue(x); + break; + case 2: + cout<<"Dequeued element is : "< +using namespace std; +//common file for PBDS +#include +//including tree_order_statistics_node_update +#include +using namespace __gnu_pbds; +//macro definition +template +using ordered_set= tree, rb_tree_tag, tree_order_statistics_node_update>; +template +using o_multiset = tree, rb_tree_tag, tree_order_statistics_node_update>; +//member functions : +//1. order_of_key(k) : number of elements strictly lesser than k +//2. find_by_order(k) : k-th element in the set + +//Optimisations (Black Magic 🌑) +#pragma GCC optimize("O3,unroll-loops") +#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") + +#define ll long long +#define lld long double +#define ull unsigned long long +#define rep(i, n) for (ll i = 0; i < n; i++) +#define repk(i, k, n) for (ll i = k; k < n ? i < n : i > n; k < n ? i++ : i--) +#define input(vec) for (auto &el : vec) cin >> el; +#define print(vec) for (auto &el : vec) cout << el<<" "; +#define bit(x) __builtin_popcount(x) +#define bitll(x) __builtin_popcountll(x) +#define popb pop_back +#define pb push_back +#define eb emplace_back +#define ub upper_bound +#define lb lower_bound +#define ff first +#define ss second +#define um unordered_map +#define om ordered_map +#define all(x) (x).begin(),(x).end() +#define minpq priority_queue>pq; +#define maxpq priority_queuepq; +#define uniq(x) (x).erase(unique(all(x)), (x).end()) +#define precision(x, y) fixed << setprecision(y) << x +#define PI 3.1415926535897932384626 +#define sz(x) ((ll)(x).size()) +#define r_search(a,b) regex_search(a,regex(b)) //search b in a +#define r_match(a,b) regex_match(a,regex(b)) //match b in a +#define r_replace(a,b,c) regex_replace(a,regex(b),c) //replace b with c in a +#define present(b, a) ((a).find((b)) != (a).end()) //if b is present in a +#define nl '\n' +const ll mod = 1e9 + 7; //1000000007 +const ll mod2 = 998244353; +const ll inf = LLONG_MAX; +const lld epsilon = 1e-12; +typedef pair pl; +typedef pair pc; +typedef pair pi; +typedef pair pd; +typedef vector vl; +typedef vector vc; +typedef vector vpl; +typedef vector vvl; +typedef vector vi; +typedef vector vpc; +typedef vector vpi; +typedef vector vvi; +typedef vector vs; +typedef vector> vvs; + +// #ifndef ONLINE_JUDGE +#define debug(x) cerr << #x <<" "; _print(x); cerr << endl; +// #else +// #define debug(x) +// #endif + +void _print(ll t) {cerr << t;} +void _print(int t) {cerr << t;} +void _print(string t) {cerr << t;} +void _print(char t) {cerr << t;} +void _print(lld t) {cerr << t;} +void _print(double t) {cerr << t;} +void _print(ull t) {cerr << t;} + +template void _print(pair p); +template void _print(vector v); +template void _print(set v); +template void _print(map v); +template void _print(multiset v); +template void _print(pair p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";} +template void _print(vector v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} +template void _print(set v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} +template void _print(multiset v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";} +template void _print(map v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} +template void _print(unordered_map v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";} + +// ------------------------Do not write above this line----------------------------------------------------------------------------------------------------------------- +//Segment-Tree (Sum-Update, Sum-Query) +//1-based indexing +//pass the vectors as reference +void build_segtree(vl &vec,ll curr,ll l,ll r,vl &segtree){ + if(l==r){ + segtree[curr]=vec[l]; + } + else{ + int mid=(l+r)/2; + build_segtree(vec,2*curr,l,mid,segtree); + build_segtree(vec,2*curr+1,mid+1,r,segtree); + segtree[curr]=segtree[2*curr]+segtree[2*curr+1]; + } +} + +ll sum_segtree(ll curr,ll curr_l,ll curr_r,ll l,ll r,vl &segtree){ + if(l>r){ + return 0; + } + + if(l==curr_l and r==curr_r){ + return segtree[curr]; + } + + ll mid=(curr_l+curr_r)/2; + return sum_segtree(2*curr,curr_l,mid,l,min(r,mid),segtree)+sum_segtree(2*curr+1,mid+1,curr_r,max(l,mid+1),r,segtree); +} + +void update_segtree(ll curr,ll l,ll r,ll pos,ll new_val,vl &segtree){ + if(l==r){ + segtree[curr]=new_val; + } + else{ + ll mid=(l+r)/2; + if(pos<=mid){ + update_segtree(2*curr,l,mid,pos,new_val,segtree); + } + else{ + update_segtree(2*curr+1,mid+1,r,pos,new_val,segtree); + } + segtree[curr]=segtree[2*curr]+segtree[2*curr+1]; + } +} + +void solve(){ + ll n; + cin>>n; + vl vec(n); + input(vec); + + vl segtree(4*n+1); + //TreeBuild + build_segtree(vec,1,0,n-1,segtree); //(input array,curr. vertex,start,end,segtree array,size) + + //Sum-query + cout<>t; + while(t--){ + solve(); + } + return 0; +} diff --git a/CPP/Segment Tree/lazy_queries_segment_tree.cpp b/CPP/Segment Tree/lazy_queries_segment_tree.cpp new file mode 100644 index 00000000..62d40077 --- /dev/null +++ b/CPP/Segment Tree/lazy_queries_segment_tree.cpp @@ -0,0 +1,166 @@ +#include + +using namespace std; +typedef long long int ll; +typedef long double ld; +typedef pair < ll, ll > iii; +const ll mod = 1e9 + 7; + +ll n, q; +struct node { + ll x; + ll ad; + ll lazy; + node() { + x = 0; + ad = 0; + lazy = 0; + } +}; +vector < ll > v; +vector < node > g; + +inline node merge(node a, node b) { + node temp; + temp.x = a.x + b.x; + temp.ad = 0; + temp.lazy = 0; + return (temp); +} + +inline void build(ll index, ll l, ll r) { + if (l == r) { + g[index].ad = 0; + g[index].lazy = 0; + g[index].x = v[l]; + return; + } + + ll mid; + mid = (l + r) / 2; + build(2 * index, l, mid); + build(2 * index + 1, mid + 1, r); + g[index] = merge(g[2 * index], g[2 * index + 1]); + +} + +inline void push(ll index, ll l, ll r) { + if (g[index].lazy > 0) { + g[index].x = (r + 1 - l) * g[index].lazy; + g[2 * index].lazy = g[index].lazy; + g[2 * index + 1].lazy = g[index].lazy; + g[2 * index].ad = 0; + g[2 * index + 1].ad = 0; + g[index].lazy = 0; + + } + + if (g[index].ad > 0) { + g[index].x = g[index].x + (r + 1 - l) * g[index].ad; + g[2 * index].ad += g[index].ad; + g[2 * index + 1].ad += g[index].ad; + //g[2*index].lazy=0; + //g[2*index+1].lazy=0; + g[index].ad = 0; + } + + return; +} + +inline ll findsum(ll index, ll l, ll r, ll lq, ll rq) { + push(index, l, r); + if (l > rq || r < lq) + return 0; + + if (l >= lq && r <= rq) + return (g[index].x); + + ll mid; + mid = (l + r) / 2; + + return (findsum(2 * index, l, mid, lq, rq) + findsum(2 * index + 1, mid + 1, r, lq, rq)); + +} + +inline void update2(ll index, ll l, ll r, ll lq, ll rq, ll x) { + push(index, l, r); + + if (l > rq || r < lq) + return; + + if (l >= lq && r <= rq) { + g[index].lazy = x; + push(index, l, r); + return; + } + + ll mid; + mid = (l + r) / 2; + update2(2 * index, l, mid, lq, rq, x); + update2(2 * index + 1, mid + 1, r, lq, rq, x); + g[index] = merge(g[2 * index], g[2 * index + 1]); + +} + +inline void update1(ll index, ll l, ll r, ll lq, ll rq, ll x) { + push(index, l, r); + + if (l > rq || r < lq) + return; + + if (l >= lq && r <= rq) { + g[index].ad += x; + push(index, l, r); + return; + } + + ll mid; + mid = (l + r) / 2; + update1(2 * index, l, mid, lq, rq, x); + update1(2 * index + 1, mid + 1, r, lq, rq, x); + g[index] = merge(g[2 * index], g[2 * index + 1]); + +} + +int main() { + + ios_base::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + + cin >> n >> q; + + v.resize(n + 1); + g.resize(8 * n + 4); + + ll i; + for (i = 1; i <= n; i++) + cin >> v[i]; + + build(1, 1, n); + + while (q--) { + ll t, a, b, x; + cin >> t; + if (t == 1) { + cin >> a >> b >> x; + + update1(1, 1, n, a, b, x); + + } + if (t == 2) { + cin >> a >> b >> x; + + update2(1, 1, n, a, b, x); + + } + + if (t == 3) { + cin >> a >> b; + cout << findsum(1, 1, n, a, b) << endl; + + } + } + + return 0; +} diff --git a/CPP/Shortest commont supersequence b/CPP/Shortest commont supersequence new file mode 100644 index 00000000..fafea811 --- /dev/null +++ b/CPP/Shortest commont supersequence @@ -0,0 +1,43 @@ +//link: https://leetcode.com/problems/shortest-common-supersequence/description/ + + + +string shortestCommonSupersequence(string str1, string str2) { + int n = str1.length(); + int m = str2.length(); + vector> dp(n+1,vector(m+1,0)); + for(int i = 1; i <= n ; i++ ){ + for(int j = 1 ;j <= m ; j++){ + if( str1[i-1] == str2[j-1]){ + dp[i][j] = 1+ dp[i-1][j-1]; + } + else{ + dp[i][j] = max(dp[i-1][j],dp[i][j-1]); + } + } + } + string lcs=""; + int i =n, j=m; + while(i>=1 && j>=1){ + if(str1[i-1] == str2[j-1]){ + lcs.push_back(str1[i-1]); + i--,j--; + } + else if( dp[i-1][j] > dp[i][j-1]){ + lcs.push_back(str1[i-1]); + i--; + } + else { + lcs.push_back(str2[j-1]); + j--; + } + } + while(i>0){ lcs.push_back(str1[i-1]); i--;} + while(j>0){ lcs.push_back(str2[j-1]); j--;} + reverse(lcs.begin(),lcs.end()); + cout< +using namespace std; + +void SieveOfEratosthenes(int n) +{ + // Create a boolean array "prime[0..n]" and initialize + // all entries it as true. A value in prime[i] will + // finally be false if i is Not a prime, else true. + bool prime[n + 1]; + memset(prime, true, sizeof(prime)); + + for (int p = 2; p * p <= n; p++) { + // If prime[p] is not changed, then it is a prime + if (prime[p] == true) { + // Update all multiples of p greater than or + // equal to the square of it numbers which are + // multiple of p and are less than p^2 are + // already been marked. + for (int i = p * p; i <= n; i += p) + prime[i] = false; + } + } + + // Print all prime numbers + for (int p = 2; p <= n; p++) + if (prime[p]) + cout << p << " "; +} + +// Driver Code +int main() +{ + int n = 30; + cout << "Following are the prime numbers smaller " + << " than or equal to " << n << endl; + SieveOfEratosthenes(n); + return 0; +} diff --git a/CPP/Sliding Window/Find All Anagrams in a String b/CPP/Sliding Window/Find All Anagrams in a String new file mode 100644 index 00000000..239ad1a3 --- /dev/null +++ b/CPP/Sliding Window/Find All Anagrams in a String @@ -0,0 +1,29 @@ +class Solution +{ + public: + vector findAnagrams(string s, string p) + { + if (s.length() < p.length()) return {}; + vector ans; + vector a(26, 0); + vector b(26, 0); + int j = 0; + while (j < p.size()) + { + a[p[j] - 'a']++; + b[s[j] - 'a']++; + j++; + } + int n = p.size(); + j--; + while (j < s.size()) + { + if (a == b) ans.push_back(j - n + 1); + j++; + if (!s[j]) break; + b[s[j - n] - 'a']--; + b[s[j] - 'a']++; + } + return ans; + } +}; diff --git a/CPP/Sliding Window/Pick max sum from both side.cpp b/CPP/Sliding Window/Pick max sum from both side.cpp new file mode 100644 index 00000000..6a712695 --- /dev/null +++ b/CPP/Sliding Window/Pick max sum from both side.cpp @@ -0,0 +1,19 @@ +int Solution::solve(vector &A, int B) { + +int n=A.size(); +int maxsum=0; +int j=n-1; +for(int i=n-B;i +using namespace std; + +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +class Solution +{ + public: + Node* lca(Node* root ,int n1 ,int n2 ) + { + if(root == NULL || root->data == n1 || root->data == n2) { + return root; + } + + Node* left = lca(root->left, n1, n2); + Node* right = lca(root->right, n1, n2); + + if(left != NULL && right != NULL) { + return root; + } else if (left != NULL) { + return left; + } else { + return right; + } + } +}; \ No newline at end of file diff --git a/Trees/Max_Depth_BinaryTree.cpp b/CPP/Trees/Max_Depth_BinaryTree.cpp similarity index 100% rename from Trees/Max_Depth_BinaryTree.cpp rename to CPP/Trees/Max_Depth_BinaryTree.cpp diff --git a/CPP/Trees/Maximum width of tree b/CPP/Trees/Maximum width of tree new file mode 100644 index 00000000..125b92bc --- /dev/null +++ b/CPP/Trees/Maximum width of tree @@ -0,0 +1,35 @@ +class Solution { + public: + // Function to get the maximum width of a binary tree. + int getMaxWidth(Node* root) + { + if(root==NULL) + { + return 0; + } + queueq; + q.push(root); + int res=0; + while(q.empty()==false) + { + int curr=q.size(); + res=max(curr,res); + for(int i=0;ileft!=NULL) + { + q.push(curr->left); + } + if(curr->right!=NULL) + { + q.push(curr->right); + } + } + } + return res; + // Your code here + } +}; diff --git a/Trees/Merge-Two-Binary-Trees.cpp b/CPP/Trees/Merge-Two-Binary-Trees.cpp similarity index 100% rename from Trees/Merge-Two-Binary-Trees.cpp rename to CPP/Trees/Merge-Two-Binary-Trees.cpp diff --git a/Trees/RecoverBinarySearchTree.cpp b/CPP/Trees/RecoverBinarySearchTree.cpp similarity index 100% rename from Trees/RecoverBinarySearchTree.cpp rename to CPP/Trees/RecoverBinarySearchTree.cpp diff --git a/Trees/Same Tree.cpp b/CPP/Trees/Same Tree.cpp similarity index 97% rename from Trees/Same Tree.cpp rename to CPP/Trees/Same Tree.cpp index 9cd4fb4a..ca7ad87f 100644 --- a/Trees/Same Tree.cpp +++ b/CPP/Trees/Same Tree.cpp @@ -1,21 +1,21 @@ -/** Question Link:-https://leetcode.com/problems/same-tree/ - * 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: - bool isSameTree(TreeNode* p, TreeNode* q) { - if(p==NULL || q==NULL) - { - return (p==q); - } - return ((p->val==q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right)); - } +/** Question Link:-https://leetcode.com/problems/same-tree/ + * 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: + bool isSameTree(TreeNode* p, TreeNode* q) { + if(p==NULL || q==NULL) + { + return (p==q); + } + return ((p->val==q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right)); + } }; \ No newline at end of file diff --git a/CPP/Trees/TargetSum.cpp b/CPP/Trees/TargetSum.cpp new file mode 100644 index 00000000..aad98f5d --- /dev/null +++ b/CPP/Trees/TargetSum.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +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) {} +}; + +//https://leetcode.com/problems/path-sum/ + +class Solution { +public: + bool hasPathSum(TreeNode* root, int targetSum) { + if(root == NULL) { + return false; + } + + targetSum = targetSum - root->val; + if(targetSum == 0 && root->left == NULL && root->right == NULL) { + return true; + } + + return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum); + } +}; \ No newline at end of file diff --git a/Trees/TopView_of_tree.cpp b/CPP/Trees/TopView_of_tree.cpp similarity index 100% rename from Trees/TopView_of_tree.cpp rename to CPP/Trees/TopView_of_tree.cpp diff --git a/CPP/Trees/average of each level b/CPP/Trees/average of each level new file mode 100644 index 00000000..5f97848b --- /dev/null +++ b/CPP/Trees/average of each level @@ -0,0 +1,31 @@ +vector averageOfLevels(TreeNode* root) + { + vectorv; + double sum=0; + double count=0; + queueq; + q.push(root); + while(q.empty()==false) + { + int size=q.size(); + count=size; + sum=0; + for(int i=0;ival; + q.pop(); + if(curr->left!=NULL) + { + q.push(curr->left); + } + if(curr->right!=NULL) + { + q.push(curr->right); + } + } + v.push_back(sum/count); + } + return v; + } +}; diff --git a/CPP/Trees/children sum property b/CPP/Trees/children sum property new file mode 100644 index 00000000..46527ad9 --- /dev/null +++ b/CPP/Trees/children sum property @@ -0,0 +1,21 @@ +bool iscsp(node*root) +{ + if(root==NULL) + { + return true; + } + if(root->left==NULL||root->right==NULL) + { + return true; + } + int sum=0; + if(root->left!=NULL) + { + sum+=root->left->key; + } + if(root->right!=NULL) + { + sum+=root->right->key; + } + return (root->key==sum&&iscsp(root->left)&&iscsp(root->right)); +} diff --git a/Trees/inverting a binary tree b/CPP/Trees/inverting a binary tree similarity index 100% rename from Trees/inverting a binary tree rename to CPP/Trees/inverting a binary tree diff --git a/Trees/kthMinimumElement.cpp b/CPP/Trees/kthMinimumElement.cpp similarity index 100% rename from Trees/kthMinimumElement.cpp rename to CPP/Trees/kthMinimumElement.cpp diff --git a/CPP/Trees/left_view_of_binary_tree.cpp b/CPP/Trees/left_view_of_binary_tree.cpp new file mode 100644 index 00000000..66c4cc7f --- /dev/null +++ b/CPP/Trees/left_view_of_binary_tree.cpp @@ -0,0 +1,85 @@ +// Input : +// 1 +// / \ +// 2 3 +// / \ \ +// 4 5 6 +// Output : 1 2 4 + +// Input : +// 1 +// / \ +// 2 3 +// \ +// 4 +// \ +// 5 +// \ +// 6 +// Output :1 2 4 5 6 + +#include +using namespace std; + +struct Node +{ + int data; + struct Node *left, *right; +}; + +// A utility function to +// create a new Binary Tree Node +struct Node *newNode(int item) +{ + struct Node *temp = (struct Node *)malloc( + sizeof(struct Node)); + temp->data = item; + temp->left = temp->right = NULL; + return temp; +} + +// Recursive function to print +// left view of a binary tree. +void leftViewUtil(struct Node *root, + int level, int *max_level) +{ + // Base Case + if (root == NULL) + return; + + // If this is the first Node of its level + if (*max_level < level) + { + cout << root->data << " "; + *max_level = level; + } + + // Recur for left subtree first, + // then right subtree + leftViewUtil(root->left, level + 1, max_level); + leftViewUtil(root->right, level + 1, max_level); +} + +// A wrapper over leftViewUtil() +void leftView(struct Node *root) +{ + int max_level = 0; + leftViewUtil(root, 1, &max_level); +} + +// Driver Code +int main() +{ + Node *root = newNode(10); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(7); + root->left->right = newNode(8); + root->right->right = newNode(15); + root->right->left = newNode(12); + root->right->right->left = newNode(14); + + leftView(root); + + return 0; +} \ No newline at end of file diff --git a/Trees/treeDuplicate.java b/CPP/Trees/treeDuplicate.java similarity index 100% rename from Trees/treeDuplicate.java rename to CPP/Trees/treeDuplicate.java diff --git a/Trees/tree_foldable.cpp b/CPP/Trees/tree_foldable.cpp similarity index 100% rename from Trees/tree_foldable.cpp rename to CPP/Trees/tree_foldable.cpp diff --git a/CPP/Tries/implementTrie.cpp b/CPP/Tries/implementTrie.cpp new file mode 100644 index 00000000..f2d99eee --- /dev/null +++ b/CPP/Tries/implementTrie.cpp @@ -0,0 +1,55 @@ +class Node { +public: + char c; + Node* child[26]; + bool isWord; + + Node(char c) { + this -> c = c; + isWord = false; + + for(int i = 0 ; i < 26 ; i++) + child[i] = NULL; + } +}; + +class Trie { + Node* root; + Node* getNode(string &s){ + Node* curr = root; + for(auto &ch:s){ + if(curr -> child[ch - 97] == NULL) + return NULL; + curr = curr -> child[ch - 97]; + } + + return curr; + } +public: + Trie() { + root = new Node('\0'); + } + + void insert(string word) { + Node* curr = root; + + for(auto &ch:word){ + if(curr -> child[ch - 97] == NULL) + curr -> child[ch - 97] = new Node(ch); + curr = curr -> child[ch - 97]; + } + + curr -> isWord = true; + } + + bool search(string word) { + Node* reqNode = getNode(word); + + return reqNode && reqNode -> isWord; + } + + bool startsWith(string prefix) { + return getNode(prefix) != NULL; + } +}; + diff --git a/CPP/Wildcard matching leetcode solution b/CPP/Wildcard matching leetcode solution new file mode 100644 index 00000000..9345be18 --- /dev/null +++ b/CPP/Wildcard matching leetcode solution @@ -0,0 +1,61 @@ + + +//link: https://leetcode.com/problems/wildcard-matching/description/ + + +bool solve(int i, int j, string s1, string s2,vector>& dp){ + //base case + if(i<0 && j<0) return true; + if(i>=0 && j<0) return false; + if(i<0 && j>=0){ + for(int k =j;k>=0;k--){ + if(s2[k]!='*') return false; + } + return true; + } + + if(dp[i][j]!=-1) return dp[i][j]; + if(s1[i] == s2[j] || s2[j] == '?'){ + return dp[i][j] = solve(i-1,j-1,s1,s2,dp); + } + + if(s2[j] == '*' ){ + return dp[i][j] = solve(i,j-1,s1,s2,dp) | solve(i-1,j,s1,s2,dp); + } + + return dp[i][j] = false; + } + bool isMatch(string s, string p) { + int n = s.length(); + int m = p.length(); + vector> dp(n+1,vector(m+1,-1)); + dp[0][0] = true; + for(int i=0;i<=n;i++){ + dp[i][0] = false; + } + for(int i=0;i<=m;i++){ + bool is = true; + for(int j=0;j>& matrix, int target) { + int m=matrix.size(); + int n= matrix[0].size(); + int r=0; + int c=n-1; + while(r=0){ + if(matrix[r][c]==target){ + return true; + } + if(matrix[r][c]>target){ + c--; + } + else{ + r++; + } + + } + return false; + } +}; diff --git a/CPP/arrays/CheckifNandItsDoubleExist.cpp b/CPP/arrays/CheckifNandItsDoubleExist.cpp new file mode 100644 index 00000000..6a6d8d09 --- /dev/null +++ b/CPP/arrays/CheckifNandItsDoubleExist.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool checkIfExist(vector& arr) { + map map; + for(int i = 0;i& arr,int i,int j) + { + if(j& arr) { + int zeroes=0; + for(int i : arr) + { + if(i==0) + zeroes++; + } + + int i = arr.size()-1, j = arr.size()+zeroes-1; + while(i!=j) + { + insert(arr,i,j--); + if(arr[i]==0) + { + insert(arr,i,j--); + } + i--; + } + } \ No newline at end of file diff --git a/CPP/arrays/KthSmallest.cpp b/CPP/arrays/KthSmallest.cpp new file mode 100644 index 00000000..ad194869 --- /dev/null +++ b/CPP/arrays/KthSmallest.cpp @@ -0,0 +1,97 @@ +#include +#include +#include + +using namespace std; + +// It searches for x in arr[], and partitions the array around x +int partition(int arr[], int l, int r, int x) { + // Search for x in arr[] and move it to end + int i; + for (i = l; i < r; i++) + if (arr[i] == x) + break; + swap(arr[i], arr[r]); + + // Standard partition algorithm + i = l; + for (int j = l; j <= r - 1; j++) { + if (arr[j] <= x) { + swap(arr[i], arr[j]); + i++; + } + } + swap(arr[i], arr[r]); + return i; +} + +// A simple function to find median of arr[] +int findMedian(int arr[], int n) { + sort(arr, arr + n); + return arr[n / 2]; +} + +// Returns kth smallest element in arr[] in worst case linear time +int kthSmallest(int arr[], int l, int r, int k) { + // If k is smaller than number of elements in array + if (k > 0 && k <= r - l + 1) { + int n = r - l + 1; + + // Divide arr[] in groups of size 5, calculate median + // of every group and store it in median[] array + int i, median[(n + 4) / 5]; + for (i = 0; i < n / 5; i++) + median[i] = findMedian(arr + l + i * 5, 5); + // For the last group + if (i * 5 < n) { + median[i] = findMedian(arr + l + i * 5, n % 5); + i++; + } + + // Find median of all medians using recursive call + int medOfMed = (i == 1) ? median[i - 1] : kthSmallest(median, 0, i - 1, i / 2); + + // Partitioning the array around a random element and + // get position of pivot element in sorted array + int pos = partition(arr, l, r, medOfMed); + + // If position is same as k + if (pos - l == k - 1) + return arr[pos]; + // If position is more, recur for left + if (pos - l > k - 1) + return kthSmallest(arr, l, pos - 1, k); + + // Else recur for right subarray + return kthSmallest(arr, pos + 1, r, k - pos + l - 1); + } + + // If k is more than number of elements in array + return INT_MAX; +} + +int main() { + int size, k; + cout << "Enter size of array: "; + cin >> size; + + int arr[size]; + cout << "Enter into the array:\n"; + for (int i = 0; i < size; i++) + cin >> arr[i]; + + cout << "Enter value of k: "; + cin >> k; + cout << endl; + + if (k % 10 == 1) + cout << k << "st smallest element is: " << kthSmallest(arr, 0, size - 1, k); + else if (k % 10 == 2) + cout << k << "nd smallest element is: " << kthSmallest(arr, 0, size - 1, k); + else if (k % 10 == 3) + cout << k << "rd smallest element is: " << kthSmallest(arr, 0, size - 1, k); + else + cout << k << "th smallest element is: " << kthSmallest(arr, 0, size - 1, k); + + return 0; +} diff --git a/CPP/arrays/Max_Consecutive_Ones.cpp b/CPP/arrays/Max_Consecutive_Ones.cpp new file mode 100644 index 00000000..c6278b1f --- /dev/null +++ b/CPP/arrays/Max_Consecutive_Ones.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +int maxones(bool a[],int n){ + int res=0,cur=0; + for(int i=0;i& nums1, int m, vector& nums2, int n) { + + int i = m-1; + int j = n-1; + int k = m+n-1; + while(i>=0 && j>=0) + { + if(nums1[i]>nums2[j]) + { + nums1[k--]=nums1[i--]; + } + else + { + nums1[k--]=nums2[j--]; + } + } + while(i>=0) + { + nums1[k--]=nums1[i--]; + } + while(j>=0) + { + nums1[k--]=nums2[j--]; + } + } +}; \ No newline at end of file diff --git a/CPP/arrays/RemoveDuplicatefromSortedArray.cpp b/CPP/arrays/RemoveDuplicatefromSortedArray.cpp new file mode 100644 index 00000000..be155857 --- /dev/null +++ b/CPP/arrays/RemoveDuplicatefromSortedArray.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + vector v; + vector :: iterator it; + + for(it = nums.begin();it!=nums.end();it++) + { + int ele = *it; + if(find(v.begin(),v.end(),ele)!=v.end()) + { + nums.erase(it); + it--; + } + else + v.push_back(*it); + + } + return nums.size(); + } +}; \ No newline at end of file diff --git a/CPP/arrays/RemoveElement.cpp b/CPP/arrays/RemoveElement.cpp new file mode 100644 index 00000000..56770666 --- /dev/null +++ b/CPP/arrays/RemoveElement.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int removeElement(vector& nums, int val) { + vector :: iterator it; + it = nums.begin(); + for(int i=0;i sortArrayByParity(vector& nums) { + int n = nums.size(); + if(n==0 || n==1) + {return nums;} + + int i = 0,j=0; + while(i map; + map[0]=1; + int sum=0, ans=0; + for(int i=0; i +#include +using namespace std; +vector twoSum(vector& numbers, int target) { + vector res; + int n = numbers.size(); + int low = 0,high = n - 1; + while(lowtarget) + high -= 1; + else if(sum numbers({2,3,4}); + int target = 6; + vector res = twoSum(numbers,target); + for(auto x:res) + cout<& arr) { + if(arr.size()<3) return false; + + int i = 0; + for(;iarr[i+1]) + { i++; + break; + } + else if(arr[i]==arr[i+1]) return false; + } + if(i<2) return false; + for(;i > threeSum(vector &num) { + + vector > res; + + std::sort(num.begin(), num.end()); + + for (int i = 0; i < num.size(); i++) { + + int target = -num[i]; + int front = i + 1; + int back = num.size() - 1; + + while (front < back) { + + int sum = num[front] + num[back]; + + // Finding answer which start from number num[i] + if (sum < target) + front++; + + else if (sum > target) + back--; + + else { + vector triplet = {num[i], num[front], num[back]}; + res.push_back(triplet); + + // Processing duplicates of Number 2 + // Rolling the front pointer to the next different number forwards + while (front < back && num[front] == triplet[1]) front++; + + // Processing duplicates of Number 3 + // Rolling the back pointer to the next different number backwards + while (front < back && num[back] == triplet[2]) back--; + } + + } + + // Processing duplicates of Number 1 + while (i + 1 < num.size() && num[i + 1] == num[i]) + i++; + + } + + return res; + +} diff --git a/CPP/arrays/leetcode-problems/Substring with Concatenation of All Words.cpp b/CPP/arrays/leetcode-problems/Substring with Concatenation of All Words.cpp new file mode 100644 index 00000000..9ebc58c8 --- /dev/null +++ b/CPP/arrays/leetcode-problems/Substring with Concatenation of All Words.cpp @@ -0,0 +1,42 @@ +//Substring with Concatenation of All Words +class Solution { +public: + vector findSubstring(string s, vector& words) { + vectorans; + int n=words.size(); + int m=words[0].size(); + int total=n*m; + if(s.size()mp; + + for(int j=0;j& deck) { + int n=deck.size(); + if(n==1){ + return false; + } + unordered_mapm; + for(int i=0;i addToArrayForm(vector A, int K) { + for (int i = A.size() - 1; i >= 0 && K > 0; --i) { + A[i] += K; + K = A[i] / 10; + A[i] %= 10; + } + while (K > 0) { + A.insert(A.begin(), K % 10); + K /= 10; + } + return A; + } diff --git a/CPP/arrays/leetcode-problems/alternating array b/CPP/arrays/leetcode-problems/alternating array new file mode 100644 index 00000000..cecce898 --- /dev/null +++ b/CPP/arrays/leetcode-problems/alternating array @@ -0,0 +1,79 @@ + int minimumOperations(vector& nums) { + + int totalEven = 0, totalOdd = 0; + + unordered_map mapEven, mapOdd; + + for(int i=0;ifirst; + int count = it->second; + + if(count>=firstEvenCount) { + secondEvenCount = firstEvenCount; + secondEven = firstEven; + firstEvenCount = count; + firstEven = num; + } + + else if(count >= secondEvenCount) { + secondEvenCount = count; + secondEven = num; + } + } + + + int firstOddCount = 0, firstOdd = 0; + int secondOddCount = 0, secondOdd = 0; + + + for(auto it=mapOdd.begin();it!=mapOdd.end();it++) { + int num = it->first; + int count = it->second; + + if(count>=firstOddCount) { + secondOddCount = firstOddCount; + secondOdd = firstOdd; + firstOddCount = count; + firstOdd = num; + } + + else if(count>=secondOddCount) { + secondOddCount = count; + secondOdd = num; + } + } + + int operationsEven = 0, operationsOdd = 0; + + + operationsEven = totalEven - firstEvenCount; + + if(firstEven!=firstOdd) operationsEven += (totalOdd - firstOddCount); + else operationsEven += (totalOdd - secondOddCount); + + + operationsOdd = totalOdd - firstOddCount; + if(firstOdd!=firstEven) operationsOdd += (totalEven - firstEvenCount); + else operationsOdd += (totalEven - secondEvenCount); + + + return min(operationsEven, operationsOdd); + + } +}; diff --git a/CPP/arrays/leetcode-problems/append k integers with minimum sum b/CPP/arrays/leetcode-problems/append k integers with minimum sum new file mode 100644 index 00000000..be7bd355 --- /dev/null +++ b/CPP/arrays/leetcode-problems/append k integers with minimum sum @@ -0,0 +1,25 @@ + long long minimalKSum(vector& nums, int k) { + mapm; + int n=nums.size(); + long long ans=0; + for(int i=0;i(r-l)){k-=(r-l);} + else{break;} + ans+=(((r*(r-1))/2)-((l*(l-1))/2)); + start=r+1; + + } + + long long l=start; + long long r=start+k; + ans+=(((r*(r-1))/2)-((l*(l-1))/2)); + + return ans; + } diff --git a/CPP/arrays/leetcode-problems/binary prefix divisible by 5 b/CPP/arrays/leetcode-problems/binary prefix divisible by 5 new file mode 100644 index 00000000..b35c9d1c --- /dev/null +++ b/CPP/arrays/leetcode-problems/binary prefix divisible by 5 @@ -0,0 +1,12 @@ + vector prefixesDivBy5(vector& nums) { + int n=nums.size(); + int p=0; + vectorv; + int d=2; + for(int i=0;i& flowerbed, int n) { + int count = 0; + for (int i = 0; i < flowerbed.size(); i++) { + // Check if the current plot is empty. + if (flowerbed[i] == 0) { + // Check if the left and right plots are empty. + bool emptyLeftPlot = (i == 0) || (flowerbed[i - 1] == 0); + bool emptyRightPlot = (i == flowerbed.size() - 1) || (flowerbed[i + 1] == 0); + + // If both plots are empty, we can plant a flower here. + if (emptyLeftPlot && emptyRightPlot) { + flowerbed[i] = 1; + count++; + } + } + } + return count >= n; + } +}; +Time complexity: O(n). A single scan of the flowerbedf array of size n is done. + +Space complexity: O(1) diff --git a/CPP/arrays/leetcode-problems/check if all points lie on straight line b/CPP/arrays/leetcode-problems/check if all points lie on straight line new file mode 100644 index 00000000..2a2555f2 --- /dev/null +++ b/CPP/arrays/leetcode-problems/check if all points lie on straight line @@ -0,0 +1,10 @@ +bool checkStraightLine( vector>& coordinates ) { + int dY = coordinates[1][1] - coordinates[0][1]; + int dX = coordinates[1][0] - coordinates[0][0]; + for( int i=2; i < coordinates.size(); i++ ) { + auto p = coordinates[i]; + if( dX*(p[1] - coordinates[0][1]) != dY*(p[0] - coordinates[0][0]) ) + return false; + } + return true; +} diff --git a/CPP/arrays/leetcode-problems/check if n and double exist b/CPP/arrays/leetcode-problems/check if n and double exist new file mode 100644 index 00000000..6db42a9c --- /dev/null +++ b/CPP/arrays/leetcode-problems/check if n and double exist @@ -0,0 +1,15 @@ +public: + bool checkIfExist(vector& arr) { + unordered_sets; + int n=arr.size(); + s.insert(arr[0]); + for(int i=1;i& nums, int k) { + int n=nums.size(); + unordered_mapm; + for(int i=0;i lks; + long long ans=0; + for(int x : a){ + for(int i=1;i<=(1<<22);i*=2){ + if(lks.count(i-x)) ans+=lks[i-x]; + } + lks[x]+=1; + } + return ans % (int)(1e9 + 7); diff --git a/CPP/arrays/leetcode-problems/count rectangles b/CPP/arrays/leetcode-problems/count rectangles new file mode 100644 index 00000000..611f7a20 --- /dev/null +++ b/CPP/arrays/leetcode-problems/count rectangles @@ -0,0 +1,20 @@ + vector countRectangles(vector>& rectangles, vector>& points) { + vector>v(101); + for(int i=0;ians; + for(int i=0;i& strs) { + int n=strs.size(); + int m=strs[0].size(); + vectorsorted(n-1,false); + int res=0; + int i,j; + for(j=0;jstrs[i+1][j]){ + res++; + break; + } + } + if(i& arr, int m, int k) { + + + int cnt=0; + for(int i=0;i+m < arr.size(); i++){ + + if(arr[i]!=arr[i+m]){ + cnt=0; + } + cnt += (arr[i] == arr[i+m]); + if(cnt == (k-1)*m) + return true; + + } + return false; + + } diff --git a/CPP/arrays/leetcode-problems/find no closest to zero b/CPP/arrays/leetcode-problems/find no closest to zero new file mode 100644 index 00000000..951dcb19 --- /dev/null +++ b/CPP/arrays/leetcode-problems/find no closest to zero @@ -0,0 +1,14 @@ + int findClosestNumber(vector& nums) { +// setting the ans to maximum value of int + int ans = INT_MAX ; + for(int i : nums){ + // checking if each value of nums is less than the max value + if(abs(i) < abs(ans)){ + ans = i ; //check for the lesser value + } + else if(abs(i) == abs(ans)){ + ans = max (ans,i) ; // return the maximum in cases there are multiple answers + } + } + return ans ; + } diff --git a/CPP/arrays/leetcode-problems/find smallest greater b/CPP/arrays/leetcode-problems/find smallest greater new file mode 100644 index 00000000..4838a279 --- /dev/null +++ b/CPP/arrays/leetcode-problems/find smallest greater @@ -0,0 +1,29 @@ + char nextGreatestLetter(vector& letters, char target) { + if (letters.back() <= target) return letters.front(); + int low = 0, high = letters.size() - 1; + while (low < high) { + auto mid = (low + high) / 2; + if (target < letters[mid]) high = mid; + else low = mid + 1; + } + return letters[low]; + } + method 2 + char nextGreatestLetter(vector& letters, char target) { + int n=letters.size(); + if(target>letters[n-1]||targettarget){ + ans=letters[mid]; + h=mid-1; + } + else{l=mid+1;} + } + + return ans; + } diff --git a/CPP/arrays/leetcode-problems/longest continuos increasing subsequence b/CPP/arrays/leetcode-problems/longest continuos increasing subsequence new file mode 100644 index 00000000..a8b0e9a4 --- /dev/null +++ b/CPP/arrays/leetcode-problems/longest continuos increasing subsequence @@ -0,0 +1,13 @@ + int findLengthOfLCIS(vector& nums) { + int res=1; + int n=nums.size(); + int curr=1; + for(int i=1;inums[i-1]){ + curr++; + res=max(res,curr); + } + else{curr=1;} + } + return res; + } diff --git a/CPP/arrays/leetcode-problems/make sum divisble by p b/CPP/arrays/leetcode-problems/make sum divisble by p new file mode 100644 index 00000000..5d45bef8 --- /dev/null +++ b/CPP/arrays/leetcode-problems/make sum divisble by p @@ -0,0 +1,14 @@ + int minSubarray(vector& A, int p) { + int n = A.size(), res = n, need = 0, cur = 0; + for (auto a : A) + need = (need + a) % p; + unordered_map last = {{0, -1}}; + for (int i = 0; i < n; ++i) { + cur = (cur + A[i]) % p; + last[cur] = i; + int want = (cur - need + p) % p; + if (last.count(want)) + res = min(res, i - last[want]); + } + return res < n ? res : -1; + } diff --git a/CPP/arrays/leetcode-problems/maximum average subarray b/CPP/arrays/leetcode-problems/maximum average subarray new file mode 100644 index 00000000..d4ce869d --- /dev/null +++ b/CPP/arrays/leetcode-problems/maximum average subarray @@ -0,0 +1,13 @@ + double findMaxAverage(vector& nums, int k) { + double max_sum=INT_MIN; + double sum=0; + int N=nums.size(); + for(int i=0;i& candies, long long k) { + int ans=0; + long long sum=0; + for(int i=0;i=k){ + ans=mid; + l=mid+1; + } + else{r=mid;} + } + return ans; + } diff --git a/CPP/arrays/leetcode-problems/maximum product b/CPP/arrays/leetcode-problems/maximum product new file mode 100644 index 00000000..f9427841 --- /dev/null +++ b/CPP/arrays/leetcode-problems/maximum product @@ -0,0 +1,7 @@ +int maximumProduct(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + int temp1 = nums[n-1]*nums[n-2]*nums[n-3]; + int temp2 = nums[0]*nums[1]*nums[n-1]; + return temp1>temp2?temp1:temp2; +} diff --git a/CPP/arrays/leetcode-problems/maximum white tiles covered b/CPP/arrays/leetcode-problems/maximum white tiles covered new file mode 100644 index 00000000..a7fa9123 --- /dev/null +++ b/CPP/arrays/leetcode-problems/maximum white tiles covered @@ -0,0 +1,36 @@ + int maximumWhiteTiles(vector>& tiles, int carpetLen) { + vectorstart; + vectorend; + int n=tiles.size(); + for(int i=0;i0){curr-=prefix[i-1];} + ans=max(ans,curr); + } + else{ + int pos=upper_bound(end.begin(),end.end(),last)-end.begin(); + int curr=prefix[pos-1]; + if(i>0){curr-=prefix[i-1];} + if(last>=start[pos]){ + curr+=last-start[pos]+1; + } + ans=max(ans,curr); + } + } + return ans; + } diff --git a/CPP/arrays/leetcode-problems/merge sorted arrays b/CPP/arrays/leetcode-problems/merge sorted arrays new file mode 100644 index 00000000..90b627e3 --- /dev/null +++ b/CPP/arrays/leetcode-problems/merge sorted arrays @@ -0,0 +1,25 @@ + void merge(vector& nums1, int m, vector& nums2, int n) { + int i,j; + int gap=n+m; + for(gap=nextGap(gap);gap>0;gap=nextGap(gap)){ + for(i=0;i+gapnums1[i+gap]){ + swap(nums1[i],nums1[i+gap]); + } + } + for(j=gap>n?gap-n:0;inums2[j]){ + swap(nums1[i],nums2[j]); + } + } + if(jnums2[j+gap]){swap(nums2[j],nums2[j+gap]);} + } + } + } + for(int p=0;p& nums1, vector& nums2) { + long origDiff = 0, n = size(nums1), minDiff; + // calculating original difference without any replacement + for(int i = 0; i < n; i++) origDiff += abs(nums1[i] - nums2[i]); + minDiff = origDiff; + // sorted nums1 needed for using binary search + vectorarr = nums1; + sort(begin(arr), end(arr)); + for(int i = 0; i < n; i++){ + // find the newDiff after replacement + long newDiff = origDiff - abs(nums1[i] - nums2[i]) + abs(bs(arr, nums2[i]) - nums2[i]); + // minDiff will store minimum possible sum of difference after replacements + minDiff = min(minDiff, newDiff); + } + return minDiff % 1000000007; +} +// bs will return the element closest to k in arr. +int bs(vector& arr, int k){ + int n = size(arr), l = 0, r = n - 1, m, closest; + while(l <= r){ + m = (l + r) / 2; + if(arr[m] == k) return arr[m]; + if(arr[m] > k) r = m - 1; + else l = m + 1; + } + closest = arr[m]; + if(m - 1 >= 0 && abs(arr[m - 1] - k) < abs(arr[m] - k)) closest = arr[m - 1]; + if(m + 1 < n && abs(arr[m + 1] - k) < abs(arr[m] - k)) closest = arr[m + 1]; + return closest; +} diff --git a/CPP/arrays/leetcode-problems/minimum time to complete trips b/CPP/arrays/leetcode-problems/minimum time to complete trips new file mode 100644 index 00000000..43d2f95e --- /dev/null +++ b/CPP/arrays/leetcode-problems/minimum time to complete trips @@ -0,0 +1,34 @@ +class Solution { +public: + // this function will count totalTrips for the given time + // a = [1,2,3] , and at time 3 how many trips we can take? + // 3/1 + 3/2 + 3/3 => 3 + 1 + 1 = 5 Trips + long long int numberOfTripsForGivenTime(vector&a , long long int givenTime) + { + long long int totalTrips = 0; + for(auto x : a) + { + // convert it to long long int + long long int val = x; + + totalTrips += (givenTime / val); + } + return totalTrips; + } + long long minimumTime(vector& arr , int totalTrips) { + long long int lowestTime = 1; + long long int highestTime = 1e14; + while(lowestTime= totalTrips) + highestTime = mid; + else + lowestTime = mid+1; + } + return lowestTime; + } +}; +Time Complexity is - O(NlogD) , where D is 1e14 +Space Complexity is - O(1) diff --git a/CPP/arrays/leetcode-problems/no of equivalent domino pairs b/CPP/arrays/leetcode-problems/no of equivalent domino pairs new file mode 100644 index 00000000..51627572 --- /dev/null +++ b/CPP/arrays/leetcode-problems/no of equivalent domino pairs @@ -0,0 +1,9 @@ + int numEquivDominoPairs(vector>& dominoes) { + + unordered_map count; + int res = 0; + for (auto& d : dominoes) { + res += count[min(d[0], d[1]) * 10 + max(d[0], d[1])]++; + } + return res; + } diff --git a/CPP/arrays/leetcode-problems/palindrome with fixed length b/CPP/arrays/leetcode-problems/palindrome with fixed length new file mode 100644 index 00000000..0885a1d4 --- /dev/null +++ b/CPP/arrays/leetcode-problems/palindrome with fixed length @@ -0,0 +1,55 @@ + int temp; + long long start,end; + if((intLength%2)!=0){ + temp=intLength/2; + } + else{temp=intLength/2-1;} + start=pow(10,temp); + while(temp){ + end=end*10+9; + temp=temp/10; + } + long long r=end-start+1; + if on traversing queries[i]>r then return -1 + otherwise call following function for each query + +// C++ program of finding nth palindrome +// of k digit +#include +using namespace std; + +void nthPalindrome(int n, int k) +{ + // Determine the first half digits + int temp = (k & 1) ? (k / 2) : (k/2 - 1); + int palindrome = (int)pow(10, temp); + palindrome += n - 1; + + // Print the first half digits of palindrome + printf("%d", palindrome); + + // If k is odd, truncate the last digit + if (k & 1) + palindrome /= 10; + + // print the last half digits of palindrome + while (palindrome) + { + printf("%d", palindrome % 10); + palindrome /= 10; + } + printf("\n"); +} + +// Driver code +int main() +{ + int n = 6, k = 5; + printf("%dth palindrome of %d digit = ",n ,k); + nthPalindrome(n ,k); + + n = 10, k = 6; + printf("%dth palindrome of %d digit = ",n ,k); + nthPalindrome(n, k); + return 0; +} diff --git a/CPP/arrays/leetcode-problems/partition array into three parts with same sum b/CPP/arrays/leetcode-problems/partition array into three parts with same sum new file mode 100644 index 00000000..833fc9b8 --- /dev/null +++ b/CPP/arrays/leetcode-problems/partition array into three parts with same sum @@ -0,0 +1,3 @@ +A simple solution is to first find all the subarrays, store the sum of these subarrays with their starting and ending points, and then find three disjoint continuous subarrays with equal sum. Time complexity of this solution will be quadratic. +An efficient solution is to first find the sum S of all array elements. Check if this sum is divisible by 3 or not. This is because if sum is not divisible then the sum cannot be split in three equal sum sets. If there are three contiguous subarrays with equal sum, then sum of each subarray is S/3. Suppose the required pair of indices is (i, j) such that sum(arr[0..i]) = sum(arr[i+1..j]) = S/3. Also sum(arr[0..i]) = preSum[i] and sum(arr[i+1..j]) = preSum[j] – preSum[i]. This gives preSum[i] = preSum[j] – preSum[i] = S/3. This gives preSum[j] = 2*preSum[i]. Thus, the problem reduces to find two indices i and j such that preSum[i] = S/3 and preSum[j] = 2*(S/3). +For finding these two indices, traverse the array and store sum upto current element in a variable preSum. Check if preSum is equal to S/3 and 2*(S/3). diff --git a/CPP/arrays/leetcode-problems/plus one b/CPP/arrays/leetcode-problems/plus one new file mode 100644 index 00000000..e82ce912 --- /dev/null +++ b/CPP/arrays/leetcode-problems/plus one @@ -0,0 +1,41 @@ + vectorv; + bool flag=true; + int n=digits.size(); + if((n==1)&&(digits[0]==9)){ + v.push_back(1); + v.push_back(0); + return v; + } + else if((n==1)&&(digits[0]!=9)){digits[0]+=1; + return digits;} + for(int i=n-1;i>0;i--){ + if((digits[i]+1)<10){ + flag=false; + digits[i]+=1; + break; + } + + digits[i]+=1; + if(digits[i]>=10){digits[i]=digits[i]%10;} + } + if((digits[0]==9)&&flag){ + v.push_back(1); + v.push_back(0); + } + else{ + if(flag){ + v.push_back(digits[0]+1);} + else{v.push_back(digits[0]);} + } + for(int i=1;i plusOne(vector& digits) { + for (int i=digits.size(); i--; digits[i] = 0) + if (digits[i]++ < 9) + return digits; + digits[0]++; + digits.push_back(0); + return digits; +} diff --git a/CPP/arrays/leetcode-problems/remove on element b/CPP/arrays/leetcode-problems/remove on element new file mode 100644 index 00000000..8d37a456 --- /dev/null +++ b/CPP/arrays/leetcode-problems/remove on element @@ -0,0 +1,18 @@ +bool canBeIncreasing(vector& nums) { + int previous = nums[0]; + bool used = false; + for (int i = 1; i < nums.size(); i++){ + if (nums[i] <= previous){ // it's not strictly increasing + if (used) + return false; + // we haven't used the element removal yet. + used = true; + if (i == 1 || nums[i] > nums[i - 2]) // we remove the element from i - 1 position because it's bigger, so we update previous. + previous = nums[i]; + // else we remove current element and leave previous to it's existing value. + } else + previous = nums[i]; + } + return true; +} +//O(n) Time complexity diff --git a/CPP/arrays/leetcode-problems/search in sorted rotated array b/CPP/arrays/leetcode-problems/search in sorted rotated array new file mode 100644 index 00000000..58dbaca4 --- /dev/null +++ b/CPP/arrays/leetcode-problems/search in sorted rotated array @@ -0,0 +1,32 @@ + bool search(vector& nums, int target) { + int l=0; + int h=nums.size()-1; + while(l<=h){ + int mid=(l+h)/2; + if(nums[mid]==target){ + return true; + } + else if((nums[l]==nums[mid])&&(nums[mid]==nums[h])){ + l++; + h--; + } + else { + if(nums[mid]>=nums[l]){ + if(target>=nums[l]&&target=nums[mid]&&target<=nums[h]){ + l=mid+1; + } + else{h=mid-1;} + } + + + } + + } diff --git a/CPP/arrays/leetcode-problems/serach insert position b/CPP/arrays/leetcode-problems/serach insert position new file mode 100644 index 00000000..d53c19c9 --- /dev/null +++ b/CPP/arrays/leetcode-problems/serach insert position @@ -0,0 +1,15 @@ + int searchInsert(vector& nums, int target) { + int h=nums.size()-1; + int l=0; + while(l<=h){ + int mid=(l+h)/2; + if(nums[mid]==target){ + return mid; + } + else if(nums[mid] successfulPairs(vector& s, vector& p, long long suc) { + + vector v(s.size(),0); + sort(p.begin(),p.end()); + + for(int i=0;i= suc) + h = mid-1; + + else + l = mid+1; + } + + v[i] = p.size()-1-h; + } + + return v; + } diff --git a/CPP/arrays/leetcode-problems/summary ranges b/CPP/arrays/leetcode-problems/summary ranges new file mode 100644 index 00000000..8b29e99d --- /dev/null +++ b/CPP/arrays/leetcode-problems/summary ranges @@ -0,0 +1,35 @@ + vector summaryRanges(vector& arr) { + int n = arr.size(); // extracting size of the array + vector ans; // declaring answer array to store our answer + + string temp = ""; // temproray string that stores all possible answer + + for(int i = 0; i < n; i++) // start traversing from the array + { + int j = i; // declare anthor pointer that will move + + // run that pointer until our range is not break + while(j + 1 < n && arr[j + 1] == arr[j] + 1) + { + j++; + } + + // if j > i, that means we got our range more than one element + if(j > i) + { + temp += to_string(arr[i]); // first store starting point + temp += "->"; // then store arrow, as question wants it + temp += to_string(arr[j]); // and lastly store the end point + } + else // we got only one element as range + { + temp += to_string(arr[i]); // then store that element in temp + } + + ans.push_back(temp); // push one possible answer string to our answer + temp = ""; // again reintiliaze temp for new possible answers + i = j; // and move i to j for a fresh start + } + + return ans; // and at last finally return the answer array + } diff --git a/CPP/arrays/leetcode-problems/valid mountain array b/CPP/arrays/leetcode-problems/valid mountain array new file mode 100644 index 00000000..34025583 --- /dev/null +++ b/CPP/arrays/leetcode-problems/valid mountain array @@ -0,0 +1,6 @@ + bool validMountainArray(vector& A) { + int n = A.size(), i = 0, j = n - 1; + while (i + 1 < n && A[i] < A[i + 1]) i++; + while (j > 0 && A[j - 1] > A[j]) j--; + return i > 0 && i == j && j < n - 1; + } diff --git a/CPP/arrays/leetcode-problems/wiggle sort2 b/CPP/arrays/leetcode-problems/wiggle sort2 new file mode 100644 index 00000000..317401e9 --- /dev/null +++ b/CPP/arrays/leetcode-problems/wiggle sort2 @@ -0,0 +1,20 @@ + void wiggleSort(vector& nums) { + int n=nums.size(); + sort(nums.begin(),nums.end()); + int i=1; + int j=n-1; + int res[n]; + while(i +#include"binarytree.h" +using namespace std; + +class node +{ + public: + int data; + node* next; +}; + +void printTree(binarytree*root) +{ + if(root==NULL) + return; + + cout<data<<":"; + if(root->left) + cout<<"L"<left->data<<","; + + if(root->right) + cout<<"R"<right->data<<","; + + cout<left); + printTree(root->right); +} + +void printlevelwise(binarytree*root) +{ + queue*> pendingnode; + pendingnode.push(root); + + while(pendingnode.size()!=0) + { + binarytree*front=pendingnode.front(); + cout<data<<":"; + pendingnode.pop(); + if(front->left) + { + cout<<"L"<left->data<<","; + pendingnode.push(front->left); + } + + if(front->right) + { + cout<<"R"<right->data<<","; + pendingnode.push(front->right); + } + + cout<* takeinput() +{ + int rootdata; + cout<<"enter data:"; + cin>>rootdata; + + if(rootdata==-1) + return NULL; + + binarytree*root=new binarytree (rootdata); + binarytree*leftchild=takeinput(); + binarytree*rightchild=takeinput(); + + root->left=leftchild; + root->right=rightchild; + + return root; + +} + + +binarytree*takeinputlevelwise() +{ + cout<<"enter root data : "; + int rootdata; + cin>>rootdata; + binarytree*root=new binarytree(rootdata); + queue*>pendingnodes; + pendingnodes.push(root); + while(pendingnodes.size()!=0) + { + binarytree*front=pendingnodes.front(); + pendingnodes.pop(); + cout<data<<" : "; + int child; + cin>>child; + if(child!=-1) + { + binarytree*leftchild=new binarytree(child); + front->left=leftchild; + pendingnodes.push(leftchild); + } + cout<data<<" : "; + cin>>child; + if(child!=-1) + { + binarytree*rightchild=new binarytree(child); + front->right=rightchild; + pendingnodes.push(rightchild); + } + } + + return root; + +} + +int countnodes(binarytree *root) +{ + if(root==NULL) + return 0; + + return 1 + countnodes(root->left) + countnodes(root->right); +} + +void postoder(binarytree*root) +{ + if(root==NULL) + return; + + postoder(root->left); + postoder(root->right); + cout<data<<" "; +} + +void preoder(binarytree*root) +{ + if(root==NULL) + return; + + cout<data<<" "; + preoder(root->left); + preoder(root->right); +} + +void inoder(binarytree*root) +{ + if(root==NULL) + return; + + inoder(root->left); + cout<data<<" "; + inoder(root->right); +} + +binarytree * treebuilding(int *in, int *pre, int preS,int preE,int inS,int inE) +{ + if(inS>inE) + { + return NULL; + } + + int rootdata=pre[preS]; + binarytree*root=new binarytree(rootdata); + + int rootindex=-1; + for(int i=inS;i<=inE;i++) + { + if(rootdata==in[i]) + { + rootindex=i; + break; + } + } + + + int lpreS=preS+1; + int linS = inS; + int linE = rootindex-1; + int lpreE = linE-linS+lpreS; + int rpreS = lpreE +1; + int rpreE = preE; + int rinS = rootindex +1; + int rinE = inE; + + + root->left=treebuilding(in,pre,lpreS,lpreE,linS,linE); + root->right=treebuilding(in,pre,rpreS,rpreE,rinS,rinE); + + return root; + + +} + +binarytree * buildtree(int *in,int *pre,int size) +{ + return treebuilding(in , pre , 0 , size -1 , 0 , size - 1); +} + +int height(binarytree*root) +{ + if(root==NULL) + return 0; + + return 1+max(height(root->left),height(root->right)); +} + +pair heightdiameter(binarytree*root) +{ + if(root==NULL) + { + pair p; + p.first=0; + p.second=0; + return p; + } + + pair leftans=heightdiameter(root->left); + pair rightans=heightdiameter(root->right); + + int leftheight=leftans.first; + int leftdiameter=leftans.second; + int rightheight=rightans.first; + int rightdiameter=rightans.second; + + int height=1 + max(leftheight,rightheight); + int diameter = max(leftheight+rightheight,max(leftdiameter,rightdiameter)); + + pairp; + p.first=height; + p.second=diameter; + return p; +} + +int sumofallnodes(binarytree*root) +{ + if(root==NULL) + { + return 0; + } + + return root->data + sumofallnodes(root->left) + sumofallnodes(root->right); + +} + +int maxnode(binarytree*root) +{ + if(root==NULL) + return -1; + + int maximum=root->data; + + maximum=max(maximum,max(maxnode(root->left),maxnode(root->right))); + return maximum; + +} + +bool findanode(binarytree*root,int x) +{ + if(root==NULL) + return false; + + if(root->data==x) + return true; + + return findanode(root->left,x) || findanode(root->right,x); +} + +pair balancedhelper(binarytree*root) +{ + if(root==NULL) + { + pair p; + p.first=true; + p.second=0; + return p; + } + + pair leftans=balancedhelper(root->left); + pair rightans=balancedhelper(root->right); + + int leftheight=leftans.second; + int rightheight=rightans.second; + + if(abs(leftheight-rightheight)>1) + { + pair p; + p.first=false; + p.second=1+max(leftheight,rightheight); + return p; + } + + pairans; + ans.first=leftans.first && rightans.first; + ans.second=1+max(leftans.second,rightans.second); + + return ans; + +} + +bool istreebalanced(binarytree*root) +{ + pairans=balancedhelper(root); + return ans.first; +} + +void leveloder(binarytree*root) +{ + queue*> pendingnodes; + pendingnodes.push(root); + pendingnodes.push(NULL); + + while(pendingnodes.size()!=0) + { + binarytree*front=pendingnodes.front(); + pendingnodes.pop(); + + if(pendingnodes.size()==0) + break; + + if(front==NULL) + { + cout<data<<" "; + if(front->left) + pendingnodes.push(front->left); + + if(front->right) + pendingnodes.push(front->right); + } + } +} + +binarytree*removeleafnodes(binarytree*root) +{ + if(root==NULL) + { + return NULL; + } + + if(root->left==NULL && root->right==NULL) + { + delete root; + return NULL; + } + + root->left=removeleafnodes(root->left); + root->right=removeleafnodes(root->right); + + return root; +} + +vector levelwiselinkedlist(binarytree*root) +{ + node *head=NULL; + node *tail=NULL; + vectoroutput; + queue*>pendingnodes; + pendingnodes.push(root); + pendingnodes.push(NULL); + + while(pendingnodes.size()!=0) + { + binarytree*front=pendingnodes.front(); + pendingnodes.pop(); + + if(pendingnodes.size()==0) + { + output.push_back(head); + break; + } + + if(front==NULL) + { + output.push_back(head); + head=NULL; + tail=NULL; + pendingnodes.push(NULL); + } + else + { + node *p=new node; + p->data=front->data; + p->next=NULL; + + if(head==NULL) + { + head=tail=p; + } + else + { + tail->next=p; + tail=p; + } + + if(front->left) + pendingnodes.push(front->left); + + if(front->right) + pendingnodes.push(front->right); + + } + } + + return output; +} + +void displaylinkedlist(node * p) +{ + while(p) + { + cout<data<<" "; + p=p->next; + } + cout<*root) +{ + stack*>s1; + stack*>s2; + + s1.push(root); + + while(s1.size()!=0 || s2.size()!=0) + { + while(s1.size()!=0) + { + binarytree*front=s1.top(); + s1.pop(); + cout<data<<" "; + if(front->left) + s2.push(front->left); + + if(front->right) + s2.push(front->right); + + } + + cout<*front=s2.top(); + s2.pop(); + cout<data<<" "; + if(front->right) + s1.push(front->right); + + if(front->left) + s1.push(front->left); + } + + cout<*root) +{ + stack*>s1; + stack*>s2; + + s1.push(root); + while(s1.size()!=0 || s2.size()!=0) + { + while(s1.size()!=0) + { + binarytree*front=s1.top(); + s1.pop(); + if(front->left) + s2.push(front->left); + + if(front->right) + s2.push(front->right); + + } + + if(s2.size()==1) + { + cout<data<<" "; + } + + while(s2.size()!=0) + { + binarytree*front=s2.top(); + s2.pop(); + if(front->left) + s1.push(front->left); + + if(front->right) + s1.push(front->right); + + } + + if(s1.size()==1) + { + cout<data<<" "; + } + + + + } + +} + +//////------------------PRACTICE QUESTIONS ON BINARY TREE ---------------------------------- +binarytree* create_insert_duplicate_nodes(binarytree*root) +{ + if(root==NULL) + return NULL; + + + binarytree*leftside=root->left; + binarytree*duplicatenode=new binarytree(root->data); + root->left=duplicatenode; + + duplicatenode->left= create_insert_duplicate_nodes(leftside); + root->right = create_insert_duplicate_nodes(root->right); + + return root; + +} + +int pair_sum_binarytree(binarytree*root,int x) +{ + //TODO pair sum binarytree +} + + +int main() +{ + // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 + // 1 2 3 4 5 6 7 -1 -1 -1 -1 8 9 -1 -1 -1 -1 -1 -1 + //8 5 10 2 6 -1 6 -1 -1 -1 7 -1 -1 -1 -1 + // 1 2 3 4 5 -1 -1 -1 -1 -1 -1 + // 1 2 3 4 5 -1 8 -1 -1 6 -1 -1 -1 -1 -1 + // int in[]={4,2,5,1,8,6,9,33,7}; + // int pre[]={1,2,4,5,33,6,8,9,7}; + // binarytree*root=buildtree(in,pre,9); + + binarytree*root=takeinputlevelwise(); + printlevelwise(root); + cout< +using namespace std; + +class book { + int pages; + int ISSN; + public: + //Special member function => Constructor + //No parameter constructor => Default Constructor + book() { + pages = 103; + ISSN = 4; + } + + //Parameterised Constructor + book(int page, int issn) { + pages = page; + ISSN = issn; + } + + void display() { + cout<<"pages: "< +using namespace std; + +class book { + int pages; + int ISBN; + public: + //Default constructor + book() { + pages = 350; + ISBN = 1234; + } + + //Parameterised constructor + book(int Pages, int isbn) { + pages = Pages; + ISBN = isbn; + } + + void display() { + cout<<"Pages : "< +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +ll int collatz(ll int curr, vector &vec, ll int lv) +{ + if (curr <= lv && vec[curr] != -1) + { + // when we find any number in chain which has a value more than -1, its time to stop + return vec[curr]; + } + // collatz basic rule: n even -> (n / 2), n odd - > 3n +1 + + ll int next = (3 * curr) + 1; + + if (curr % 2 == 0) + { + next = curr / 2; + } + // prev number in range = 1 + next number in range + // (8 -> 4 -> 2 -> 1) here (answer for 8 is 4) and (answer for 4 is 3) + int nextv = 1 + collatz(next, vec, lv); + // if number lies in range(0 - vector.size()) then update it , other ignore it + if (curr <= lv) + { + vec[curr] = nextv; + } + return nextv; +} + +void solve() +{ + int x = 1000000; + vector vec(x + 1, -1); + vec[0] = vec[1] = 1; + for (int i = 1; i < x; i++) + { + vec[i + 1] = collatz(i + 1, vec, x - 1); + } + ll int maxm = -1, ans = -1; + for (int i = 0; i < vec.size(); i++) + { + if (vec[i] >= maxm) + { + maxm = vec[i]; + ans = i; + } + maxm = max(maxm, vec[i]); + } + cout << ans << endl; + return; +} + +int main() +{ + + ios_base::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + cin.exceptions(cin.failbit); + + clock_t start = clock(); + + solve(); + + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + + printf("Time measured: %.3f seconds.\n", elapsed); + + return 0; +} diff --git a/findPos/Namanjain6152.md b/CPP/findPos/Namanjain6152.cpp similarity index 99% rename from findPos/Namanjain6152.md rename to CPP/findPos/Namanjain6152.cpp index cc5a08e7..eccdd394 100644 --- a/findPos/Namanjain6152.md +++ b/CPP/findPos/Namanjain6152.cpp @@ -48,3 +48,4 @@ pair firstAndLastPosition(vector& arr, int n, int k) return {ans1,ans2}; } + diff --git a/CPP/graph_tree/Bipartite Graph.cpp b/CPP/graph_tree/Bipartite Graph.cpp new file mode 100644 index 00000000..448be42c --- /dev/null +++ b/CPP/graph_tree/Bipartite Graph.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + bool bfs(vector> graph, vector &vis, int src) + { + queue q; + q.push(src); + int clr = 0; + while(!q.empty()) + { + int size = q.size(); + for(int i=0; i>& graph) { + vector vis(graph.size(),-1); + for(int i=0; i + +using namespace std; + +const int V = 4; + +// This function returns true if +// graph G[V][V] is Bipartite, else false +bool isBipartiteUtil(int G[][V], int src, int colorArr[]) +{ + colorArr[src] = 1; + + // Create a queue (FIFO) of vertex numbers a + // nd enqueue source vertex for BFS traversal + queue q; + q.push(src); + + // Run while there are vertices in queue (Similar to + // BFS) + while (!q.empty()) { + // Dequeue a vertex from queue ( Refer + // http://goo.gl/35oz8 ) + int u = q.front(); + q.pop(); + + // Return false if there is a self-loop + if (G[u][u] == 1) + return false; + + // Find all non-colored adjacent vertices + for (int v = 0; v < V; ++v) { + // An edge from u to v exists and + // destination v is not colored + if (G[u][v] && colorArr[v] == -1) { + // Assign alternate color to this + // adjacent v of u + colorArr[v] = 1 - colorArr[u]; + q.push(v); + } + + // An edge from u to v exists and destination + // v is colored with same color as u + else if (G[u][v] && colorArr[v] == colorArr[u]) + return false; + } + } + + // If we reach here, then all adjacent vertices can + // be colored with alternate color + return true; +} + +// Returns true if G[][] is Bipartite, else false +bool isBipartite(int G[][V]) +{ + + int colorArr[V]; + for (int i = 0; i < V; ++i) + colorArr[i] = -1; + + // This code is to handle disconnected graph + for (int i = 0; i < V; i++) + if (colorArr[i] == -1) + if (isBipartiteUtil(G, i, colorArr) == false) + return false; + + return true; +} + +// Driver code +int main() +{ + int G[][V] = { { 0, 1, 0, 1 }, + { 1, 0, 1, 0 }, + { 0, 1, 0, 1 }, + { 1, 0, 1, 0 } }; + + isBipartite(G) ? cout << "Yes" : cout << "No"; + return 0; +} diff --git a/CPP/graph_tree/Detect a cycle in a graph.cpp b/CPP/graph_tree/Detect a cycle in a graph.cpp new file mode 100644 index 00000000..d3edcc1e --- /dev/null +++ b/CPP/graph_tree/Detect a cycle in a graph.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +using namespace std; + +class Graph{ +int V; +list *adj; + +bool isCyclicHelper(int s,bool *visited,bool *RStack){ + if(visited[s]==false){ + visited[s] = true; + rStack[s] = true; + + for(auto it=adj[s].begin();it!=adj[s].end();it++){ + if(!visited[*it]&&isCyclicHelper(*it,visited,rStack)){ + return true; + } + else if(rStack[*it]){ + return true; + } + } + + } +RStack[s]=false; +return false; +} + + +public: + Graph(int V){ + this->V = V; + adj = new list[V]; + } + + void addEdge(int u,int v){ + adj[u].push_back(v); + + } + + bool isCyclic(){ + bool *visited = new bool[V]; + bool *rStack = new bool[V]; + + memset(visited,false,sizeof(false)); + memset(rStack,false,sizeof(false)); + + //This works if there is a single DFS forest. Otherwise use a for loop. + if(isCyclicHelper(0,visited,rStack)){ + return true; + } + else{ + return false; + } + } + +}; + +int main(){ + + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + if(g.isCyclic()) + cout << "Graph contains cycle"; + else + cout << "Graph doesn't contain cycle"; + return 0; + +return 0; +} diff --git a/CPP/graph_tree/Floyd Warshall.cpp b/CPP/graph_tree/Floyd Warshall.cpp new file mode 100644 index 00000000..6139f81f --- /dev/null +++ b/CPP/graph_tree/Floyd Warshall.cpp @@ -0,0 +1,41 @@ +// Function of floyd Warshall algorithm + +void floydWarshall(vector> &distance) // distance is the adjacency matrix of nodes 0 to n-1 + { + int n=distance.size(),i,j,k; + + for(k=0;k adj[],vector &visited,stack &stk) +{ + visited[node] = true; + + for(auto child: adj[node]) + { + if(!visited[child]) + { + dfs(child,adj,visited,stk); + } + } + + stk.push(node); +} + +void dfsRec(int node,vector g[],vector &visited) +{ + visited[node]=true; + + for(auto child: g[node]) + { + if(!visited[child]) + { + dfsRec(child,g,visited); + } + } + + return; +} + +//Function to find number of strongly connected components in the graph. +int kosaraju(int V, vector adj[]) +{ + int i,j; + + stack stk; + + vector result; + vector visited(V,false); + + for(i=0;i g[V]; + + for(i=0;iright!=NULL and node->right!=curr) + node=node->right; + return node; +} + +void MorrisTraversal(struct tNode* root) +{ + tNode *curr=root; + while(curr!=NULL) + { + if(curr->left==NULL) + { + cout<data<<" "; + curr=curr->right; + } + else + { + tNode *rm=rightMost(curr->left, curr); + if(rm->right==NULL) + { + rm->right=curr; + curr=curr->left; + } + else + { + rm->right=NULL; + cout<data<<" "; + curr=curr->right; + } + } + } +} + diff --git a/CPP/graph_tree/bfs.cpp b/CPP/graph_tree/bfs.cpp new file mode 100644 index 00000000..ec625491 --- /dev/null +++ b/CPP/graph_tree/bfs.cpp @@ -0,0 +1,74 @@ +#include +#include +#include +using namespace std; +int n,m; +int dist[100]; +int parent[100]; +vector adjList[100]; +queue q; + +void bfs(int sour) +{ + for(int i=1;i<=n;i++) + { + if(n!=1) + { + parent[i]=0; + dist[i]=-1; + } + } + parent[sour]=0; + dist[sour]=0; + q.push(sour); + while(!q.empty()) + { + int x=q.front(); + q.pop(); + for(int j=0;j>n; + cout<<"Enter Edges_"; + cin>>m; + int x,y; + for(int i=1;i<=m;i++) + { + cin>>x; + cin>>y; + adjList[x].push_back(y); + } + + for(int i=1;i<=n;i++) + { + cout<"; + for(int j=0;j vec5 = func5(stri, values); + + for (int j = 0; j < vec5.size(); j++) + { + string strj = stri; + strj = strj + to_string(vec5[j]); + + values[vec5[j]] = 1; + + // cout << "STRJ: " << strj << endl; + + // cout << "CHECK VECTOR: " << endl; + // for (int i = 0; i < values.size(); i++) + // { + // cout << values[i] << " "; + // } + // cout << endl; + + vector vec7 = func7(strj, values); + + for (int k = 0; k < vec7.size(); k++) + { + + string strk = strj; + strk = strk + to_string(vec7[k]); + + values[vec7[k]] = 1; + + // cout << "STRK: " << strk << endl; + + // cout << "CHECK VECTOR: " << endl; + // for (int i = 0; i < values.size(); i++) + // { + // cout << values[i] << " "; + // } + // cout << endl; + + vector vec11 = func11(strk, values); + + for (int l = 0; l < vec11.size(); l++) + { + + string strl = strk; + strl = strl + to_string(vec11[l]); + + values[vec11[l]] = 1; + + // cout << "STRL: " << strl << endl; + + vector vec13 = func13(strl, values); + + for (int m = 0; m < vec13.size(); m++) + { + + string strm = strl; + strm = strm + to_string(vec13[m]); + + values[vec13[m]] = 1; + + // cout << "STRM: " << strm << endl; + + vector vec17 = func17(strm, values); + + for (int n = 0; n < vec17.size(); n++) + { + + string strn = strm; + strn = strn + to_string(vec17[n]); + + values[vec17[n]] = 1; + + // cout << "STRM: " << strn << endl; + + // cout << "CHECK VECTOR: " << endl; + // for (int i = 0; i < values.size(); i++) + // { + // cout << values[i] << " "; + // } + // cout << endl; + + for (int a = 0; a < values.size(); a++) + { + if (values[a] == 0) + { + string abcd = to_string(a); + string crst = abcd + strn; + + cout << "FINAL STRING: " << crst << endl; + } + } + + values[vec17[n]] = 0; + } + + // answer is size of vec17 + + values[vec13[m]] = 0; + } + + values[vec11[l]] = 0; + } + + values[vec7[k]] = 0; + } + + values[vec5[j]] = 0; + } + values[vec3[i]] = 0; + } +} + +void solve() +{ + + int start = 100, end = 1000; + for (int i = start; i < end; i++) + { + int curr = i; + if (curr % 2 == 0) + { + int a, b, c; + a = curr % 10; + curr /= 10; + b = curr % 10; + curr /= 10; + c = curr % 10; + curr /= 10; + + if (a != b && b != c && c != a) + { + // cout << i << endl; + func(i); + } + } + } +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + cin.exceptions(cin.failbit); + // freopen("input.txt", "r", stdin); + // freopen("output.txt", "w", stdout); + + clock_t start = clock(); + + solve(); + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + printf("Time measured: %.4f seconds.", elapsed); + return 0; +} + +/* + + + + + +*/ \ No newline at end of file diff --git a/CPP/pandigital_numbers/readme.txt b/CPP/pandigital_numbers/readme.txt new file mode 100644 index 00000000..5cf6ab1c --- /dev/null +++ b/CPP/pandigital_numbers/readme.txt @@ -0,0 +1,5 @@ +First code is of Problem statement: https://projecteuler.net/problem=43 + +Idea to solve this problem is: +we are given numbers that divides (di di+1 di+2), we will then form an array that satisifes condition and through multilple loops and by applying different fucntions like func3(), func5(), .. we will find how many values out of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} satifies that and keep oh doing it.. (Also we mark the numbers we found as 1, so that we dont get those again) +Finally we get all the numbers \ No newline at end of file diff --git a/CPP/pattern/4th b/CPP/pattern/4th new file mode 100644 index 00000000..abdd5cff --- /dev/null +++ b/CPP/pattern/4th @@ -0,0 +1,21 @@ +#include +using namespace std; +int main(){ + int n; + cin>>n; + + for(int i=1;i<=n;i++){ + for(int j=1;j<=n-1;j++){ + cout<<" "; + } + for(int k=1;k<=(2*i-1);k++){ + cout<<"*"; + + } + for(int k=(2*i-1);k<=1;k--){ + cout<<"*"; + + }cout< +using namespace std; +int main(){ + int n; + cin>>n; + for(int i=1;i<=n;i++){ + for(int j=1;j<=i;j++){ + cout< +using namespace std; +int main(){ + int n; + cin>>n; + + for(int i=1;i<=n;i++){ + for(int j=1;j<=n-i;j++){ + cout<<" "; + } + int k,j=i; + for(;j<=n;j--){ + cout< + +using namespace std; + +int main(){ + + int m,n; + cin>>m>>n; + + cout<<(m*n)/2; + return 0; +} diff --git a/CPP/pattern/floyd b/CPP/pattern/floyd new file mode 100644 index 00000000..203a1c30 --- /dev/null +++ b/CPP/pattern/floyd @@ -0,0 +1,12 @@ +#include +using namespace std; +int main(){ + int n,count=1; + cin>>n; + for(int i=1;i<=n;i++){ + for(int j=1;j<=i;j++){ + cout< +using namespace std; + +int binExpRec(int a, int b){ + + if(b==0){ + return 1; + } + + long long r = binExpRec(a,b/2); + + if(b & 1){ + return (a * r * r); + } + else{ + return r * r; + } + +} + +int main(){ + int a,b; + + cout<<"Enter the number and its power: "; + cin>>a>>b; + + int finalAns = binExpRec(a,b); + cout<< a << " to the power " << b << " = " << finalAns; + + return 0; +} diff --git a/CPP/recursion/Classic_Sudoke_Solver/README.md b/CPP/recursion/Classic_Sudoke_Solver/README.md new file mode 100644 index 00000000..354e5e45 --- /dev/null +++ b/CPP/recursion/Classic_Sudoke_Solver/README.md @@ -0,0 +1,35 @@ +## Classic Sudoku Solver. + +Implementation of Classic Sudoku Solver (9X9 Size) in C++. + +Sample Input : +```bash +Enter Unsolved Sudoku Matrix: +5 3 0 0 7 0 0 0 0 +6 0 0 1 9 5 0 0 0 +0 9 8 0 0 0 0 6 0 +8 0 0 0 6 0 0 0 3 +4 0 0 8 0 3 0 0 1 +7 0 0 0 2 0 0 0 6 +0 6 0 0 0 0 2 8 0 +0 0 0 4 1 9 0 0 5 +0 0 0 0 8 0 0 7 9 +``` + +Sample Output : +```bash +Solved Sudoku matrix: +----------------------- +5 3 4 | 6 7 8 | 9 1 2 | +6 7 2 | 1 9 5 | 3 4 8 | +1 9 8 | 3 4 2 | 5 6 7 | +----------------------- +8 5 9 | 7 6 1 | 4 2 3 | +4 2 6 | 8 5 3 | 7 9 1 | +7 1 3 | 9 2 4 | 8 5 6 | +----------------------- +9 6 1 | 5 3 7 | 2 8 4 | +2 8 7 | 4 1 9 | 6 3 5 | +3 4 5 | 2 8 6 | 1 7 9 | +----------------------- +``` diff --git a/CPP/recursion/Classic_Sudoke_Solver/Sudoku_Solver.cpp b/CPP/recursion/Classic_Sudoke_Solver/Sudoku_Solver.cpp new file mode 100644 index 00000000..4563e334 --- /dev/null +++ b/CPP/recursion/Classic_Sudoke_Solver/Sudoku_Solver.cpp @@ -0,0 +1,143 @@ +#include +#include +#include + +constexpr auto size = 9; + +// Function for unsolved sudoku input. +void take_inp(std::vector>& arr, int size) { + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { + std::cin >> arr[i][j]; + } + } +} + +// Function to print solved sudoku. +void print_vec(std::vector>& arr) { + int r_digit = 0, c_digit = 0; + + std::cout << "-----------------------\n"; + for (int i = 0; i < arr.size(); ++i) { + for (int j = 0; j < arr[i].size(); ++j) { + std::cout << arr[i][j] << " "; + ++c_digit; + if (c_digit == 3) { + std::cout << "| "; + c_digit = 0; + } + } + std::cout << std::endl; + ++r_digit; + if (r_digit == 3) { + std::cout << "-----------------------\n"; + r_digit = 0; + } + } +} + +bool value_canbe_placed(std::vector>& arr, int size, int i, int j, int val) { + // horizontal linear check + for (int l = 0; l < size; ++l) { + if (arr[i][l] == val) { + return false; + } + } + + // vertical linear check + for (int m = 0; m < size; ++m) { + if (arr[m][j] == val) { + return false; + } + } + + // checking inside 3X3 maTRix of 9X9 sudoku + int root = sqrt(size); + int mrow = (i / root) * root; + int mcol = (j / root) * root; + + for (int r = mrow; r <= mrow + 2; ++r) { + for (int c = mcol; c <= mcol + 2; ++c) { + if (arr[r][c] == val) { + return false; + } + } + } + + // value not present + return true; +} + +bool solveSudoku(std::vector>& arr, int size, int i, int j) { + // --> base case + // when row become equal to size, print + // solved sudoku matrix and return to main. + if (i == size) { + std::cout << "\nSolved Sudoku matrix:\n"; + print_vec(arr); + // sudoku solved, return true + return true; + } + + + // --> recursive case + // Case: if value can be filled + + // check column + // if value of j is reached to 9 i.e, > 8 in range 0 to 8 for 9 values + // increment the value of i to check for next row + if (j == size) { + return solveSudoku(arr, size, i + 1, 0); + } + + // if value of arr[i][j] is not equal to 0 then + // check for next column element of that row + if (arr[i][j] != 0) { + return solveSudoku(arr, size, i, j + 1); + } + + // if value of arr[i][j] equal to 0 then + // check if the num ranging from 1 to 9 can be placed at those index + // if number can be placed at those index then place that number + // again check for next column element of that row + // if next element can be placed return true else reset value at those index + else { + for (int num = 1; num <= size; ++num) { + if (value_canbe_placed(arr, size, i, j, num)) { + arr[i][j] = num; + bool nextValue = solveSudoku(arr, size, i, j + 1); + if (nextValue) { + return true; + } + else { + arr[i][j] = 0; + } + } + } + } + + // --> If value can't be filled return false + return false; +} + +int main() { + // 2d vector inp for storing sudoku. + // Size 9X9. + std::vector col(size); + std::vector> inp(size, col); + + // Function to take unsolved sudoku matrix. + std::cout << "Enter Unsolved Sudoku Matrix:\n"; + take_inp(inp, size); + + // Solve sudoku matrix and print it. + // Arguments passed are : 2D input matrix + // : Size of board. + // : Starting row. + // : Starting column. + if (!solveSudoku(inp, size, 0, 0)) { + std::cout << "Input Unsolved Sudoku have no solution. "; + } + + return 0; +} diff --git a/CPP/recursion/Fast Exponentiation.cpp b/CPP/recursion/Fast Exponentiation.cpp new file mode 100644 index 00000000..4499b8fb --- /dev/null +++ b/CPP/recursion/Fast Exponentiation.cpp @@ -0,0 +1,24 @@ +// program to find nth power of a number using optimized recursion (fast exponentiation) +#include +using namespace std; + +int fastExponent(int a, int b) { + // base case + if (b == 1) { + return a; + } + int tempResult = fastExponent(a, b/2); + // recursive relation + if ((b & 1) == 0) { + return (tempResult * tempResult); + } + else { + return (a * (tempResult * tempResult)); + } +} + +int main () { + int base = 3, power = 11; + cout< +using namespace std; +// Recursive function to return gcd of a and b +int gcd(int a, int b) +{ + // Everything divides 0 + if (a == 0) + return b; + if (b == 0) + return a; + + // base case + if (a == b) + return a; + + // a is greater + if (a > b) + return gcd(a-b, b); + return gcd(a, b-a); +} + +// Driver program to test above function +int main() +{ + int a = 98, b = 56; + cout<<"GCD of "< + +using namespace std; + +void Josh(vector person, int k, int index) +{ + if (person.size() == 1) { + cout << person[0] << endl; + return; + } + index = ((index + k) % person.size()); + person.erase(person.begin() + index); + Josh(person, k, index); +} + +int main() +{ + int n = 14; + int k = 2; + k--; + int index= 0; + vector person; + for (int i = 1; i <= n; i++) { + person.push_back(i); + } + Josh(person, k, index); +} diff --git a/CPP/recursion/M Coloring Problem b/CPP/recursion/M Coloring Problem new file mode 100644 index 00000000..ad10972b --- /dev/null +++ b/CPP/recursion/M Coloring Problem @@ -0,0 +1,51 @@ +#include +using namespace std; +//Code By Abhimanyu +bool isSafe(int node, int color[], bool graph[101][101], int n, int col) { + for (int k = 0; k < n; k++) { + if (k != node && graph[k][node] == 1 && color[k] == col) { + return false; + } + } + return true; +} +bool solve(int node, int color[], int m, int N, bool graph[101][101]) { + if (node == N) { + return true; + } + + for (int i = 1; i <= m; i++) { + if (isSafe(node, color, graph, N, i)) { + color[node] = i; + if (solve(node + 1, color, m, N, graph)) return true; + color[node] = 0; + } + + } + return false; +} +bool gC(bool graph[101][101], int m, int N) { + int color[N] = { + 0 + }; + if (solve(0, color, m, N, graph)) return true; + return false; +} + +int main() { + int N = 4; + int m = 3; + + bool graph[101][101]; + memset(graph, false, sizeof graph); + + + graph[0][1] = 1; graph[1][0] = 2; + graph[1][2] = 1; graph[2][1] = 1; + graph[2][3] = 1; graph[3][2] = 1; + graph[3][0] = 1; graph[0][3] = 1; + graph[0][2] = 1; graph[2][0] = 1; + + cout << gC(graph, m, N); + +} diff --git a/CPP/recursion/N_Queens/N_Queens.cpp b/CPP/recursion/N_Queens/N_Queens.cpp index ca9aeaec..0d1cad47 100644 --- a/CPP/recursion/N_Queens/N_Queens.cpp +++ b/CPP/recursion/N_Queens/N_Queens.cpp @@ -2,13 +2,18 @@ #include // Function to print the bord -void printBoard(std::vector>& board, int n) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (board[i][j] == 1) { +void printBoard(std::vector> &board, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n; ++j) + { + if (board[i][j] == 1) + { std::cout << 'Q' << ' '; } - else { + else + { std::cout << '_' << ' '; } } @@ -17,11 +22,14 @@ void printBoard(std::vector>& board, int n) { } // Function for checking valid squares. -bool canBePlaced(std::vector>& board, int i, int j, int n) { +bool canBePlaced(std::vector> &board, int i, int j, int n) +{ // Vertical check. - for (int v = 0; v < i; ++v) { - if (board[v][j] == 1) { + for (int v = 0; v < i; ++v) + { + if (board[v][j] == 1) + { return false; } } @@ -30,8 +38,10 @@ bool canBePlaced(std::vector>& board, int i, int j, int n) { int u = i, v = j; // Upper left diagonal check. - while (i >= 0 && j >= 0) { - if(board[i][j] == 1) { + while (i >= 0 && j >= 0) + { + if (board[i][j] == 1) + { return false; } --i; @@ -39,8 +49,10 @@ bool canBePlaced(std::vector>& board, int i, int j, int n) { } // Upper right diagonal. - while (u >= 0 && v < n) { - if (board[u][v] == 1) { + while (u >= 0 && v < n) + { + if (board[u][v] == 1) + { return false; } --u; @@ -52,11 +64,13 @@ bool canBePlaced(std::vector>& board, int i, int j, int n) { } // Main recursive function. -bool N_Queens(std::vector>& board, int n, int row) { +bool N_Queens(std::vector> &board, int n, int row) +{ // --> base case // When row becomes equal to n // means all queens have been placed in the right manner. - if (row == n) { + if (row == n) + { // Print the first possible way. printBoard(board, n); // Endl for printing the next possible board @@ -68,20 +82,24 @@ bool N_Queens(std::vector>& board, int n, int row) { } // --> recursive case - for (int column = 0; column < n; ++column) { + for (int column = 0; column < n; ++column) + { // Check if the queen can be placed at the ith row and jth column. - if (canBePlaced(board, row, column, n)) { + if (canBePlaced(board, row, column, n)) + { // Mark that place as 1. board[row][column] = 1; // Check for further positions. bool remaining_positions = N_Queens(board, n, row + 1); - if (remaining_positions) { + if (remaining_positions) + { // If queens can be placed in the remaining positions // it means the placing of queens can proceed further. // return true return true; } - else { + else + { // If queens cannot be placed further in the right way // backtrack to the previous position. board[row][column] = 0; @@ -92,18 +110,22 @@ bool N_Queens(std::vector>& board, int n, int row) { return false; } -int main() { +int main() +{ int n = 0; // Input Size of the chessboard // No of queens will be the same as size n. std::cin >> n; - + if (n <= 3) + { + std::cout << "No solution exists for n = " << n << std::endl; + } // 2D vector for storing board having size max size of nXn. // First create a column vector of size n. std::vector column(n); // Create Row vectors and fill rows with columns. - std::vector> board(n,column); + std::vector> board(n, column); // Function call for // Arguments passed are : 2D vector board diff --git a/CPP/recursion/N_Queens/N_Queens.exe b/CPP/recursion/N_Queens/N_Queens.exe new file mode 100644 index 00000000..7bf26991 Binary files /dev/null and b/CPP/recursion/N_Queens/N_Queens.exe differ diff --git a/CPP/recursion/NestedRecursion.cpp b/CPP/recursion/NestedRecursion.cpp new file mode 100644 index 00000000..157e5505 --- /dev/null +++ b/CPP/recursion/NestedRecursion.cpp @@ -0,0 +1,14 @@ +#include +int fun(int n) +{ +if(n>100) +return n-10; +return fun(fun(n+11)); +} +int main() +{ +int r; +r=fun(95); +printf("%d\n",r); +return 0; +} \ No newline at end of file diff --git a/CPP/recursion/Phone Keypad Problem b/CPP/recursion/Phone Keypad Problem new file mode 100644 index 00000000..5a659310 --- /dev/null +++ b/CPP/recursion/Phone Keypad Problem @@ -0,0 +1,42 @@ +#include +using namespace std; + +const vector pad = { + "", "", "abc", "def", "ghi", "jkl", + "mno", "pqrs", "tuv", "wxyz"}; + +vector letterCombinations(string digits) +{ + if (digits.empty()) + return {}; + vector result; + result.push_back(""); + + for (auto digit : digits) + { + vector tmp; + for (auto candidate : pad[digit - '0']) + { + for (auto s : result) + { + tmp.push_back(s + candidate); + } + } + result.swap(tmp); + } + return result; +} + +int main() +{ + string s; + cin >> s; + vector ans = letterCombinations(s); + for (auto i : ans) + { + cout << i << " "; + } + return 0; +} + +// by YASH GAUTAM diff --git a/CPP/recursion/Rat in a Maze b/CPP/recursion/Rat in a Maze new file mode 100644 index 00000000..8e7e09ce --- /dev/null +++ b/CPP/recursion/Rat in a Maze @@ -0,0 +1,95 @@ +#include +using namespace std; + +bool isSafe(int x, int y, int n, vector> vis, vector> &m) +{ + if ((x >= 0 and x < n) and (y >= 0 and y < n) and vis[x][y] == 0 and m[x][y] == 1) + { + return true; + } + return false; +} + +void solve(vector> &m, int n, vector &ans, int x, int y, vector> vis, string path) +{ + if (x == n - 1 and y == n - 1) + { + ans.push_back(path); + return; + } + vis[x][y] = 1; + + int newx = x + 1, newy = y; + if (isSafe(newx, newy, n, vis, m)) + { + path.push_back('D'); + solve(m, n, ans, newx, newy, vis, path); + path.pop_back(); + } + + newx = x, newy = y - 1; + if (isSafe(newx, newy, n, vis, m)) + { + path.push_back('L'); + solve(m, n, ans, newx, newy, vis, path); + path.pop_back(); + } + + newx = x, newy = y + 1; + if (isSafe(newx, newy, n, vis, m)) + { + path.push_back('R'); + solve(m, n, ans, newx, newy, vis, path); + path.pop_back(); + } + + newx = x - 1, newy = y; + if (isSafe(newx, newy, n, vis, m)) + { + path.push_back('U'); + solve(m, n, ans, newx, newy, vis, path); + path.pop_back(); + } + + vis[x][y] = 0; +} + +vector findPath(vector> &m, int n) +{ + vector ans; + if (m[0][0] == 0) + return ans; + int x = 0, y = 0; + vector> vis = m; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + vis[i][j] = 0; + } + string path = ""; + solve(m, n, ans, x, y, vis, path); + sort(ans.begin(), ans.end()); + return ans; +} + +int main() +{ + int n; + cin >> n; + vector> a(n, vector(n, 0)); + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + cin >> a[i][j]; + } + } + vector ans = findPath(a, n); + for (auto i : ans) + { + cout << i << endl; + } + return 0; +} + +// by YASH GAUTAM diff --git a/CPP/recursion/Subset with given Target b/CPP/recursion/Subset with given Target new file mode 100644 index 00000000..bde6d257 --- /dev/null +++ b/CPP/recursion/Subset with given Target @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +void solve(int i , int arr[],int sum,int target ,vectorans,int n) +{ + if(i>=n) + { + if(sum==target) + { + for(auto it : ans) + { + cout<ans; + +solve(0,arr,0,target ,ans,n); +} diff --git a/CPP/recursion/fibonacci_series.cpp b/CPP/recursion/fibonacci_series.cpp new file mode 100644 index 00000000..6022ba3f --- /dev/null +++ b/CPP/recursion/fibonacci_series.cpp @@ -0,0 +1,58 @@ +// #include +// using namespace std; +// int fib(int n){ +// if(n<=1) +// return n; +// else +// return fib(n-2)+fib(n-1); +// } +// int main(){ +// cout< +// using namespace std; +// int fib(int n){ +// if(n<=1) +// return 1; +// int t0=0,t1=1,s; +// for(int i=2;i<=n;i++){ +// s=t0+t1; +// t0=t1; +// t1=s; +// } +// return s; +// } +// int main(){ +// cout< +// using namespace std; +// int F[10]; +// int fib(int n){ +// if(n<=1){ +// F[n]=n; +// return n; +// } +// else +// if(F[n-2]==-1){ +// F[n-2]=fib(n-2); +// } +// if(F[n-1]==-1){ +// F[n-1]=fib(n-1); +// } +// return fib(n-2)+fib(n-1); +// } +// int main(){ +// cout< +using namespace std; +int fun(int n){ + if(n>100) + return n-10; + else + return fun(fun(n+11)); +} +int main(){ + cout< +using namespace std; + +int pivotIndex (int arr[], int lo, int hi) { + // base case + if (lo == hi) { + return lo; + } + int mid = lo + (hi - lo)/2; + // recursive relation + if (arr[mid] >= arr[0]) { // LINE-1 + return pivotIndex(arr, mid+1, hi); + } + else { // LINE-2 + return pivotIndex(arr, lo, mid); + } +} + +int main() { + int array[5] = {8,10,17,1,3}; + cout<<"Pivot index is: "< +using namespace std; + +void reverse(string &str) +{ + stack st; + for (int i=0; i +using namespace std; + +int FoundPivot(int arr[],int l,int r){ + if(l<=r){ + int mid = l + (r-l)/2; + + if(midarr[mid+1]) + return mid; + else if(mid > l && arr[mid] < arr[mid-1]) + return mid-1; + + if(arr[mid] >= arr[r]) + return FoundPivot(arr, mid+1, r); + + else + return FoundPivot(arr, l, mid-1); + + } + return -1; +} +int binarySearch(int arr[], int l, int r, int target){ + if(l>r)return -1; + + int mid = l + (r-l)/2; + + if(arr[mid] > target){ + return binarySearch(arr,l, mid-1, target); + } + else if(arr[mid] < target){ + return binarySearch(arr, mid+1, r, target); + } + return mid; +} + +void searchElementInRotatedArray(int arr[], int target,int n){ + int pivot = FoundPivot(arr,0, n-1); + + if(pivot == -1)return; + + int found = binarySearch(arr, 0, pivot, target); + + if(found == -1){ + found = binarySearch(arr, pivot+1, n-1, target); + } + if(found == -1){ + cout<<"NOT PRESENT !!"; + return; + } + cout<<"FOUND AT :"< +using namespace std; + +int binarySearch(int arr[], int, int, int); + +// Returns position of first occurrence of +// x in array +int exponentialSearch(int arr[], int n, int x) +{ + // If x is present at first location itself + if (arr[0] == x) + return 0; + + // Find range for binary search by + // repeated doubling + int i = 1; + while (i < n && arr[i] <= x) + i = i * 2; + + // Call binary search for the found range. + return binarySearch(arr, i / 2, + min(i, n - 1), x); +} + +// A recursive binary search function. It returns +// location of x in given array arr[l..r] is +// present, otherwise -1 +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) + { + int mid = l + (r - l) / 2; + + // If the element is present at the middle + // itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then it + // can only be present n left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, r, x); + } + + // We reach here when element is not present + // in array + return -1; +} + +// Driver code +int main(void) +{ + int arr[] = {2, 3, 4, 10, 40}; + int n = sizeof(arr) / sizeof(arr[0]); + int x = 10; + int result = exponentialSearch(arr, n, x); + (result == -1) ? cout << "Element is not present in array" : cout << "Element is present at index " << result; + return 0; +} \ No newline at end of file diff --git a/CPP/sliding-window/Find the K-Beauty of a Number.cpp b/CPP/sliding-window/Find the K-Beauty of a Number.cpp new file mode 100644 index 00000000..c6d83e41 --- /dev/null +++ b/CPP/sliding-window/Find the K-Beauty of a Number.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool isBeauty(string s1, string s2){ + int n1 = stoi(s1); + int n2 = stoi(s2); + if(n2) return !(n1 % n2); + return false; + } + + int divisorSubstrings(int num, int k) { + string s = to_string(num); + int n = s.size(); + if(!n) return 0; + int i = 0, j = 0, beautyCount = 0; + + + while(j < n){ + // Calculation + string window = s.substr(i, j - i + 1); + + // Window size not reached yet + if(j - i + 1 < k){ + j++; + } + + else if(j - i + 1 == k){ + // Find the answer + if(isBeauty(s, window)) beautyCount++; + + // Slide the window + i++; + j++; + } + } + return beautyCount; + } +}; diff --git a/CPP/sorting/3Sum Closest.cpp b/CPP/sorting/3Sum Closest.cpp new file mode 100644 index 00000000..0c0fe9fc --- /dev/null +++ b/CPP/sorting/3Sum Closest.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + sort(nums.begin(), nums.end()); + int sum, min = INT_MAX; + for (int i = 0; i < nums.size() - 2; i++) { + if (i == 0 || nums[i] != nums[i - 1]) { + int l = i + 1, r = nums.size() - 1; + while (l < r) { + int nsum = nums[r] + nums[l] + nums[i]; + if (nsum == target) + return nsum; + else if (nsum < target) + l++; + else + r--; + if (abs(nsum - target) < min) { + sum = nsum; + min = abs(sum - target); + } + } + } + } + return sum; + } +}; diff --git a/CPP/sorting/Cocktail Sort.cpp b/CPP/sorting/Cocktail Sort.cpp new file mode 100644 index 00000000..5e39ace8 --- /dev/null +++ b/CPP/sorting/Cocktail Sort.cpp @@ -0,0 +1,72 @@ +// C++ implementation of Cocktail Sort +#include +using namespace std; + +// Sorts array a[0..n-1] using Cocktail sort +void CocktailSort(int a[], int n) +{ +bool swapped = true; +int start = 0; +int end = n - 1; + +while (swapped) { +// reset the swapped flag on entering +// the loop, because it might be true from +// a previous iteration. +swapped = false; + +// loop from left to right same as +// the bubble sort +for (int i = start; i < end; ++i) { +if (a[i] > a[i + 1]) { + swap(a[i], a[i + 1]); + swapped = true; +} +} + +// if nothing moved, then array is sorted. +if (!swapped) +break; + +// otherwise, reset the swapped flag so that it +// can be used in the next stage +swapped = false; + +// move the end point back by one, because +// item at the end is in its rightful spot +--end; + +// from right to left, doing the +// same comparison as in the previous stage +for (int i = end - 1; i >= start; --i) { +if (a[i] > a[i + 1]) { + swap(a[i], a[i + 1]); + swapped = true; +} +} + +// increase the starting point, because +// the last stage would have moved the next +// smallest number to its rightful spot. +++start; +} +} + +/* Prints the array */ +void printArray(int a[], int n) +{ +for (int i = 0; i < n; i++) +printf("%d ", a[i]); +printf("\n"); +} + +// Driver code +int main() +{ +int arr[] = { 5, 1, 4, 2, 8, 0, 2 }; +int n = sizeof(arr) / sizeof(arr[0]); +CocktailSort(arr, n); +printf("Sorted array :\n"); +printArray(arr, n); +return 0; +} diff --git a/CPP/sorting/Heap Sort in C++ b/CPP/sorting/Heap Sort in C++ index 37b86c8c..0887d91c 100644 --- a/CPP/sorting/Heap Sort in C++ +++ b/CPP/sorting/Heap Sort in C++ @@ -1,4 +1,10 @@ + #include +======= +// C++ program for implementation of Heap Sort + +#include + using namespace std; // To heapify a subtree rooted with node i diff --git a/CPP/sorting/Implementing Red Black Tree b/CPP/sorting/Implementing Red Black Tree new file mode 100644 index 00000000..abdd8e2a --- /dev/null +++ b/CPP/sorting/Implementing Red Black Tree @@ -0,0 +1,426 @@ +// Implementing Red-Black Tree in C++ + +#include +using namespace std; + +struct Node { + int data; + Node *parent; + Node *left; + Node *right; + int color; +}; + +typedef Node *NodePtr; + +class RedBlackTree { + private: + NodePtr root; + NodePtr TNULL; + + void initializeNULLNode(NodePtr node, NodePtr parent) { + node->data = 0; + node->parent = parent; + node->left = nullptr; + node->right = nullptr; + node->color = 0; + } + + // Preorder + void preOrderHelper(NodePtr node) { + if (node != TNULL) { + cout << node->data << " "; + preOrderHelper(node->left); + preOrderHelper(node->right); + } + } + + // Inorder + void inOrderHelper(NodePtr node) { + if (node != TNULL) { + inOrderHelper(node->left); + cout << node->data << " "; + inOrderHelper(node->right); + } + } + + // Post order + void postOrderHelper(NodePtr node) { + if (node != TNULL) { + postOrderHelper(node->left); + postOrderHelper(node->right); + cout << node->data << " "; + } + } + + NodePtr searchTreeHelper(NodePtr node, int key) { + if (node == TNULL || key == node->data) { + return node; + } + + if (key < node->data) { + return searchTreeHelper(node->left, key); + } + return searchTreeHelper(node->right, key); + } + + // For balancing the tree after deletion + void deleteFix(NodePtr x) { + NodePtr s; + while (x != root && x->color == 0) { + if (x == x->parent->left) { + s = x->parent->right; + if (s->color == 1) { + s->color = 0; + x->parent->color = 1; + leftRotate(x->parent); + s = x->parent->right; + } + + if (s->left->color == 0 && s->right->color == 0) { + s->color = 1; + x = x->parent; + } else { + if (s->right->color == 0) { + s->left->color = 0; + s->color = 1; + rightRotate(s); + s = x->parent->right; + } + + s->color = x->parent->color; + x->parent->color = 0; + s->right->color = 0; + leftRotate(x->parent); + x = root; + } + } else { + s = x->parent->left; + if (s->color == 1) { + s->color = 0; + x->parent->color = 1; + rightRotate(x->parent); + s = x->parent->left; + } + + if (s->right->color == 0 && s->right->color == 0) { + s->color = 1; + x = x->parent; + } else { + if (s->left->color == 0) { + s->right->color = 0; + s->color = 1; + leftRotate(s); + s = x->parent->left; + } + + s->color = x->parent->color; + x->parent->color = 0; + s->left->color = 0; + rightRotate(x->parent); + x = root; + } + } + } + x->color = 0; + } + + void rbTransplant(NodePtr u, NodePtr v) { + if (u->parent == nullptr) { + root = v; + } else if (u == u->parent->left) { + u->parent->left = v; + } else { + u->parent->right = v; + } + v->parent = u->parent; + } + + void deleteNodeHelper(NodePtr node, int key) { + NodePtr z = TNULL; + NodePtr x, y; + while (node != TNULL) { + if (node->data == key) { + z = node; + } + + if (node->data <= key) { + node = node->right; + } else { + node = node->left; + } + } + + if (z == TNULL) { + cout << "Key not found in the tree" << endl; + return; + } + + y = z; + int y_original_color = y->color; + if (z->left == TNULL) { + x = z->right; + rbTransplant(z, z->right); + } else if (z->right == TNULL) { + x = z->left; + rbTransplant(z, z->left); + } else { + y = minimum(z->right); + y_original_color = y->color; + x = y->right; + if (y->parent == z) { + x->parent = y; + } else { + rbTransplant(y, y->right); + y->right = z->right; + y->right->parent = y; + } + + rbTransplant(z, y); + y->left = z->left; + y->left->parent = y; + y->color = z->color; + } + delete z; + if (y_original_color == 0) { + deleteFix(x); + } + } + + // For balancing the tree after insertion + void insertFix(NodePtr k) { + NodePtr u; + while (k->parent->color == 1) { + if (k->parent == k->parent->parent->right) { + u = k->parent->parent->left; + if (u->color == 1) { + u->color = 0; + k->parent->color = 0; + k->parent->parent->color = 1; + k = k->parent->parent; + } else { + if (k == k->parent->left) { + k = k->parent; + rightRotate(k); + } + k->parent->color = 0; + k->parent->parent->color = 1; + leftRotate(k->parent->parent); + } + } else { + u = k->parent->parent->right; + + if (u->color == 1) { + u->color = 0; + k->parent->color = 0; + k->parent->parent->color = 1; + k = k->parent->parent; + } else { + if (k == k->parent->right) { + k = k->parent; + leftRotate(k); + } + k->parent->color = 0; + k->parent->parent->color = 1; + rightRotate(k->parent->parent); + } + } + if (k == root) { + break; + } + } + root->color = 0; + } + + void printHelper(NodePtr root, string indent, bool last) { + if (root != TNULL) { + cout << indent; + if (last) { + cout << "R----"; + indent += " "; + } else { + cout << "L----"; + indent += "| "; + } + + string sColor = root->color ? "RED" : "BLACK"; + cout << root->data << "(" << sColor << ")" << endl; + printHelper(root->left, indent, false); + printHelper(root->right, indent, true); + } + } + + public: + RedBlackTree() { + TNULL = new Node; + TNULL->color = 0; + TNULL->left = nullptr; + TNULL->right = nullptr; + root = TNULL; + } + + void preorder() { + preOrderHelper(this->root); + } + + void inorder() { + inOrderHelper(this->root); + } + + void postorder() { + postOrderHelper(this->root); + } + + NodePtr searchTree(int k) { + return searchTreeHelper(this->root, k); + } + + NodePtr minimum(NodePtr node) { + while (node->left != TNULL) { + node = node->left; + } + return node; + } + + NodePtr maximum(NodePtr node) { + while (node->right != TNULL) { + node = node->right; + } + return node; + } + + NodePtr successor(NodePtr x) { + if (x->right != TNULL) { + return minimum(x->right); + } + + NodePtr y = x->parent; + while (y != TNULL && x == y->right) { + x = y; + y = y->parent; + } + return y; + } + + NodePtr predecessor(NodePtr x) { + if (x->left != TNULL) { + return maximum(x->left); + } + + NodePtr y = x->parent; + while (y != TNULL && x == y->left) { + x = y; + y = y->parent; + } + + return y; + } + + void leftRotate(NodePtr x) { + NodePtr y = x->right; + x->right = y->left; + if (y->left != TNULL) { + y->left->parent = x; + } + y->parent = x->parent; + if (x->parent == nullptr) { + this->root = y; + } else if (x == x->parent->left) { + x->parent->left = y; + } else { + x->parent->right = y; + } + y->left = x; + x->parent = y; + } + + void rightRotate(NodePtr x) { + NodePtr y = x->left; + x->left = y->right; + if (y->right != TNULL) { + y->right->parent = x; + } + y->parent = x->parent; + if (x->parent == nullptr) { + this->root = y; + } else if (x == x->parent->right) { + x->parent->right = y; + } else { + x->parent->left = y; + } + y->right = x; + x->parent = y; + } + + // Inserting a node + void insert(int key) { + NodePtr node = new Node; + node->parent = nullptr; + node->data = key; + node->left = TNULL; + node->right = TNULL; + node->color = 1; + + NodePtr y = nullptr; + NodePtr x = this->root; + + while (x != TNULL) { + y = x; + if (node->data < x->data) { + x = x->left; + } else { + x = x->right; + } + } + + node->parent = y; + if (y == nullptr) { + root = node; + } else if (node->data < y->data) { + y->left = node; + } else { + y->right = node; + } + + if (node->parent == nullptr) { + node->color = 0; + return; + } + + if (node->parent->parent == nullptr) { + return; + } + + insertFix(node); + } + + NodePtr getRoot() { + return this->root; + } + + void deleteNode(int data) { + deleteNodeHelper(this->root, data); + } + + void printTree() { + if (root) { + printHelper(this->root, "", true); + } + } +}; + +int main() { + RedBlackTree bst; + bst.insert(55); + bst.insert(40); + bst.insert(65); + bst.insert(60); + bst.insert(75); + bst.insert(57); + + bst.printTree(); + cout << endl + << "After deleting" << endl; + bst.deleteNode(40); + bst.printTree(); +} diff --git a/CPP/sorting/heap_sort.cpp b/CPP/sorting/heap_sort.cpp new file mode 100644 index 00000000..bdb808a9 --- /dev/null +++ b/CPP/sorting/heap_sort.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; +/* function to heapify a subtree. Here 'i' is the +index of root node in array a[], and 'n' is the size of heap. */ +void heapify(int a[], int n, int i) +{ + int largest = i; // Initialize largest as root + int left = 2 * i + 1; // left child + int right = 2 * i + 2; // right child + // If left child is larger than root + if (left < n && a[left] > a[largest]) + largest = left; + // If right child is larger than root + if (right < n && a[right] > a[largest]) + largest = right; + // If root is not largest + if (largest != i) { + // swap a[i] with a[largest] + int temp = a[i]; + a[i] = a[largest]; + a[largest] = temp; + + heapify(a, n, largest); + } +} +/*Function to implement the heap sort*/ +void heapSort(int a[], int n) +{ + + for (int i = n / 2 - 1; i >= 0; i--) + heapify(a, n, i); + // One by one extract an element from heap + for (int i = n - 1; i >= 0; i--) { + /* Move current root element to end*/ + // swap a[0] with a[i] + int temp = a[0]; + a[0] = a[i]; + a[i] = temp; + + heapify(a, i, 0); + } +} +/* function to print the array elements */ +void printArr(int a[], int n) +{ + for (int i = 0; i < n; ++i) + { + cout< +#include +#include +using namespace std; + +// Function to perform insertion sort on subarray `a[low…high]` +void insertionsort(int a[], int low, int high) +{ + // start from the second element in the subarray + // (the element at index `low` is already sorted) + for (int i = low + 1; i <= high; i++) + { + int value = a[i]; + int j = i; + + // find index `j` within the sorted subset a[0…i-1] + // where element a[i] belongs + while (j > low && a[j - 1] > value) + { + a[j] = a[j - 1]; + j--; + } + + // Note that the subarray `a[j…i-1]` is shifted to + // the right by one position, i.e., `a[j+1…i]` + + a[j] = value; + } +} + +// Function to partition the array using Lomuto partition scheme +int partition(int a[], int low, int high) +{ + // Pick the rightmost element as a pivot from the array + int pivot = a[high]; + + // elements less than the pivot will be pushed to the left of `pIndex` + // elements more than the pivot will be pushed to the right of `pIndex` + // equal elements can go either way + int pIndex = low; + + // each time we find an element less than or equal to the pivot, `pIndex` + // is incremented, and that element would be placed before the pivot. + for (int i = low; i < high; i++) + { + if (a[i] <= pivot) + { + swap(a[i], a[pIndex]); + pIndex++; + } + } + + // swap `pIndex` with pivot + swap (a[pIndex], a[high]); + + // return `pIndex` (index of the pivot element) + return pIndex; +} + +// Quicksort randomized partition to rearrange elements across pivot +int randPartition(int a[], int low, int high) +{ + // choose a random index between `[low, high]` + int pivotIndex = rand() % (high - low + 1) + low; + + // swap the end element with the element present at a random index + swap(a[pivotIndex], a[high]); + + // call the partition procedure + return partition(a, low, high); +} + +// Function to perform heapsort on the given range of elements +void heapsort(int *begin, int *end) +{ + make_heap(begin, end); + sort_heap(begin, end); +} + +// Function to perform introsort on the given array +void introsort(int a[], int *begin, int *end, int maxdepth) +{ + // perform insertion sort if partition size is 16 or smaller + if ((end - begin) < 16) { + insertionsort(a, begin - a, end - a); + } + // perform heapsort if the maximum depth is 0 + else if (maxdepth == 0) { + heapsort(begin, end + 1); + } + else { + // otherwise, perform Quicksort + int pivot = randPartition(a, begin - a, end - a); + introsort(a, begin, a + pivot - 1, maxdepth - 1); + introsort(a, a + pivot + 1, end, maxdepth - 1); + } +} + +int main() +{ + int a[] = { 5, 7, -8, 9, 10, 4, -7, 0, -12, 1, 6, 2, 3, -4, -15, 12 }; + int n = sizeof(a) / sizeof(a[0]); + + // get the maximum depth + int maxdepth = log(n) * 2; + + // sort the array using introsort the algorithm + introsort(a, a, a + n - 1, maxdepth); + + // print the sorted array + for (int i = 0; i < n; i++) { + cout << a[i] << " "; + } + + return 0; +} diff --git a/CPP/sorting/library_sort.cpp b/CPP/sorting/library_sort.cpp new file mode 100644 index 00000000..b48aefeb --- /dev/null +++ b/CPP/sorting/library_sort.cpp @@ -0,0 +1,90 @@ +#include +#include + +void librarySort(int *index, int n) { + int lib_size, index_pos, + *gaps, // gaps + *library[2]; // libraries + + bool target_lib, *numbered; + + for (int i = 0; i < 2; i++) + library[i] = new int[n]; + + gaps = new int[n + 1]; + numbered = new bool[n + 1]; + + lib_size = 1; + index_pos = 1; + target_lib = 0; + library[target_lib][0] = index[0]; + + while (index_pos < n) { + // binary search + int insert = std::distance( + library[target_lib], + std::lower_bound(library[target_lib], + library[target_lib] + lib_size, index[index_pos])); + + // if there is no gap to insert a new index ... + + if (numbered[insert] == true) { + int prov_size = 0, next_target_lib = !target_lib; + + // update library and clear gaps + + for (int i = 0; i <= n; i++) { + if (numbered[i] == true) { + library[next_target_lib][prov_size] = gaps[i]; + prov_size++; + numbered[i] = false; + } + + if (i <= lib_size) { + library[next_target_lib][prov_size] = + library[target_lib][i]; + prov_size++; + } + } + + target_lib = next_target_lib; + lib_size = prov_size - 1; + } else { + numbered[insert] = true; + gaps[insert] = index[index_pos]; + index_pos++; + } + } + + int index_pos_for_output = 0; + for (int i = 0; index_pos_for_output < n; i++) { + if (numbered[i] == true) { + // std::cout << gaps[i] << std::endl; + index[index_pos_for_output] = gaps[i]; + index_pos_for_output++; + } + + if (i < lib_size) { + // std::cout << library[target_lib][i] << std::endl; + index[index_pos_for_output] = library[target_lib][i]; + index_pos_for_output++; + } + } +} + +int main() { + // ---example-- + int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; + int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); + + librarySort(index_ex, n_ex); + std::cout << "sorted array :" << std::endl; + for (int i = 0; i < n_ex; i++) + std::cout << index_ex[i] << " "; + std::cout << std::endl; + + /* --output-- + sorted array : + -12 -8 -6 0 1 1 1 4 5 9 9 + */ +} diff --git a/CPP/sorting/radix_sort.cpp b/CPP/sorting/radix_sort.cpp new file mode 100644 index 00000000..919590ca --- /dev/null +++ b/CPP/sorting/radix_sort.cpp @@ -0,0 +1,66 @@ +// Radix Sort in C++ Programming + +#include +using namespace std; + +// Function to get the largest element from an array +int getMax(int array[], int n) { + int max = array[0]; + for (int i = 1; i < n; i++) + if (array[i] > max) + max = array[i]; + return max; +} + +// Using counting sort to sort the elements in the basis of significant places +void countingSort(int array[], int size, int place) { + const int max = 10; + int output[size]; + int count[max]; + + for (int i = 0; i < max; ++i) + count[i] = 0; + + // Calculate count of elements + for (int i = 0; i < size; i++) + count[(array[i] / place) % 10]++; + + // Calculate cumulative count + for (int i = 1; i < max; i++) + count[i] += count[i - 1]; + + // Place the elements in sorted order + for (int i = size - 1; i >= 0; i--) { + output[count[(array[i] / place) % 10] - 1] = array[i]; + count[(array[i] / place) % 10]--; + } + + for (int i = 0; i < size; i++) + array[i] = output[i]; +} + +// Main function to implement radix sort +void radixsort(int array[], int size) { + // Get maximum element + int max = getMax(array, size); + + // Apply counting sort to sort elements based on place value. + for (int place = 1; max / place > 0; place *= 10) + countingSort(array, size, place); +} + +// Print an array +void printArray(int array[], int size) { + int i; + for (i = 0; i < size; i++) + cout << array[i] << " "; + cout << endl; +} + +// Driver code +int main() { + int array[] = {121, 432, 564, 23, 1, 45, 788}; + int n = sizeof(array) / sizeof(array[0]); + radixsort(array, n); + printArray(array, n); +} diff --git a/CPP/sorting/randomised_quicksort.cpp b/CPP/sorting/randomised_quicksort.cpp new file mode 100644 index 00000000..ccf725f5 --- /dev/null +++ b/CPP/sorting/randomised_quicksort.cpp @@ -0,0 +1,75 @@ +#include +#include +#include + +using namespace std; + +// This function places all smaller +// to left of pivot and all greater +// elements to right of pivot +int partition(int arr[], int low, int high) { + int pivot = arr[high]; + + // Index of smaller element + int i = (low - 1); + + for (int j = low; j <= high - 1; j++) { + // If current element is smaller + // than or equal to pivot + if (arr[j] <= pivot) { + + // increment index of smaller element + i++; + swap(arr[i], arr[j]); + } + } + swap(arr[i + 1], arr[high]); + return (i + 1); +} + +// Generates Random Pivot, swaps pivot with end element +int partition_r(int arr[], int low, int high) { + // Generates random number + srand(time(NULL)); + int random = low + rand() % (high - low); + + // Swap A[random] with A[high] + swap(arr[random], arr[high]); + + return partition(arr, low, high); +} + +// Quicksort method +void quickSort(int arr[], int low, int high) { + if (low < high) { + int pIndex = partition_r(arr, low, high); + + // Separately sort elements before partition and after partition + quickSort(arr, low, pIndex - 1); + quickSort(arr, pIndex + 1, high); + } +} + +int main() { + int size; + cout << "Enter size of array: "; + cin >> size; + int arr[size]; + cout << "Enter contents of array:\n"; + for (int i = 0; i < size; i++) + cin >> arr[i]; + + cout << "\nUnsorted array:\n[ "; + for (int i = 0; i < size; i++) + cout << arr[i] << " "; + cout << "]\n"; + + quickSort(arr, 0, size - 1); + + cout << "Sorted array:\n[ "; + for (int i = 0; i < size; i++) + cout << arr[i] << " "; + cout << "]\n"; + + return 0; +} diff --git a/CPP/sorting/shellsort.cpp b/CPP/sorting/shellsort.cpp new file mode 100644 index 00000000..5ecfdd8e --- /dev/null +++ b/CPP/sorting/shellsort.cpp @@ -0,0 +1,31 @@ +#include + +#include + +void swap(int * x, int * y) { + int temp = * x; + * x = * y; + * y = temp; +} +void ShellSort(int A[], int n) { + int gap, i, j, temp; + for (gap = n / 2; gap >= 1; gap /= 2) { + for (i = gap; i < n; i++) { + temp = A[i]; + j = i - gap; + while (j >= 0 && A[j] > temp) { + A[j + gap] = A[j]; + j = j - gap; + } + A[j + gap] = temp; + } + } +} +int main() { + int A[] = {11,13,7,12,16,9,24,5,10,3}, n = 10, i; + SellSort(A, n); + for (i = 0; i < 10; i++) + printf("%d ", A[i]); + printf("\n"); + return 0; +} diff --git a/CPP/stl/List in STL b/CPP/stl/List in STL new file mode 100644 index 00000000..3ff73662 --- /dev/null +++ b/CPP/stl/List in STL @@ -0,0 +1,52 @@ +// CPP program to show the implementation of List +#include +#include +#include +using namespace std; + +// function for printing the elements in a list +void showlist(list g) +{ + list::iterator it; + for (it = g.begin(); it != g.end(); ++it) + cout << '\t' << *it; + cout << '\n'; +} + +// Driver Code +int main() +{ + + list gqlist1, gqlist2; + + for (int i = 0; i < 10; ++i) { + gqlist1.push_back(i * 2); + gqlist2.push_front(i * 3); + } + cout << "\nList 1 (gqlist1) is : "; + showlist(gqlist1); + + cout << "\nList 2 (gqlist2) is : "; + showlist(gqlist2); + + cout << "\ngqlist1.front() : " << gqlist1.front(); + cout << "\ngqlist1.back() : " << gqlist1.back(); + + cout << "\ngqlist1.pop_front() : "; + gqlist1.pop_front(); + showlist(gqlist1); + + cout << "\ngqlist2.pop_back() : "; + gqlist2.pop_back(); + showlist(gqlist2); + + cout << "\ngqlist1.reverse() : "; + gqlist1.reverse(); + showlist(gqlist1); + + cout << "\ngqlist2.sort(): "; + gqlist2.sort(); + showlist(gqlist2); + + return 0; +} diff --git a/CPP/structures/stack using linked list.cpp b/CPP/structures/stack using linked list.cpp new file mode 100644 index 00000000..ad42c2b3 --- /dev/null +++ b/CPP/structures/stack using linked list.cpp @@ -0,0 +1,86 @@ +#include +using namespace std; + +// Stack implementation using Linked List + + +// class for _stack +class _stack +{ + // private data----> + + + // node structure + struct node + { + int data; + node* next; + }; + node* head = NULL; + int n = 0;// for size of stack +public: + // public data----> + + + // push fuction + void push(int a) { + // making node + node* temp = new node(); + // check whether a stack overflows or not + if(temp==NULL){cout<<"Stack Overflow\n";return;} + + // adding nodes at the beginning of linkked list + temp->data = a; + temp->next = head; + head = temp; + n++;// increamenting size + } + + // pop function + void pop() { + // check stack is empty or not + if (head == NULL) {cout << "Empty stack\n"; return;} + // points temp node pointer to the top + node *temp = head; + // move head to next node + head = head->next; + // delete temp node pointer + delete(temp); + n--;// decreamenting size + } + + // top function + int top() { + // check stack is empty or not + if (head == NULL) {cout << "Empty stack"; return -1;} + // return top node data + return head->data; + } + + // stack emptly check function + bool isEmpty() { + if (head == NULL)return true; + else return false; + } + + // function for returning the size of stack + int size() { return n;} +}; + + + +int main() { + + + _stack s; + + // user/random inputs.. + for (int i = 0; i < 10; ++i) {int a; cin >> a; s.push(a); cout << s.top() << endl;} + s.pop(); + s.pop(); + cout << s.isEmpty() << endl; + cout << s.top() << endl; + s.push(121); + cout << s.top() << endl; + return 0; +} diff --git a/CSES/DP/BookShop_MEMO.cpp b/CSES/DP/BookShop_MEMO.cpp new file mode 100644 index 00000000..5cb7c097 --- /dev/null +++ b/CSES/DP/BookShop_MEMO.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + +int f(int idx, int tar, vector &cost, vector &weight,vector> &dp) { + if (idx == 0) { + if (tar >= cost[0]) return weight[0]; + return 0; + } + if (dp[idx][tar] != -1) return dp[idx][tar]; + int notake = f(idx-1,tar,cost,weight,dp); + int take = 0; + if (tar >= cost[idx]) take = f(idx-1,tar - cost[idx], cost, weight,dp) + weight[idx]; + return dp[idx][tar] = max(take , notake); +} + +void solve() { + int n, x; cin >> n >> x; + vector cost(n); cin >> cost; + vector weight(n); cin >> weight; + vector> dp(n+1,vector (x+1,-1)); + cout << f(n-1,x,cost,weight,dp) << '\n'; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/DP/BookShop_TABU.cpp b/CSES/DP/BookShop_TABU.cpp new file mode 100644 index 00000000..afdeecf5 --- /dev/null +++ b/CSES/DP/BookShop_TABU.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + +void solve() { + int n, x; cin >> n >> x; + vector cost(n); cin >> cost; + vector weight(n); cin >> weight; + vector> dp(n+1,vector (x+1,-1)); + + for (int i = 0; i <= x; ++i) { + if (i >= cost[0]) { + dp[0][i] = weight[0]; + } else dp[0][i] = 0; + } + + for (int i = 1; i < n; ++i) { + for (int tar = 1; tar <=x; ++tar) { + int notake = dp[i-1][tar]; + int take = 0; + if (tar >= cost[i]) take = dp[i-1][tar-cost[i]] + weight[i]; + dp[i][tar] = max(take,notake); + } + } + cout << dp[n-1][x]; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/DP/DiceCombination.cpp b/CSES/DP/DiceCombination.cpp new file mode 100644 index 00000000..d78a964f --- /dev/null +++ b/CSES/DP/DiceCombination.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) +#define nline '\n' + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T a,T b) {return a > b ? a : b;} +tcU> T min(T a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + +void solve() { + int n; cin >> n; + vector dp(n+1,0); + dp[0] = 1; + dp[1] = 1; + for (int i = 2; i <= n; ++i) { + ll ways = 0; + for (int k = 1; k <= 6; ++k) { + if ((i-k) >= 0) { + (ways += dp[i-k]) %= mod; + } + } + (dp[i] = ways) %= mod; + } + cout << dp[n] % mod << '\n'; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + /* cin >> T; */ + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} diff --git a/CSES/DP/GridPaths.cpp b/CSES/DP/GridPaths.cpp new file mode 100644 index 00000000..3e0090e3 --- /dev/null +++ b/CSES/DP/GridPaths.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + +int f(int i,int k,vector> &grid,vector> &dp) { + if (i < 0 || k < 0 ) return 0; + if (i == 0 && k == 0 && grid[i][k] != '*') return 1; + + if (grid[i][k] == '*') return 0; + if (dp[i][k] != -1) return dp[i][k]; + int one = f(i-1,k,grid,dp) % mod; + int second = f(i,k-1,grid,dp) % mod; + return (dp[i][k] = (one + second) %mod) %= mod; +} + +void solve() { + int N; cin >> N; + vector> grid(N,vector (N)); + vector> dp(N+1,vector (N+1,-1)); + rep(i,0,N) { + rep(k,0,N) { + cin >> grid[i][k]; + } + } + cout << f(N-1,N-1,grid,dp) << '\n'; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/DP/MinimizingCoins.cpp b/CSES/DP/MinimizingCoins.cpp new file mode 100644 index 00000000..054cfc97 --- /dev/null +++ b/CSES/DP/MinimizingCoins.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) +#define nline '\n' + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + +void solve() { + ll n, x; cin >> n >> x; + vector coins(n); + cin >> coins; + + vectorprev(x + 1,0); + for (ll i = 0; i <= x; ++i) { + if (i % coins[0] == 0 ) prev[i] = i / coins[0]; + else prev[i] = 1e9; + } + for (ll i = 1; i < n; ++i) { + vector cur(x + 1, 0); + for (ll tar = 1; tar <= x; ++tar) { + ll take = 1e9; + if (tar >= coins[i]) take = cur[tar-coins[i]] + 1; + ll notake = prev[tar]; + cur[tar] = min(take,notake); + } + prev = cur; + } + cout << (prev[x] == 1e9 ? -1 : prev[x]) << '\n'; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + /* cin >> T; */ + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/DP/RemovingDigits.cpp b/CSES/DP/RemovingDigits.cpp new file mode 100644 index 00000000..f318858d --- /dev/null +++ b/CSES/DP/RemovingDigits.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +int f(int N,vector &dp) { + if (N <= 0) return 0; + + if (dp[N] != -1) return dp[N]; + + int ans = INT_MAX; + int temp = N; + while (temp != 0){ + int rem = temp % 10; + if (rem != 0) { + int ways = f(N-rem,dp) + 1; + ans = min(ans,ways); + } + temp/=10; + } + return dp[N] = ans; +} + +void solve() { + int N; cin >> N; + vector dp(N+1,-1); + cout << f(N,dp) << std::endl; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/DP/coinCombinations1.cpp b/CSES/DP/coinCombinations1.cpp new file mode 100644 index 00000000..fec5500a --- /dev/null +++ b/CSES/DP/coinCombinations1.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + + +void solve() { + ll n, x; cin >> n >> x; + vector coins(n); cin >> coins; + + vector prev(x + 1,0); + prev[0] = 1; + + for (int tar = 1; tar <= x; ++tar) { + for (int idx = 0; idx < n; ++idx) { + if (tar - coins[idx] >= 0) (prev[tar] += prev[tar-coins[idx]] % mod) %= mod; + } + } + cout << prev[x] << '\n'; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/DP/coinCombinations2.cpp b/CSES/DP/coinCombinations2.cpp new file mode 100644 index 00000000..3b58a252 --- /dev/null +++ b/CSES/DP/coinCombinations2.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +using ll = long long; +using ld = long double; +#define tcU template using V = vector; +#define rep(i,a,b) for(int i=a;i=a;i--) +#define sz(a) (int)(a.size()) +#define all(a) a.begin(),a.end() +#define precision(n) cout << fixed << setprecision(n) + +void setIO(string s) { freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } +const int mod = 1e9 + 7; +tcU> T max(T &a,T b) {return a > b ? a : b;} +tcU> T min(T &a, T b) { return a > b ? b : a;} + +template // cin >> pair +istream &operator>>(istream &istream, pair &p) { return (istream >> p.first >> p.second); } +tcU> // cin >> vector +istream &operator>>(istream &istream, vector &v) { for (auto &it : v) { cin >> it; } return istream; } +template // cout << pair +ostream &operator<<(ostream &ostream, const pair &p) { return (ostream << p.first << " " << p.second); } +tcU> // cout << vector +ostream &operator<<(ostream &ostream, const vector &c) { for (auto &it : c) { cout << it << " "; } return ostream; } + + +void solve() { + ll n, x; cin >> n >> x; + vector coins(n); cin >> coins; + + vector prev(x + 1,0); + prev[0] = 1; + + for (int idx = 0; idx < n; ++idx) { + for (int tar = 1; tar <= x; ++tar) { + if (tar - coins[idx] >= 0) (prev[tar] += prev[tar-coins[idx]] % mod) %= mod; + } + } + cout << prev[x] << '\n'; +} + +signed main() { + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T = 1; + rep(i,1,T+1){ + /* cout << "Case #" << i << ": "; */ + solve(); + } + return 0; +} + diff --git a/CSES/Intro/CheesboardAndQueens.cc b/CSES/Intro/CheesboardAndQueens.cc new file mode 100644 index 00000000..af2632a2 --- /dev/null +++ b/CSES/Intro/CheesboardAndQueens.cc @@ -0,0 +1,54 @@ +#include +using namespace::std; +#define N 8 + +char grid[8][8]; +static int cnt = 0; + +bool is_safe(int row,int col){ + int i, j; + + /* Check this row on left side */ + for (i = 0; i < col; i++) + if (grid[row][i] == 'G') + return false; + + /* Check upper diagonal on left side */ + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) + if (grid[i][j] == 'G') + return false; + + /* Check lower diagonal on left side */ + for (i = row, j = col; j >= 0 && i < N; i++, j--) + if (grid[i][j] == 'G') + return false; + + return true; +} + +void dfs(int row,int col) { + if (col >= N) { cnt++; return; } + + for (int i = 0; i < 8; ++i) { + if (grid[i][col] != '*' && is_safe(i,col)) { + grid[i][col] = 'G'; + dfs(i,col+1); + grid[i][col] = '.'; + } + } +} + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + for(int i = 0; i < 8; ++i) { + for (int j = 0; j < 8; ++j) { + cin >> grid[i][j]; + } + } + dfs(0,0); + cout << cnt << endl; + return 0; +} + + diff --git a/CSES/Intro/CoinPiles.cc b/CSES/Intro/CoinPiles.cc new file mode 100644 index 00000000..dd8cce25 --- /dev/null +++ b/CSES/Intro/CoinPiles.cc @@ -0,0 +1,22 @@ +#include +using namespace std; + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int T; cin >> T; + while (T--) { + int a, b; cin >> a >> b; + if(a 2 * b) { + cout << "NO\n"; + } else if ((a + b) % 3 == 0) { + cout << "YES\n"; + } else { + cout << "NO\n"; + } + } + return 0; +} + diff --git a/CSES/Intro/DigitQueries.cc b/CSES/Intro/DigitQueries.cc new file mode 100644 index 00000000..2c2cd952 --- /dev/null +++ b/CSES/Intro/DigitQueries.cc @@ -0,0 +1,41 @@ +#include +using namespace::std; + +int64_t power(int64_t x,int64_t y) { + int64_t res = 1; + while (y > 0) { + if (y & 1) res = res * x; + y = y >> 1; + x = (x * x); + } + return res; +} + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int Q; cin >> Q; + while (Q--) { + int64_t K; cin >> K; + int64_t n = 1, sum = 0; + + while (K >= sum) { + sum = sum + 9 * n * power(10,n-1); + n++; + } + n--; + + // Digits away + int64_t away = (sum - K) / n; + int64_t rem = (sum - K) % n; + + // calculate Number + int64_t number = (power(10,n) - 1) - away; + + string No = to_string(number); + cout << No[(No.length() - 1 - rem)] << endl; + } + return 0; +} + + diff --git a/CSES/Intro/GrayCode.cc b/CSES/Intro/GrayCode.cc new file mode 100644 index 00000000..0d02f04f --- /dev/null +++ b/CSES/Intro/GrayCode.cc @@ -0,0 +1,18 @@ +#include +using namespace std; + +int main(){ + int N; cin >> N; + for(int i = 0; i <(1<>1)); + bitset<32>B = GC; + for(int k = 0; k < N; ++k) { + cout << B[k]; + } + cout << '\n'; + } + return 0; +} + +// 00, 01, 11, 10 +// 0th, 1th, 2th, 3th diff --git a/CSES/Intro/GridPaths.cc b/CSES/Intro/GridPaths.cc new file mode 100644 index 00000000..c088d48d --- /dev/null +++ b/CSES/Intro/GridPaths.cc @@ -0,0 +1,64 @@ +#include +using namespace::std; + +static int cnt = 0; +bool vis[7][7]; +string s; + +// pruning +bool e(int i,int j) { return (i >= 0 && i < 7 && j < 7 && j >=0 && !vis[i][j]); } + +void dfs(int i,int j,int idx) { + if (i == 6 && j == 0) { + if (idx == 48) cnt++; + return; // optimisation 2 + } + if (vis[i][j] == true) return; + vis[i][j] = true; + if (s[idx] == '?' || s[idx] == 'L') { + if (j && !vis[i][j-1]) { + if ((e(i,j-2)==false && e(i+1,j-1) && e(i-1,j-1)) == false){ + dfs(i,j-1,idx+1); + } + } + } + if (s[idx] == '?' || s[idx] == 'R') { + if (j < 6 && !vis[i][j+1]) { + if ((e(i,j+2) == false && e(i+1,j+1) && e(i-1,j+1)) == false) { + dfs(i,j+1,idx+1); + } + } + } + if (s[idx] == '?' || s[idx] == 'U'){ + if (i && !vis[i-1][j]) { + if ((e(i-2,j) == false && e(i-1,j+1) && e(i-1,j-1)) == false) { + dfs(i-1,j,idx+1); + } + } + } + if (s[idx] == '?' || s[idx] == 'D') { + if (i < 6 && !vis[i+1][j]) { + if ((e(i+2,j) == false && e(i+1,j+1) && e(i+1,j-1)) == false) { + dfs(i+1,j,idx+1); + } + } + } + + vis[i][j] = false; // backtrack +} + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + cin >> s; + dfs(0,0,0); + cout << cnt << endl; + return 0; +} + + +// we only done 2 optimisation +// 1st is if we have reached at the end early then return OPT1 +// 2nd if we reached at the wall end and only can move right or left then return OPT2 +//3rd if can move only left and right and already visited one then return +//4th if diagonal already visited return diff --git a/CSES/Intro/Palindrome.cc b/CSES/Intro/Palindrome.cc new file mode 100644 index 00000000..4b577157 --- /dev/null +++ b/CSES/Intro/Palindrome.cc @@ -0,0 +1,35 @@ +#include +using namespace std; + +int main(){ + string s; cin >> s; + mapm; + for (auto i : s) m[i]++; + + int odd = 0; + char L; + for (auto i : m) { + if (i.second % 2 != 0) { + L = i.first; + odd++; + } + } + if (odd > 1) { + cout << "NO SOLUTION\n"; + } else { + string ans=""; + if (odd !=0) ans.push_back(L); + for (auto i : m) { + string R(i.second/2, i.first); + string C = R; + C += ans; + ans = C; + reverse(R.begin(),R.end()); + ans += R; + } + cout << ans << '\n'; + } + return 0; +} + + diff --git a/CSES/Intro/TowerH.cc b/CSES/Intro/TowerH.cc new file mode 100644 index 00000000..a7ed5d78 --- /dev/null +++ b/CSES/Intro/TowerH.cc @@ -0,0 +1,31 @@ +#include +using namespace::std; +int cnt = 0; +vector> ans; + +void f(int n,int from,int to,int aux) { + if (n == 0) return; + cnt++; + f(n-1,from,aux,to); + ans.push_back({from,to}); + f(n-1,aux,to,from); +} + +int solve(int n) { + f(n,1,3,2); + return cnt; +} + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n; cin >> n; + cout << solve(n) << endl; + for (auto i : ans) { + cout << i.first << " " << i.second << endl; + } + cout << endl; + return 0; +} + + diff --git a/CSES/Intro/TwoSets.cpp b/CSES/Intro/TwoSets.cpp new file mode 100644 index 00000000..c9510eb0 --- /dev/null +++ b/CSES/Intro/TwoSets.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n; cin >> n; + int sum = (n*(n+1))/2; + if (sum % 2 != 0) { + cout << "NO\n"; + exit(0); + } + if (n <= 3) { + cout << "YES\n"; + cout <<"2" << '\n'; + cout << "1 2" << '\n'; + cout << "1" << '\n'; + cout << "3" << '\n'; + exit(0); + } + + vector one,second; + if (n % 2 == 0) { + for(int i = 1; i <= n; ++i) { + if (i % 4 == 0 || i % 4 == 1) { + one.push_back(i); + } else { + second.push_back(i); + } + } + } else { + one.push_back(1); + one.push_back(2); + second.push_back(3); + for (int i = 1; i <= n - 3; ++i) { + if (i % 4 == 0 || i % 4 == 1) { + one.push_back(i + 3); + } else { + second.push_back(i + 3); + } + } + } + + cout << "YES\n"; + cout << one.size() << '\n'; + for (auto i : one) cout << i << " "; + cout << '\n'; + cout << second.size() << '\n'; + for (auto i : second) cout << i << " "; + cout << '\n'; + return 0; +} + + diff --git a/CSES/Intro/a.out b/CSES/Intro/a.out new file mode 100755 index 00000000..56c82ca3 Binary files /dev/null and b/CSES/Intro/a.out differ diff --git a/CSES/Sorting/CollectionNumbers.cc b/CSES/Sorting/CollectionNumbers.cc new file mode 100644 index 00000000..e14db5cf --- /dev/null +++ b/CSES/Sorting/CollectionNumbers.cc @@ -0,0 +1,22 @@ +#include "bits/stdc++.h" +#define int long long +using namespace::std; + +signed main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n; cin >> n; + std::vector v(n); + mapm; + int ans = 1; + for (int &x: v) cin >> x, --x; + for (int i = 0; i < n; ++i) { m[v[i]] = i; } + for (int i = 1; i < n; ++i) { + ans += (m[i] < m[i-1]); + } + cout << ans << endl; + return 0; +} + +// main observation is +// if a number x come before x + 1 then no extra move required but otherwise we need extra move diff --git a/CSES/Sorting/CollectionNumbers2.cc b/CSES/Sorting/CollectionNumbers2.cc new file mode 100644 index 00000000..152ebd9d --- /dev/null +++ b/CSES/Sorting/CollectionNumbers2.cc @@ -0,0 +1,30 @@ +#include "bits/stdc++.h" +#define int long long +using namespace::std; + +signed main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n,q; cin >> n >> q; + std::vector v(n); + for (int &x: v) cin >> x, --x; + while (q--) { + int a, b; cin >> a >> b; + --a,--b; + swap(v[a],v[b]); + mapm; + int ans = 1; + + for (int i = 0; i < n; ++i) { m[v[i]] = i; } + for (int i = 1; i < n; ++i) { + ans += (m[i] < m[i-1]); + } + cout << ans << endl; + } + return 0; +} + +// bruteforce +// 4 2 1 5 3 +// 4 1 2 5 3 swap(i,k) +// a[i] and a[k] made affect on a[i-1] a[k-1] and a[i+1] a[k+1] diff --git a/CSES/Sorting/Concert.cc b/CSES/Sorting/Concert.cc new file mode 100644 index 00000000..08c8115e --- /dev/null +++ b/CSES/Sorting/Concert.cc @@ -0,0 +1,32 @@ +#include +using namespace::std; +#define endl '\n' + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n, m; cin >> n >> m; + multiset x; + for (int i = 0; i < n; ++i) { + int l; cin >> l; + x.insert(l); + } + + for (int i = 0; i < m; ++i) { + int val; cin >> val; + auto it = x.upper_bound(val); + if (it == x.begin()) { + cout << -1 << endl; + } else { + --it; + cout << *it << endl; + x.erase(it); + } + } + return 0; +} + + +// 5 3 7 8 5 +// 4 8 3 +// 3 5 5 7 8 diff --git a/CSES/Sorting/MaximumSubarraySum.cc b/CSES/Sorting/MaximumSubarraySum.cc new file mode 100644 index 00000000..cd174430 --- /dev/null +++ b/CSES/Sorting/MaximumSubarraySum.cc @@ -0,0 +1,23 @@ +#include +using namespace::std; +#define endl '\n' +#define rep(i,a,b) for(int i=a; i < (b); ++i) +#define int long long + +int32_t main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int ans = -1e10; + int curr = 0; + int n; cin >> n; + vector v(n); + rep(i,0,n) cin >> v[i]; + rep(i,0,n) { + curr = max(v[i], curr + v[i]); + ans = max(ans, curr); + } + cout << ans << endl; + return 0; +} + + diff --git a/CSES/Sorting/MissingCoinSum.cc b/CSES/Sorting/MissingCoinSum.cc new file mode 100644 index 00000000..7c2c2369 --- /dev/null +++ b/CSES/Sorting/MissingCoinSum.cc @@ -0,0 +1,31 @@ +#include +using namespace::std; +#define endl '\n' +#define rep(i,a,b) for(int i=a; i < (b); ++i) +#define int long long + +int32_t main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n; cin >> n; + vector V(n); rep(i,0,n) cin>> V[i]; + sort(V.begin(),V.end()); + int res = 1; + if (V[0] != 1) { + cout << 1 << endl; + exit(0); + } + for (int i = 0; i < n && V[i] <= res; ++i) { + res += V[i]; + } + cout << res << endl; + return 0; +} +// 1 2 2 7 9 +// Solution :- +// we first check if we have a[0] = 1 then we can make sum = 1 else answer = 1 +// we move ahead and now we have (1, [1] + 2 => [3] ) => { 1, 2 ,3 } sum we can make from a[0] to a[2] +// now similarly +// a[2] => [1,2,3] + 2 => 3,4,5 +// a[3] => [1,2,3,4] + 7 => 8,9,10,11 so answer = 6 +//https://medium.com/dexters-lab/eli5-find-the-smallest-positive-integer-value-that-cannot-be-represented-as-sum-of-any-subset-of-f8ea2488184b diff --git a/CSES/Sorting/Playlist.cc b/CSES/Sorting/Playlist.cc new file mode 100644 index 00000000..43f40f09 --- /dev/null +++ b/CSES/Sorting/Playlist.cc @@ -0,0 +1,33 @@ +#include "bits/stdc++.h" +#define int long long +using namespace::std; + +signed main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n; cin >> n; + vector v(n); + mapm; + for(int i = 0; i < n; ++i) { + cin >> v[i]; + } + int ans = 0; + m[v[0]] = 1; + int cnt = 0; + for(int i = 1; i < n; ++i) { + if (m.find(v[i])!=m.end()) { + cnt++; + ans = max(ans,m[v[i-1]]); + m[v[i]] = (m[v[i-1]] + cnt - m[v[i]]); + } else { + m[v[i]] = m[v[i-1]] + 1; + } + } + ans = max(ans,m[v[n-1]]); + cout << ans << endl; + return 0; +} + +// 1 2 1 3 7 4 2 +// 1 2 | 3,4,5, ans = 5, 5 - 2=> 3 +// (3-1) diff --git a/CSES/Sorting/Restaurant.cc b/CSES/Sorting/Restaurant.cc new file mode 100644 index 00000000..e2e06630 --- /dev/null +++ b/CSES/Sorting/Restaurant.cc @@ -0,0 +1,25 @@ +#include "bits/stdc++.h" +#define int long long +using namespace::std; + +signed main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n; cin >> n; + vector> v; + for (int i = 0; i < n; ++i) { + int start, end; cin >> start >> end; + v.push_back({start,+1}); + v.push_back({end,-1}); + } + sort(v.begin(),v.end()); + vector prefix(v.size()+1); + prefix[0] = v[0].second; + for (int i = 1; i < v.size(); ++i) { + prefix[i] = prefix[i-1] + v[i].second; + } + cout << *max_element(prefix.begin(),prefix.end()) << endl; + return 0; +} + + diff --git a/CSES/Sorting/SumOfTwoValues.cc b/CSES/Sorting/SumOfTwoValues.cc new file mode 100644 index 00000000..fe0e59a2 --- /dev/null +++ b/CSES/Sorting/SumOfTwoValues.cc @@ -0,0 +1,28 @@ +#include +using namespace::std; +#define endl '\n' +#define rep(i,a,b) for(int i=a; i < (b); ++i) + +int main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int n, x; cin >> n >> x; + mapm; + vector V; + rep(i,0,n){ + int v; cin >> v; + V.push_back(v); + m[v] = i; + } + + rep(i,0,n) { + if (m.find(x - V[i]) != m.end() && m[x-V[i]]!=i) { + cout << i+ 1 << " " << m[x-V[i]] + 1 << endl; + exit(0); + } + } + cout << "IMPOSSIBLE" << endl; + return 0; +} + + diff --git a/CSES/Sorting/Traffic_lights.cc b/CSES/Sorting/Traffic_lights.cc new file mode 100644 index 00000000..a38b3405 --- /dev/null +++ b/CSES/Sorting/Traffic_lights.cc @@ -0,0 +1,32 @@ +#include "bits/stdc++.h" +#define int long long +using namespace::std; + +signed main(){ + ios_base::sync_with_stdio(false),cin.tie(nullptr); + + int x, n; cin >> x >> n; + set lights{0,x}; + multisetdist{x}; + + for(int i = 0; i < n; ++i){ + int pos; cin >> pos; + auto it1 = lights.upper_bound(pos); + auto it2 = it1; + --it2; + + dist.erase(dist.find(*it1 - *it2)); + dist.insert(pos - *it2); + dist.insert(*it1 - pos); + lights.insert(pos); + + auto ans = dist.end(); + --ans; + cout << *ans << " "; + } + return 0; +} +// if our max is on left side and element add on right no affect else affect +// 1 2 3 4 5 6 7 8 +// 3 +// 1 2 | 4 5 6 7 8 diff --git a/CSES/Sorting/a.out b/CSES/Sorting/a.out new file mode 100755 index 00000000..24b27f30 Binary files /dev/null and b/CSES/Sorting/a.out differ diff --git a/CSharp/Programming Skills 1/average-salary-excluding-the-minimum-and-maximum-salary-1491.cs b/CSharp/Programming Skills 1/average-salary-excluding-the-minimum-and-maximum-salary-1491.cs new file mode 100644 index 00000000..1ab320cd --- /dev/null +++ b/CSharp/Programming Skills 1/average-salary-excluding-the-minimum-and-maximum-salary-1491.cs @@ -0,0 +1,10 @@ +public class Solution { + public double Average(int[] salary) { + Array.Sort(salary); + int sum = 0; + for (int i = 1; i < salary.Length - 1; i++) + sum += salary[i]; + double avgSalary = Convert.ToDouble(sum.ToString("N3")) / (salary.Length - 2); + return Math.Floor(avgSalary * 100000) / 100000; + } +} \ No newline at end of file diff --git a/CSharp/Programming Skills 1/count-odd-numbers-in-an-interval-range-1523.cs b/CSharp/Programming Skills 1/count-odd-numbers-in-an-interval-range-1523.cs new file mode 100644 index 00000000..fbadc926 --- /dev/null +++ b/CSharp/Programming Skills 1/count-odd-numbers-in-an-interval-range-1523.cs @@ -0,0 +1,10 @@ +public class Solution { + public int CountOdds(int low, int high) { + int count = 0; + for (int i = low; i <= high; i++) + if (i % 2 == 1) + count++; + + return count; + } +} \ No newline at end of file diff --git a/DSA Javascript/Stack_Using_Singly_Linked_List.js b/DSA Javascript/Stack_Using_Singly_Linked_List.js new file mode 100644 index 00000000..fb1c779d --- /dev/null +++ b/DSA Javascript/Stack_Using_Singly_Linked_List.js @@ -0,0 +1,83 @@ +//Stack using linkedlist +function stackUsingLL(){ + //Node + let Node = function(elm){ + this.element = elm; + this.next = null; + } + + //To keep track of the size + let length = 0; + + //To keep track of the list + let head = null; + + //Push data in the stack + this.push = function(elm){ + //Create a new node + let node = new Node(elm), + current; + + //Add the new node at the top + current = head; + node.next = current; + head = node; + + length++; + } + + //Pop the item from the stack + this.pop = function(){ + let current = head; + + //If there is item then remove it + //and make the next element as the first + if(current){ + let elm = current.element; + current = current.next; + head = current; + length--; + return elm; + } + + return null; + } + + //Return the first element in the stack + this.peek = function(){ + if(head){ + return head.element; + } + + return null; + } + + //Convert the stack to an array + this.toArray = function(){ + let arr = []; + let current = head; + while(current){ + arr.push(current.element); + current = current.next; + } + + return arr; + } + + //Check if stack is empty + this.isEmpty = function(){ + return length === 0; + } + + //Return the size of the stack + this.size = function(){ + return length; + } + + //Clear the stack + this.clear = function(){ + head = null; + length = 0; + } + +} diff --git a/DSA Javascript/linked_list.js b/DSA Javascript/linked_list.js new file mode 100644 index 00000000..c440d575 --- /dev/null +++ b/DSA Javascript/linked_list.js @@ -0,0 +1,230 @@ +class Node { + // constructor + constructor(element) { + this.element = element; + this.next = null + } +} +// linkedlist class +class LinkedList { + constructor() { + this.head = null; + this.size = 0; + } + + // adds an element at the end + // of list + add(element) { + // creates a new node + var node = new Node(element); + + // to store current node + var current; + + // if list is Empty add the + // element and make it head + if (this.head == null) + this.head = node; + else { + current = this.head; + + // iterate to the end of the + // list + while (current.next) { + current = current.next; + } + + // add node + current.next = node; + } + this.size++; + } + + // insert element at the position index + // of the list + insertAt(element, index) { + if (index < 0 || index > this.size) + return console.log("Please enter a valid index."); + else { + // creates a new node + var node = new Node(element); + var curr, prev; + + curr = this.head; + + // add the element to the + // first index + if (index == 0) { + node.next = this.head; + this.head = node; + } else { + curr = this.head; + var it = 0; + + // iterate over the list to find + // the position to insert + while (it < index) { + it++; + prev = curr; + curr = curr.next; + } + + // adding an element + node.next = curr; + prev.next = node; + } + this.size++; + } + } + + // removes an element from the + // specified location + removeFrom(index) { + if (index < 0 || index >= this.size) + return console.log("Please Enter a valid index"); + else { + var curr, prev, it = 0; + curr = this.head; + prev = curr; + + // deleting first element + if (index === 0) { + this.head = curr.next; + } else { + // iterate over the list to the + // position to removce an element + while (it < index) { + it++; + prev = curr; + curr = curr.next; + } + + // remove the element + prev.next = curr.next; + } + this.size--; + + // return the remove element + return curr.element; + } + } + + // removes a given element from the + // list + removeElement(element) { + var current = this.head; + var prev = null; + + // iterate over the list + while (current != null) { + // comparing element with current + // element if found then remove the + // and return true + if (current.element === element) { + if (prev == null) { + this.head = current.next; + } else { + prev.next = current.next; + } + this.size--; + return current.element; + } + prev = current; + current = current.next; + } + return -1; + } + + + // finds the index of element + indexOf(element) { + var count = 0; + var current = this.head; + + // iterate over the list + while (current != null) { + // compare each element of the list + // with given element + if (current.element === element) + return count; + count++; + current = current.next; + } + + // not found + return -1; + } + + // checks the list for empty + isEmpty() { + return this.size == 0; + } + + // gives the size of the list + size_of_list() { + console.log(this.size); + } + + + // prints the list items + printList() { + var curr = this.head; + var str = ""; + while (curr) { + str += curr.element + " "; + curr = curr.next; + } + console.log(str); + } + +} + +// creating an object for the +// Linkedlist class +var ll = new LinkedList(); + +// testing isEmpty on an empty list +// returns true +console.log(ll.isEmpty()); + +// adding element to the list +ll.add(10); + +// prints 10 +ll.printList(); + +// returns 1 +console.log(ll.size_of_list()); + +// adding more elements to the list +ll.add(20); +ll.add(30); +ll.add(40); +ll.add(50); + +// returns 10 20 30 40 50 +ll.printList(); + +// prints 50 from the list +console.log("is element removed ?" + ll.removeElement(50)); + +// prints 10 20 30 40 +ll.printList(); + +// returns 3 +console.log("Index of 40 " + ll.indexOf(40)); + +// insert 60 at second position +// ll contains 10 20 60 30 40 +ll.insertAt(60, 2); + +ll.printList(); + +// returns false +console.log("is List Empty ? " + ll.isEmpty()); + +// remove 3rd element from the list +console.log(ll.removeFrom(3)); + +// prints 10 20 60 40 +ll.printList(); diff --git a/DSA android fingerprint/android fingerprint dsa algorithm.java b/DSA android fingerprint/android fingerprint dsa algorithm.java new file mode 100644 index 00000000..459dda0a --- /dev/null +++ b/DSA android fingerprint/android fingerprint dsa algorithm.java @@ -0,0 +1,146 @@ +package com.paulsofts.gfgfingerprintauthentication; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; + +import android.Manifest; +import android.annotation.TargetApi; +import android.app.KeyguardManager; +import android.content.pm.PackageManager; +import android.hardware.fingerprint.FingerprintManager; +import android.os.Build; +import android.os.Bundle; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyPermanentlyInvalidatedException; +import android.security.keystore.KeyProperties; +import android.widget.TextView; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; + +public class MainActivity extends AppCompatActivity { + + private KeyStore keyStore; + // Defining variable for storing + // key in android keystore container + private static final String KEY_NAME = "CaptainSandeep"; + private Cipher cipher; + private TextView errorText; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + // Initializing KeyguardManager and FingerprintManager + KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); + FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE); + + // Initializing our error text + errorText = (TextView) findViewById(R.id.errorText); + + // Here, we are using various security checks + // Checking device is inbuilt with fingerprint sensor or not + if(!fingerprintManager.isHardwareDetected()){ + + // Setting error message if device + // doesn't have fingerprint sensor + errorText.setText("Device does not support fingerprint sensor"); + }else { + // Checking fingerprint permission + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { + errorText.setText("Fingerprint authentication is not enabled"); + }else{ + // Check for at least one registered finger + if (!fingerprintManager.hasEnrolledFingerprints()) { + errorText.setText("Register at least one finger"); + }else{ + // Checking for screen lock security + if (!keyguardManager.isKeyguardSecure()) { + errorText.setText("Screen lock security not enabled"); + }else{ + + // if everything is enabled and correct then we will generate + // the encryption key which will be stored on the device + generateKey(); + if (cipherInit()) { + FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); + FingerprintHandler helper = new FingerprintHandler(this); + helper.startAuth(fingerprintManager, cryptoObject); + } + } + } + } + } + } + + + @TargetApi(Build.VERSION_CODES.M) + protected void generateKey() { + try { + keyStore = KeyStore.getInstance("AndroidKeyStore"); + } catch (Exception e) { + e.printStackTrace(); + } + + + KeyGenerator keyGenerator; + try { + keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + } catch (NoSuchAlgorithmException | NoSuchProviderException e) { + throw new RuntimeException("KeyGenerator instance failed", e); + } + + try { + keyStore.load(null); + keyGenerator.init(new + KeyGenParameterSpec.Builder(KEY_NAME, + KeyProperties.PURPOSE_ENCRYPT | + KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_CBC) + .setUserAuthenticationRequired(true) + .setEncryptionPaddings( + KeyProperties.ENCRYPTION_PADDING_PKCS7) + .build()); + keyGenerator.generateKey(); + } catch (NoSuchAlgorithmException | + InvalidAlgorithmParameterException + | CertificateException | IOException e) { + throw new RuntimeException(e); + } + } + + + @TargetApi(Build.VERSION_CODES.M) + public boolean cipherInit() { + try { + cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); + } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { + throw new RuntimeException("Cipher failed", e); + } + + try { + keyStore.load(null); + SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, + null); + cipher.init(Cipher.ENCRYPT_MODE, key); + return true; + } catch (KeyPermanentlyInvalidatedException e) { + return false; + } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { + throw new RuntimeException("Cipher initialization failed", e); + } + } +} diff --git a/Dijkstra's Algorithm b/Dijkstra's Algorithm new file mode 100644 index 00000000..2725d739 --- /dev/null +++ b/Dijkstra's Algorithm @@ -0,0 +1,94 @@ +#include +using namespace std; + +#define debug(x) cout<<#x<<" is "< +struct Dijkstra { + + int node,edge; + vector< vector< pair > > adj; + vector< T > level; + vector parent; + + Dijkstra(int _node, int _edge) : node(_node), edge(_edge) { + vector(node+1).swap(parent); + vector(node+1, numeric_limits::max()).swap(level); + vector< vector< pair > > (node+1).swap(adj); + } + + void add_edge(int u, int v, T w) { + adj[u].push_back({v,w}); + adj[v].push_back({u,w}); + } + + void traverse(int src) { + + level[src] = 0; + set< pair > s {{0,src}}; + parent[src] = -1; + + while(not s.empty()) { + auto it = *s.begin(); + int cur_node = it.y; + T cur_level = it.x; + s.erase(s.begin()); + + for(auto u : adj[cur_node]) { + if(level[u.x] - u.y > cur_level) { + level[u.x] = cur_level + u.y; + parent[u.x] = cur_node; + s.insert({level[u.x],u.x}); + } + } + } + } + + void print_path(int x) { + + if(level[x] == numeric_limits::max()) { + cout<<"-1\n"; + return; + } + + if(x == -1){ + return; + } + + print_path(parent[x]); + cout<>node>>edge; + + Dijkstra d(node,edge); + + + while(edge--){ + int x,y; + ll w; + cin>>x>>y>>w; + d.add_edge(x,y,w); + } + + d.traverse(1); + d.print_path(node); + + return 0; +} diff --git a/Dynamic Programming/0-1Knapsack.cpp b/Dynamic Programming/0-1Knapsack.cpp new file mode 100644 index 00000000..1668c34a --- /dev/null +++ b/Dynamic Programming/0-1Knapsack.cpp @@ -0,0 +1,128 @@ +// Q173 https://www.codingninjas.com/codestudio/problems/1072980?topList=striver-sde-sheet-problems&utm_source=striver&utm_medium=website&leftPanelTab=0 + + + + +// Recursion +// Time: O(2^n) +// Space: O(n) +#include +int ks(vector &val, vector &wt, int ind, int W){ + if(ind==0) { + if(wt[0]<=W) return val[0]; + return 0; + } + int nt=ks(val,wt,ind-1,W); + int t=INT_MIN; + if(wt[ind]<=W) + t=val[ind]+ks(val,wt,ind-1,W-wt[ind]); + return max(t,nt); +} + +int maxProfit(vector &val, vector &wt, int n, int W) +{ + return ks(val,wt,n-1,W); +} + + +// Memorisation +// Time: O(N*m) +// Space: O(N*M)+O(N) = auxiliary stack space+ dp +#include +int ks(vector &val, vector &wt, int ind, int W,vector> &dp){ + if(ind==0) { + if(wt[0]<=W) return val[0]; + return 0; + } + if(dp[ind][W]!=-1) return dp[ind][W]; + int nt=ks(val,wt,ind-1,W,dp); + int t=INT_MIN; + if(wt[ind]<=W) + t=val[ind]+ks(val,wt,ind-1,W-wt[ind],dp); + return dp[ind][W]=max(t,nt); +} + +int maxProfit(vector &val, vector &wt, int n, int W) +{ vector> dp(n,vector(W+1,-1)); + return ks(val,wt,n-1,W,dp); +} + + + + + +// DP +// Time: O(N*m) +// Space: O(N*M) +#include +int maxProfit(vector &val, vector &wt, int n, int W) +{ vector> dp(n,vector(W+1,0)); + for(int cw=0;cw +int maxProfit(vector &val, vector &wt, int n, int W){ + vector p(W+1,0); + vector c(W+1,0); + for(int cw=wt[0];cw +int maxProfit(vector &val, vector &wt, int n, int W){ + vector p(W+1,0); +// vector c(W+1,0); + for(int cw=wt[0];cw=0;cw--){ + int nt=p[cw]; + int t=INT_MIN; + if(wt[ind]<=cw) + t=val[ind]+p[cw-wt[ind]]; + p[cw]=max(t,nt); + } +// p=c; + + } + return p[W]; + +} diff --git a/Dynamic Programming/Kadanes.cpp b/Dynamic Programming/Kadanes.cpp new file mode 100644 index 00000000..2a78e536 --- /dev/null +++ b/Dynamic Programming/Kadanes.cpp @@ -0,0 +1,26 @@ +// C++ program to print largest contiguous array sum +#include +using namespace std; +//This is the smallest code for kadanes algorithm +int maxSubArraySum(int A[], int size) +{ + int ans = A[0]; + int sum = A[0]; + for(int i =1 ; i + +using namespace std; + +int maxSubArraySum(int a[], int size) { + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +int main() { + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a) / sizeof(a[0]); + + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} \ No newline at end of file diff --git a/Dynamic Programming/Longest-Common-Substring.cpp b/Dynamic Programming/Longest-Common-Substring.cpp new file mode 100644 index 00000000..6a14f2ba --- /dev/null +++ b/Dynamic Programming/Longest-Common-Substring.cpp @@ -0,0 +1,35 @@ +/* Dynamic Programming solution to find length of the longest common substring*/ +#include + +using namespace std; + +int LongestCommonSubStr(string X, string Y, int m, int n) { + + int dp[m + 1][n + 1]; + int result = 0; + + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0 || j == 0) + dp[i][j] = 0; + + else if (X[i - 1] == Y[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + result = max(result, dp[i][j]); + } else + dp[i][j] = 0; + } + } + return result; +} + +int main() { + string X = "FirstCommit"; + string Y = "LastCommit"; + + int m = X.length(); + int n = Y.length(); + + cout << "Length of Longest Common Substring is " << LongestCommonSubStr(X, Y, m, n); + return 0; +} \ No newline at end of file diff --git a/Dynamic Programming/Smallest contiguous array sum.cpp b/Dynamic Programming/Smallest contiguous array sum.cpp new file mode 100644 index 00000000..253d29c3 --- /dev/null +++ b/Dynamic Programming/Smallest contiguous array sum.cpp @@ -0,0 +1,46 @@ +// C++ implementation to find the smallest sum +// contiguous subarray +#include + +using namespace std; + +// function to find the smallest sum contiguous subarray +int smallestSumSubarr(int arr[], int n) +{ + // to store the minimum value that is ending + // up to the current index + int min_ending_here = INT_MAX; + + // to store the minimum value encountered so far + int min_so_far = INT_MAX; + + // traverse the array elements + for (int i=0; i 0, then it could not possibly + // contribute to the minimum sum further + if (min_ending_here > 0) + min_ending_here = arr[i]; + + // else add the value arr[i] to min_ending_here + else + min_ending_here += arr[i]; + + // update min_so_far + min_so_far = min(min_so_far, min_ending_here); + } + + // required smallest sum contiguous subarray value + return min_so_far; +} + + +// Driver program to test above +int main() +{ + int arr[] = {3, -4, 2, -3, -1, 7, -5}; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Smallest sum: " + << smallestSumSubarr(arr, n); + return 0; +} diff --git a/Dynamic Programming/TSP.java b/Dynamic Programming/TSP.java new file mode 100644 index 00000000..29277075 --- /dev/null +++ b/Dynamic Programming/TSP.java @@ -0,0 +1,65 @@ +import java.util.Scanner; +public class TSP{ +public static void main(String[] args) +{ +int c[][]=new int[10][10], tour[]=new int[10]; +Scanner in = new Scanner(System.in); +int i, j,cost; +System.out.println("** TSP DYNAMIC PROGRAMMING ***"); +System.out.println("Enter the number of cities: "); +int n = in.nextInt(); +if(n==1) +{ +System.out.println("Path is not possible"); +System.exit(0); +} +System.out.println("Enter the cost matrix"); +for(i=1;i<=n;i++) +for(j=1;j<=n;j++) +c[i][j] = in.nextInt(); +System.out.println("The entered cost matrix is"); +for(i=1;i<=n;i++) +{ +for(j=1;j<=n;j++) +{ +System.out.print(c[i][j]+"\t"); +} +System.out.println(); +} +for(i=1;i<=n;i++) +tour[i]=i; +cost = tspdp(c, tour, 1, n); +System.out.println("The accurate path is"); +for(i=1;i<=n;i++) +System.out.print(tour[i]+"->"); + +System.out.println("1"); +System.out.println("The accurate mincost is "+cost); +System.out.println("*** ***** *****"); +} +static int tspdp(int c[][], int tour[], int start, int n) +{ +int mintour[]=new int[10], temp[]=new int[10], mincost=999, ccost, i, j, k; +if(start == n-1) +{ +return (c[tour[n-1]][tour[n]] + c[tour[n]][1]); +} +for(i=start+1; i<=n; i++) +{ + for(j=1; j<=n; j++) + temp[j] = tour[j]; + temp[start+1] = tour[i]; + temp[i] = tour[start+1]; + if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))& prices) { + int ma=0; + int ans=0; + int mi=prices[0]; + int n=prices.size(); + for(int i=1;i +using namespace std; + +int lcs(string &s1, string &s2) +{ + int n = s1.size(); + int m = s2.size(); + vector> dp(n + 1, vector(m + 1, 0)); + int ans = 0; + for (int i = 1; i <= n; i++) + { + for (int j = 1; j <= m; j++) + { + if (s1[i - 1] == s2[j - 1]) + { + // looking if just previous characters are also equal or not + int val = 1 + dp[i - 1][j - 1]; + dp[i][j] = val; + ans = max(ans, val); + } + else + { + // not a part of equal substring, hence 0 + dp[i][j] = 0; + } + } + } + return ans; +} + +int main() +{ + string s1; + string s2; + cin >> s1 >> s2; + cout << "The Length of Longest Common Substring is " << lcs(s1, s2); +} + +// Sample Inputs + +// abcjklp +// acjkp + +// Corresponding Outputs + +// 3 \ No newline at end of file diff --git a/Dynamic Programming/maximumNonAdjacentSum.cpp b/Dynamic Programming/maximumNonAdjacentSum.cpp new file mode 100644 index 00000000..09e5c681 --- /dev/null +++ b/Dynamic Programming/maximumNonAdjacentSum.cpp @@ -0,0 +1,79 @@ +// Problem : Given an array of ‘N’ positive integers, we need to return the maximum sum of the subsequence such that no two elements of the subsequence are adjacent elements in the array. + +#include +using namespace std; + +// Recursive Approach starts + +int maximumNonAdjacentSum(int ind, vector &arr, vector &dp) +{ + if (ind == 0) + { + return arr[0]; + } + else if (ind == 1) + { + return max(arr[0], arr[1]); + } + if (dp[ind] != -1) + { + return dp[ind]; + } + // there can be two cases for an element, either we keep it, so we discard the element adjacent to it, or else we discard the current element so that we can move ahead and make decision for the adjacent element and then return the maximum of both of these choices + int pick = arr[ind] + maximumNonAdjacentSum(ind - 2, arr, dp); + int nonPick = maximumNonAdjacentSum(ind - 1, arr, dp); + return dp[ind] = max(pick, nonPick); +} + +int solve(int n, vector &arr) +{ + vector dp(n, -1); + return maximumNonAdjacentSum(n - 1, arr, dp); +} + +// Recursive Approach ends + +// Tabulation Approach starts + +// int maximumNonAdjacentSum(vector &nums) +// { +// int n = nums.size(); +// if (n == 1) +// { +// return nums[0]; +// } +// vector v(n, 0); +// v[0] = nums[0]; +// v[1] = max(nums[0], nums[1]); +// for (int i = 2; i < n; i++) +// { +// v[i] = max(nums[i] + v[i - 2], v[i - 1]); +// } +// return v[n - 1]; +// } + +// Tabulation approach ends + +int main() +{ + int n; + cin >> n; + vector arr(n); + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + cout << solve(n, arr); +} + +// Sample Inputs + +// 4 2 1 4 9 +// 3 1 2 4 +// 9 1 2 3 1 3 5 8 1 9 + +// Corresponding Outputs + +// 11 +// 5 +// 24 \ No newline at end of file diff --git a/Dynamic Programming/minFallingPathSumTriangle.cpp b/Dynamic Programming/minFallingPathSumTriangle.cpp new file mode 100644 index 00000000..d3b1fb96 --- /dev/null +++ b/Dynamic Programming/minFallingPathSumTriangle.cpp @@ -0,0 +1,77 @@ +// Problem : Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an +// adjacent number of the row below.More formally, if you are on index i on the current row, you may move to either +// index i or index i + 1 on the next row. + +#include +using namespace std; + +int minimumTotal(vector> &triangle) +{ + int n = triangle.size(); + vector> dp(n); + for (int i = 0; i < n; i++) + { + for (int j = 0; j < triangle[i].size(); j++) + { + if (i == 0 and j == 0) + { + // very first cell + dp[i].push_back(triangle[i][j]); + } + else if (j == 0) + { + // we can jump to this cell by one way(⬇️) + dp[i].push_back(dp[i - 1][j] + triangle[i][j]); + } + else if (j == (triangle[i].size() - 1)) + { + // we can jump to this cell by one way(↘️) + dp[i].push_back(dp[i - 1][j - 1] + triangle[i][j]); + } + else + { + // we can jump to this cell by two ways(⬇️ and ↘️) + dp[i].push_back(min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j]); + } + } + } + // returning the minimum out of all calculated sums + return *min_element(dp[n - 1].begin(), dp[n - 1].end()); +} +int main() +{ + int n; + cin >> n; + vector> triangle(n); + for (int i = 0; i < n; i++) + { + for (int j = 0; j <= i; j++) + { + int x; + cin >> x; + triangle[i].push_back(x); + } + } + cout << minimumTotal(triangle); +} + +// Sample Inputs + +// Sample Inputs + +// Sample Inputs + +// 4 +// 2 +// 3 4 +// 6 5 7 +// 4 1 8 3 + +// 1 +// -10 + +// Corresponding Outputs + +// 11 + +// -10 \ No newline at end of file diff --git a/Dynamic Programming/minimumPathFallingSum.java b/Dynamic Programming/minimumPathFallingSum.java new file mode 100644 index 00000000..c038eda0 --- /dev/null +++ b/Dynamic Programming/minimumPathFallingSum.java @@ -0,0 +1,122 @@ +/*https://leetcode.com/problems/minimum-falling-path-sum/submissions/ + * + */ +// minimum hai bhai +private class recursion { + + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + int m = matrix[0].length; + + int ans = Integer.MAX_VALUE; + + for (int j = 0; j < m; j++) { + ans = Math.min(ans, recur(n - 1, j, matrix)); + } + return ans; + } + + private int recur(int i, int j, int[][] matrix) { + // out of bound errors + if (j < 0 || j >= matrix[0].length) return Integer.MAX_VALUE; + // if reawched the first row, then only + if (i == 0) return matrix[0][j]; + + int up = recur(i - 1, j, matrix); + int leftdiagonal = recur(i - 1, j - 1, matrix); + int rightdiagonal = recur(i - 1, j + 1, matrix); + return matrix[i][j] + Math.min(up, Math.min(leftdiagonal, rightdiagonal)); + } +} + +private class memoisation { + int dp[][]; + + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + int m = matrix[0].length; + dp = new int[n][m]; + int ans = Integer.MAX_VALUE; + // fill dp with min value + for (int a[] : dp) { + Arrays.fill(a, Integer.MAX_VALUE); + } + + for (int j = 0; j < m; j++) { + ans = Math.min(ans, recur(n - 1, j, matrix)); + } + return ans; + } + + private int recur(int i, int j, int[][] matrix) { + // out of bound errors + if (j < 0 || j >= matrix[0].length) return Integer.MAX_VALUE; + // if reawched the first row, then only + if (i == 0) return matrix[0][j]; + if (dp[i][j] != Integer.MAX_VALUE) return dp[i][j]; + + int up = recur(i - 1, j, matrix); + int leftdiagonal = recur(i - 1, j - 1, matrix); + int rightdiagonal = recur(i - 1, j + 1, matrix); + return ( + dp[i][j] = + matrix[i][j] + Math.min(up, Math.min(leftdiagonal, rightdiagonal)) + ); + } +} + +private class tabulation { + int dp[][]; + + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + int m = matrix[0].length; + dp = new int[n][m]; + int ans = Integer.MAX_VALUE; + // fill dp with min value + for (int a[] : dp) { + Arrays.fill(a, Integer.MAX_VALUE); + } + + // filling the first array + for (int i = 0; i < m; i++) { + dp[0][i] = matrix[0][i]; + } + + for (int i = 1; i < n; i++) { + for (int col = 0; col < m; col++) { + // check out of boound and go + dp[i][col] = matrix[i][col]; + + int up = dp[i - 1][col]; + int leftdiag = dp[i - 1][Math.max(0, col - 1)]; + int rightdiag = dp[i - 1][Math.min(m - 1, col + 1)]; + + // minimum from the rest of moves + dp[i][col] += Math.min(up, Math.min(leftdiag, rightdiag)); + } + } + + // return the minimum value from the end + for (int j = 0; j < m; j++) { + ans = Math.min(ans, dp[n - 1][j]); + } + return ans; + } + + private int recur(int i, int j, int[][] matrix) { + // out of bound errors + if (j < 0 || j >= matrix[0].length) return Integer.MAX_VALUE; + // if reawched the first row, then only + if (i == 0) return matrix[0][j]; + if (dp[i][j] != Integer.MAX_VALUE) return dp[i][j]; + + int up = recur(i - 1, j, matrix); + int leftdiagonal = recur(i - 1, j - 1, matrix); + int rightdiagonal = recur(i - 1, j + 1, matrix); + return ( + dp[i][j] = + matrix[i][j] + Math.min(up, Math.min(leftdiagonal, rightdiagonal)) + ); + } +} diff --git a/Dynamic Programming/minimumPathSumDP.java b/Dynamic Programming/minimumPathSumDP.java new file mode 100644 index 00000000..af8a7100 --- /dev/null +++ b/Dynamic Programming/minimumPathSumDP.java @@ -0,0 +1,69 @@ +/*https://leetcode.com/problems/minimum-path-sum/ + * dp easy, striver op + * + */ + +private class Recursion { + + public int minPathSum(int[][] grid) { + int n = grid.length; + int m = grid[0].length; + return recursion(n - 1, m - 1, grid); + } + + private int recursion(int i, int j, int[][] grid) { + if (i == 0 && j == 0) return grid[0][0]; + if (i < 0 || j < 0) return Integer.MAX_VALUE; + int up = recursion(i - 1, j, grid); // travelling from upside + int left = recursion(i, j - 1, grid); // travelling from righside + return grid[i][j] + Math.min(up, left); + } +} + +private class memoization { + int dp[][]; + + public int minPathSum(int[][] grid) { + int n = grid.length; + int m = grid[0].length; + dp = new int[n][m]; + for (int a[] : dp) { + Arrays.fill(a, -1); + } + return recursion(n - 1, m - 1, grid); + } + + private int recursion(int i, int j, int[][] grid) { + if (i == 0 && j == 0) return grid[0][0]; + if (i < 0 || j < 0) return Integer.MAX_VALUE; + if (dp[i][j] != -1) return dp[i][j]; + int up = recursion(i - 1, j, grid); // travelling from upside + int left = recursion(i, j - 1, grid); // travelling from righside + return dp[i][j] = grid[i][j] + Math.min(up, left); + } +} + +private class tabulation { + int dp[][]; + + public int minPathSum(int[][] grid) { + int n = grid.length; + int m = grid[0].length; + dp = new int[n][m]; + for (int a[] : dp) { + Arrays.fill(a, -1); + } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (i == 0 && j == 0) dp[i][j] = grid[i][j]; + if (dp[i][j] != -1) continue; else if (i == 0 && j != 0) dp[i][j] = + grid[i][j] + dp[i][j - 1]; else if (i != 0 && j == 0) dp[i][j] = + grid[i][j] + dp[i - 1][j]; else { + dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + return dp[n - 1][m - 1]; + } +} diff --git a/Dynamic Programming/ninjaAndHisFriends.cpp b/Dynamic Programming/ninjaAndHisFriends.cpp new file mode 100644 index 00000000..53d990f8 --- /dev/null +++ b/Dynamic Programming/ninjaAndHisFriends.cpp @@ -0,0 +1,125 @@ +// Problem(3-D DP) : We are given an ‘N *M’ matrix.Every cell of the matrix has some chocolates on it, mat[i][j] gives us the +// number of chocolates.We have two friends ‘Alice’ and ‘Bob’.initially, Alice is standing on the cell(0, 0) and Bob is standing +// on the cell(0, M - 1).Both of them can move only to the cells below them in these three directions : to the bottom cell(↓), +// to the bottom - right cell(↘), or to the bottom - left cell(↙). When Alica and Bob visit a cell, they take all the chocolates +// from that cell with them. It can happen that they visit the same cell, in that case, the chocolates need to be considered only +// once. They cannot go out of the boundary of the given matrix, we need to return the maximum number of chocolates that Bob and +// Alice can together collect. + +#include +using namespace std; + +int f(int i, int j1, int j2, vector> &grid, int n, int m, vector>> &dp) +{ + if (i == n) + { + return 0; + } + if (dp[i][j1][j2] != -1) + { + return dp[i][j1][j2]; + } + int mx = INT_MIN; + // if Alice can move to the left column in the row below + if (((j1 - 1) >= 0)) + { + // if Bob can move to the same column in the row below + mx = max(mx, f(i + 1, j1 - 1, j2, grid, n, m, dp)); + // if Bob can move to the left column in the row below + if ((j2 - 1) >= 0) + { + mx = max(mx, f(i + 1, j1 - 1, j2 - 1, grid, n, m, dp)); + } + // if Bob can move to the right column in the row below + if ((j2 + 1) < m) + { + mx = max(mx, f(i + 1, j1 - 1, j2 + 1, grid, n, m, dp)); + } + } + // if Alice can move to the same column in the row below + // if Bob can move to the same column in the row below + mx = max(mx, f(i + 1, j1, j2, grid, n, m, dp)); + // if Bob can move to the left column in the row below + if ((j2 - 1) >= 0) + { + mx = max(mx, f(i + 1, j1, j2 - 1, grid, n, m, dp)); + } + // if Bob can move to the right column in the row below + if ((j2 + 1) < m) + { + mx = max(mx, f(i + 1, j1, j2 + 1, grid, n, m, dp)); + } + // if Alice can move to the right column in the row below + if (((j1 + 1) < m)) + { + // if Bob can move to the same column in the row below + mx = max(mx, f(i + 1, j1 + 1, j2, grid, n, m, dp)); + // if Bob can move to the left column in the row below + if ((j2 - 1) >= 0) + { + mx = max(mx, f(i + 1, j1 + 1, j2 - 1, grid, n, m, dp)); + } + // if Bob can move to the right column in the row below + if ((j2 + 1) < m) + { + mx = max(mx, f(i + 1, j1 + 1, j2 + 1, grid, n, m, dp)); + } + } + if (j1 == j2) + { + // if same cell for both alice and bob, count chocolates only once + return dp[i][j1][j2] = (mx + grid[i][j1]); + } + else + { + return dp[i][j1][j2] = (mx + grid[i][j1] + grid[i][j2]); + } +} + +int maximumChocolates(int r, int c, vector> &grid) +{ + vector>> dp(r, vector>(c, vector(c))); + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + for (int k = 0; k < c; k++) + { + dp[i][j][k] = -1; + } + } + } + return f(0, 0, c - 1, grid, r, c, dp); +} + +int main() +{ + int r, c; + cin >> r >> c; + vector> grid(r, vector(c)); + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + cin >> grid[i][j]; + } + } + cout << maximumChocolates(r, c, grid); +} + +// Sample Inputs + +// 3 4 +// 2 3 1 2 +// 3 4 2 2 +// 5 6 3 5 + +// 2 2 +// 1 1 +// 1 2 + +// Corresponding Outputs + +// 21 + +// 5 diff --git a/Dynamic Programming/triangle.java b/Dynamic Programming/triangle.java new file mode 100644 index 00000000..2135d71c --- /dev/null +++ b/Dynamic Programming/triangle.java @@ -0,0 +1,43 @@ +/*https://leetcode.com/problems/triangle/ + * triangle + * strivers dp series + */ +private class recursion { + + public int minimumTotal(List> tri) { + return recur(tri, 0, 0); + } + + private static int recur(List> tri, int i, int j) { + if (i == tri.size() - 1) { + return tri.get(i).get(j); + } + int ans = tri.get(i).get(j); + int down = recur(tri, i + 1, j); //tri.get(i+1).get(j); + int diagonal = recur(tri, i + 1, j + 1); //tri.get(i+1).get(j+1); + return ans + Math.min(down, diagonal); + } +} + +private class memoization { + int dp[][]; + + public int minimumTotal(List> tri) { + dp = new int[tri.size()][tri.size()]; + for (int a[] : dp) { + Arrays.fill(a, -1); + } + return recur(tri, 0, 0); + } + + private int recur(List> tri, int i, int j) { + if (i == tri.size() - 1) { + return tri.get(i).get(j); + } + if (dp[i][j] != -1) return dp[i][j]; + int ans = tri.get(i).get(j); + int down = recur(tri, i + 1, j); //tri.get(i+1).get(j); + int diagonal = recur(tri, i + 1, j + 1); //tri.get(i+1).get(j+1); + return dp[i][j] = ans + Math.min(down, diagonal); + } +} diff --git a/Hashtable/Addition-using-hashtable.java b/Hashtable/Addition-using-hashtable.java index e6aef62d..e16ba4e6 100644 --- a/Hashtable/Addition-using-hashtable.java +++ b/Hashtable/Addition-using-hashtable.java @@ -4,14 +4,9 @@ class AddElementsToHashtable { public static void main(String args[]) { - // No need to mention the - // Generic type twice - Hashtable ht1 = new Hashtable<>(); - // Initialization of a Hashtable // using Generics - Hashtable ht2 - = new Hashtable(); + Hashtable ht1 = new Hashtable<>(), ht2 = new Hashtable<>(); // Inserting the Elements // using put() method diff --git a/Hashtable/Check if Binary String Has at Most One Segment of Ones.cpp b/Hashtable/Check if Binary String Has at Most One Segment of Ones.cpp new file mode 100644 index 00000000..4c564bf6 --- /dev/null +++ b/Hashtable/Check if Binary String Has at Most One Segment of Ones.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool checkOnesSegment(string s) { + bool changed = false; + for (int i = 1; i < s.length(); i++) { + if (s[i] == s[i-1]) continue; + if (changed) return false; + changed = true; + } + return true; + } +}; diff --git a/Hashtable/Checking for a valid sudoku b/Hashtable/Checking for a valid sudoku new file mode 100644 index 00000000..9ecc4612 --- /dev/null +++ b/Hashtable/Checking for a valid sudoku @@ -0,0 +1,97 @@ +import java.util.*; + +class example2 { + public static boolean notInRow(char arr[][], int row) + { + + HashSet st = new HashSet<>(); + + for (int i = 0; i < 9; i++) { + if (st.contains(arr[row][i])) + return false; + + if (arr[row][i] != '.') + st.add(arr[row][i]); + } + return true; + } + + public static boolean notInCol(char arr[][], int col) + { + HashSet st = new HashSet<>(); + + for (int i = 0; i < 9; i++) { + + // If already encountered before, + // return false + if (st.contains(arr[i][col])) + return false; + + // If it is not an empty cell, + // insert value at the current + // cell in the set + if (arr[i][col] != '.') + st.add(arr[i][col]); + } + return true; + } + + public static boolean notInBox(char arr[][], int startRow, int startCol) + { + HashSet st = new HashSet<>(); + + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 3; col++) { + char curr = arr[row + startRow][col + startCol]; + + if (st.contains(curr)) + return false; + + if (curr != '.') + st.add(curr); + } + } + return true; + } + public static boolean isValid(char arr[][], int row, + int col) + { + return notInRow(arr, row) && notInCol(arr, col) + && notInBox(arr, row - row % 3, col - col % 3); + } + + public static boolean isValidConfig(char arr[][], int n) + { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + + // If current row or current column or + // current 3x3 box is not valid, return + // false + if (!isValid(arr, i, j)) + return false; + } + } + return true; + } + + public static void main(String[] args) + { + char[][] board = new char[][] { + { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, + { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, + { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, + { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, + { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, + { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, + { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, + { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, + { '.', '.', '.', '.', '8', '.', '.', '7', '9' } + }; + + // Function call + System.out.println( + (isValidConfig(board, 9) ? "YES" : "NO")); + } +} + diff --git a/Hashtable/Clone-a-Binary-Tree-with-Random-Pointers.cpp b/Hashtable/Clone-a-Binary-Tree-with-Random-Pointers.cpp new file mode 100644 index 00000000..c458a901 --- /dev/null +++ b/Hashtable/Clone-a-Binary-Tree-with-Random-Pointers.cpp @@ -0,0 +1,119 @@ +// A hashmap based C++ program to clone a binary +// tree with random pointers +#include +#include +using namespace std; + +/* A binary tree node has data, pointer to left child, + a pointer to right child and a pointer to + random node*/ +struct Node +{ + int key; + struct Node* left, *right, *random; +}; + +/* Helper function that allocates a new Node with the +given data and NULL left, right and random pointers. */ +Node* newNode(int key) +{ + Node* temp = new Node; + temp->key = key; + temp->random = temp->right = temp->left = NULL; + return (temp); +} + +/* Given a binary tree, print its Nodes in inorder*/ +void printInorder(Node* node) +{ + if (node == NULL) + return; + + /* First recur on left subtree */ + printInorder(node->left); + + /* then print data of Node and its random */ + cout << "[" << node->key << " "; + if (node->random == NULL) + cout << "NULL], "; + else + cout << node->random->key << "], "; + + /* now recur on right subtree */ + printInorder(node->right); +} + +/* This function creates clone by copying key +and left and right pointers. This function also +stores mapping from given tree node to clone. */ +Node* copyLeftRightNode(Node* treeNode, unordered_map &mymap) +{ + if (treeNode == NULL) + return NULL; + Node* cloneNode = newNode(treeNode->key); + mymap[treeNode] = cloneNode; + cloneNode->left = copyLeftRightNode(treeNode->left, mymap); + cloneNode->right = copyLeftRightNode(treeNode->right, mymap); + return cloneNode; +} + +// This function copies random node by using the hashmap built by +// copyLeftRightNode() +void copyRandom(Node* treeNode, Node* cloneNode, unordered_map &mymap) +{ + if (cloneNode == NULL) + return; + cloneNode->random = mymap[treeNode->random]; + copyRandom(treeNode->left, cloneNode->left, mymap); + copyRandom(treeNode->right, cloneNode->right, mymap); +} + +// This function makes the clone of given tree. It mainly uses +// copyLeftRightNode() and copyRandom() +Node* cloneTree(Node* tree) +{ + if (tree == NULL) + return NULL; + unordered_map mymap; + Node* newTree = copyLeftRightNode(tree, mymap); + copyRandom(tree, newTree, mymap); + return newTree; +} + +/* Driver program to test above functions*/ +int main() +{ + //Test No 1 + Node *tree = newNode(1); + tree->left = newNode(2); + tree->right = newNode(3); + tree->left->left = newNode(4); + tree->left->right = newNode(5); + tree->random = tree->left->right; + tree->left->left->random = tree; + tree->left->right->random = tree->right; + + // Test No 2 + // tree = NULL; + + // Test No 3 + // tree = newNode(1); + + // Test No 4 + /* tree = newNode(1); + tree->left = newNode(2); + tree->right = newNode(3); + tree->random = tree->right; + tree->left->random = tree; + */ + + cout << "Inorder traversal of original binary tree is: \n"; + printInorder(tree); + + Node *clone = cloneTree(tree); + + cout << "\n\nInorder traversal of cloned binary tree is: \n"; + printInorder(clone); + + return 0; +} diff --git a/Hashtable/Find-All-Duplicate-Subtrees.py b/Hashtable/Find-All-Duplicate-Subtrees.py new file mode 100644 index 00000000..fbfcaf6b --- /dev/null +++ b/Hashtable/Find-All-Duplicate-Subtrees.py @@ -0,0 +1,53 @@ +# Python3 program to find averages of +# all levels in a binary tree. + +# Helper function that allocates a +# new node with the given data and +# None left and right pointers. +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + +def inorder(node, m): + if (not node): + return "" + + Str = "(" + Str += inorder(node.left, m) + Str += str(node.data) + Str += inorder(node.right, m) + Str += ")" + + # Subtree already present (Note that + # we use unordered_map instead of + # unordered_set because we want to print + # multiple duplicates only once, consider + # example of 4 in above subtree, it + # should be printed only once. + if (Str in m and m[Str] == 1): + print(node.data, end = " ") + if Str in m: + m[Str] += 1 + else: + m[Str] = 1 + + return Str + +# Wrapper over inorder() +def printAllDups(root): + m = {} + inorder(root, m) + +# Driver code +if __name__ == '__main__': + root = None + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.right.left = newNode(2) + root.right.left.left = newNode(4) + root.right.right = newNode(4) + printAllDups(root) + diff --git a/Hashtable/Find-Substring-With-Given-Hash-Value.cpp b/Hashtable/Find-Substring-With-Given-Hash-Value.cpp new file mode 100644 index 00000000..7247ca27 --- /dev/null +++ b/Hashtable/Find-Substring-With-Given-Hash-Value.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + string subStrHash(string s, int p, int mod, int k, int target) { + long h = 0, N = s.size(), pp = 1; // `pp` = p^k + vector hash(N); + string r(rbegin(s), rend(s)); + for (int i = 0; i < N; ++i) { + if (i < k) pp = pp * p % mod; + h = (h * p + (r[i] - 'a' + 1)) % mod; // push r[i] into the window + if (i - k >= 0) { // pop r[i-k] out of the window + h = (h - (r[i - k] - 'a' + 1) * pp % mod + mod) % mod; + } + if (i >= k - 1) hash[i] = h; + } + reverse(begin(hash), end(hash)); + for (int i = 0; i < N; ++i) { + if (hash[i] == target) return s.substr(i, k); // hash[i] is the hash of `s[i .. (i+k-1)]` + } + return ""; + } +}; diff --git a/Hashtable/Palindrome-Substring-Queries.cpp b/Hashtable/Palindrome-Substring-Queries.cpp new file mode 100644 index 00000000..49465ca6 --- /dev/null +++ b/Hashtable/Palindrome-Substring-Queries.cpp @@ -0,0 +1,173 @@ +/* A C++ program to answer queries to check whether +the substrings are palindrome or not efficiently */ +#include +using namespace std; + +#define p 101 +#define MOD 1000000007 + +// Structure to represent a query. A query consists +// of (L, R) and we have to answer whether the substring +// from index-L to R is a palindrome or not +struct Query { + int L, R; +}; + +// A function to check if a string str is palindrome +// in the range L to R +bool isPalindrome(string str, int L, int R) +{ + // Keep comparing characters while they are same + while (R > L) + if (str[L++] != str[R--]) + return (false); + return (true); +} + +// A Function to find pow (base, exponent) % MOD +// in log (exponent) time +unsigned long long int modPow( + unsigned long long int base, + unsigned long long int exponent) +{ + if (exponent == 0) + return 1; + if (exponent == 1) + return base; + + unsigned long long int temp = modPow(base, exponent / 2); + + if (exponent % 2 == 0) + return (temp % MOD * temp % MOD) % MOD; + else + return (((temp % MOD * temp % MOD) % MOD) + * base % MOD) + % MOD; +} + +// A Function to calculate Modulo Multiplicative Inverse of 'n' +unsigned long long int findMMI(unsigned long long int n) +{ + return modPow(n, MOD - 2); +} + +// A Function to calculate the prefix hash +void computePrefixHash( + string str, int n, + unsigned long long int prefix[], + unsigned long long int power[]) +{ + prefix[0] = 0; + prefix[1] = str[0]; + + for (int i = 2; i <= n; i++) + prefix[i] = (prefix[i - 1] % MOD + + (str[i - 1] % MOD + * power[i - 1] % MOD) + % MOD) + % MOD; + + return; +} + +// A Function to calculate the suffix hash +// Suffix hash is nothing but the prefix hash of +// the reversed string +void computeSuffixHash( + string str, int n, + unsigned long long int suffix[], + unsigned long long int power[]) +{ + suffix[0] = 0; + suffix[1] = str[n - 1]; + + for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) + suffix[j] = (suffix[j - 1] % MOD + + (str[i] % MOD + * power[j - 1] % MOD) + % MOD) + % MOD; + return; +} + +// A Function to answer the Queries +void queryResults(string str, Query q[], int m, int n, + unsigned long long int prefix[], + unsigned long long int suffix[], + unsigned long long int power[]) +{ + for (int i = 0; i <= m - 1; i++) { + int L = q[i].L; + int R = q[i].R; + + // Hash Value of Substring [L, R] + unsigned long long hash_LR + = ((prefix[R + 1] - prefix[L] + MOD) % MOD + * findMMI(power[L]) % MOD) + % MOD; + + // Reverse Hash Value of Substring [L, R] + unsigned long long reverse_hash_LR + = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD + * findMMI(power[n - R - 1]) % MOD) + % MOD; + + // If both are equal then + // the substring is a palindrome + if (hash_LR == reverse_hash_LR) { + if (isPalindrome(str, L, R) == true) + printf("The Substring [%d %d] is a " + "palindrome\n", + L, R); + else + printf("The Substring [%d %d] is not a " + "palindrome\n", + L, R); + } + + else + printf("The Substring [%d %d] is not a " + "palindrome\n", + L, R); + } + + return; +} + +// A Dynamic Programming Based Approach to compute the +// powers of 101 +void computePowers(unsigned long long int power[], int n) +{ + // 101^0 = 1 + power[0] = 1; + + for (int i = 1; i <= n; i++) + power[i] = (power[i - 1] % MOD * p % MOD) % MOD; + + return; +} + +/* Driver program to test above function */ +int main() +{ + string str = "abaaabaaaba"; + int n = str.length(); + + // A Table to store the powers of 101 + unsigned long long int power[n + 1]; + + computePowers(power, n); + + // Arrays to hold prefix and suffix hash values + unsigned long long int prefix[n + 1], suffix[n + 1]; + + // Compute Prefix Hash and Suffix Hash Arrays + computePrefixHash(str, n, prefix, power); + computeSuffixHash(str, n, suffix, power); + + Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } }; + int m = sizeof(q) / sizeof(q[0]); + + queryResults(str, q, m, n, prefix, suffix, power); + return (0); +} diff --git "a/Hashtable/Recaman\342\200\231s-sequence.py" "b/Hashtable/Recaman\342\200\231s-sequence.py" new file mode 100644 index 00000000..9b5db2d8 --- /dev/null +++ "b/Hashtable/Recaman\342\200\231s-sequence.py" @@ -0,0 +1,37 @@ +# Python 3 program to print n-th +# number in Recaman's sequence + +# Prints first n terms of Recaman +# sequence +def recaman(n): + + # Create an array to store terms + arr = [0] * n + + # First term of the sequence + # is always 0 + arr[0] = 0 + print(arr[0], end=", ") + + # Fill remaining terms using + # recursive formula. + for i in range(1, n): + + curr = arr[i-1] - i + for j in range(0, i): + + # If arr[i-1] - i is + # negative or already + # exists. + if ((arr[j] == curr) or curr < 0): + curr = arr[i-1] + i + break + + arr[i] = curr + print(arr[i], end=", ") + +# Driver code +n = 17 + +recaman(n) + diff --git a/Hashtable/Removing an element from a Hashtable b/Hashtable/Removing an element from a Hashtable new file mode 100644 index 00000000..effc3df0 --- /dev/null +++ b/Hashtable/Removing an element from a Hashtable @@ -0,0 +1,27 @@ +// This program will remove a particular element from the HashTable. + +import java.util.*; +class Example1 { + + public static void main(String args[]) + { + // Initialization of a Hashtable + Map map + = new Hashtable(); + + // Inserting the Elements using put method + map.put(1, "Apple"); + map.put(2, "Mango"); + map.put(3, "Orange"); + map.put(4, "Grapes"); + + // Initial HashMap + System.out.println("Initial map : " + map); + + // Remove the map entry with key 2 + map.remove(2); + + // Final Hashtable + System.out.println("Updated map : " + map); + } +} diff --git a/Hashtable/Smallest-subarray-with-k-distinct-numbers.py b/Hashtable/Smallest-subarray-with-k-distinct-numbers.py new file mode 100644 index 00000000..a2b3b97b --- /dev/null +++ b/Hashtable/Smallest-subarray-with-k-distinct-numbers.py @@ -0,0 +1,49 @@ +# Python 3 program to find minimum range +# that contains exactly k distinct numbers. + +# Prints the minimum range that contains +# exactly k distinct numbers. +def minRange(arr, n, k): + + l = 0 + r = n + + # Consider every element as + # starting point. + for i in range(n): + + # Find the smallest window starting + # with arr[i] and containing exactly + # k distinct elements. + s = [] + for j in range(i, n) : + s.append(arr[j]) + if (len(s) == k): + if ((j - i) < (r - l)) : + r = j + l = i + + break + + # There are less than k distinct + # elements now, so no need to continue. + if (j == n): + break + + # If there was no window with k distinct + # elements (k is greater than total + # distinct elements) + if (l == 0 and r == n): + print("Invalid k") + else: + print(l, r) + +# Driver code +if __name__ == "__main__": + + arr = [ 1, 2, 3, 4, 5 ] + n = len(arr) + k = 3 + minRange(arr, n, k) + + diff --git a/Hashtable/Sorting-using-trivial-hash-function.py b/Hashtable/Sorting-using-trivial-hash-function.py new file mode 100644 index 00000000..f81a768d --- /dev/null +++ b/Hashtable/Sorting-using-trivial-hash-function.py @@ -0,0 +1,46 @@ +# Python3 program to sort an array +# using hash function + + +def sortUsingHash(a, n): + + # find the maximum element + Max = max(a) + + # create a hash function upto + # the max size + Hash = [0] * (Max + 1) + + # traverse through all the elements + # and keep a count + for i in range(0, n): + Hash[a[i]] += 1 + + # Traverse upto all elements and check + # if it is present or not. If it is + # present, then print the element the + # number of times it's present. Once we + # have printed n times, that means we + # have printed n elements so break out + # of the loop + for i in range(0, Max + 1): + + # if present + if Hash[i] != 0: + + # print the element that number + # of times it's present + for j in range(0, Hash[i]): + print(i, end=" ") + + +# Driver Code +if __name__ == "__main__": + + a = [9, 4, 3, 2, 5, 2, 1, 0, 4, + 3, 5, 10, 15, 12, 18, 20, 19] + n = len(a) + + sortUsingHash(a, n) + +#This code is given by Aman. diff --git a/Hashtable/cuckoo-hashing.cpp b/Hashtable/cuckoo-hashing.cpp new file mode 100644 index 00000000..18eb8c33 --- /dev/null +++ b/Hashtable/cuckoo-hashing.cpp @@ -0,0 +1,139 @@ +// C++ program to demonstrate working of Cuckoo +// hashing. +#include + +// upper bound on number of elements in our set +#define MAXN 11 + +// choices for position +#define ver 2 + +// Auxiliary space bounded by a small multiple +// of MAXN, minimizing wastage +int hashtable[ver][MAXN]; + +// Array to store possible positions for a key +int pos[ver]; + +/* function to fill hash table with dummy value +* dummy value: INT_MIN +* number of hashtables: ver */ +void initTable() +{ + for (int j=0; j> bucket[100]; //bucket is an array whose each element is a vector of pair + + void put(int key, int value) { + int index = key%100; + for(int i=0 ; imaxsum) + maxsum=sum; + if(sum<0) + sum=0; + } + System.out.println(maxsum); + } +} diff --git a/Java/Array/Largest_col_sum.java b/Java/Array/LargestColSum.java similarity index 94% rename from Java/Array/Largest_col_sum.java rename to Java/Array/LargestColSum.java index e6f5258e..9b305ecf 100644 --- a/Java/Array/Largest_col_sum.java +++ b/Java/Array/LargestColSum.java @@ -3,7 +3,7 @@ package Two_Dimensional_Array; import java.util.Scanner; -public class Largest_col_sum { +public class LargestColSum { public static int largestcolsum(int [] [] arr2) { int rows = arr2.length; int cols = arr2[0].length; diff --git a/Java/Array/Largest_Row_Column.java b/Java/Array/LargestRowColumn.java similarity index 96% rename from Java/Array/Largest_Row_Column.java rename to Java/Array/LargestRowColumn.java index 56cd2e18..34e6e2e0 100644 --- a/Java/Array/Largest_Row_Column.java +++ b/Java/Array/LargestRowColumn.java @@ -53,7 +53,7 @@ package Two_Dimensional_Array; import java.util.Scanner; -public class Largest_Row_Column { +public class LargestRowColumn { public static void largestRowColumn(int [] [] arr2) { int cols = arr2[0].length; diff --git a/Java/Array/Largest_Row_Sum.java b/Java/Array/LargestRowSum.java similarity index 94% rename from Java/Array/Largest_Row_Sum.java rename to Java/Array/LargestRowSum.java index ed93900f..baeb2289 100644 --- a/Java/Array/Largest_Row_Sum.java +++ b/Java/Array/LargestRowSum.java @@ -7,7 +7,7 @@ package Two_Dimensional_Array; import java.util.Scanner; -public class Largest_Row_Sum { +public class LargestRowSum { public static int largestcolsum(int [] [] arr2) { int max = Integer.MIN_VALUE; for (int i = 0; i < arr2.length; i++) { diff --git a/Java/LeftRotateArrayByD.java b/Java/Array/LeftRotateArrayByD.java similarity index 96% rename from Java/LeftRotateArrayByD.java rename to Java/Array/LeftRotateArrayByD.java index 857c21fb..e02d46fd 100644 --- a/Java/LeftRotateArrayByD.java +++ b/Java/Array/LeftRotateArrayByD.java @@ -1,60 +1,60 @@ -package com.company; - -public class LeftRotateArrayByD { - - //Reversal Algorithm--> - static void reverse(int[] arr, int low, int high){ - int temp=0; - while (low - -// static void leftRotate(int[] arr, int d){ -// int[] temp = new int[d]; -// for (int i=0; i - -// static void leftRotateOne(int[] arr){ -// int n = arr.length; -// int temp = arr[0]; -// for (int i=1; i + static void reverse(int[] arr, int low, int high){ + int temp=0; + while (low + +// static void leftRotate(int[] arr, int d){ +// int[] temp = new int[d]; +// for (int i=0; i + +// static void leftRotateOne(int[] arr){ +// int n = arr.length; +// int temp = arr[0]; +// for (int i=1; i adj[]; /* adjacency list */ + private Queue que; /* maintaining a queue */ + + BfsTraversal(int v) { + node = v; + adj = new LinkedList[node]; + for (int i = 0; i < v; i++) { + adj[i] = new LinkedList(); + } + que = new LinkedList(); + } + + void insertEdge(int v, int w) { + adj[v].add(w); + } + + void BFS(int n) { + boolean nodes[] = new boolean[node]; /* initialize boolean array for holding the data */ + int a = 0; + nodes[n] = true; + que.add(n); /* root node is added to the top of the queue */ + while (que.size() != 0) { + n = que.poll(); /* remove the top element of the queue */ + System.out.print(n + " "); /* print the top element of the queue */ + for (int i = 0; i < adj[n].size(); i++) { + a = adj[n].get(i); + if (!nodes[a]) /* only insert nodes into queue if they have not been explored already */ + { + nodes[a] = true; + que.add(a); + } + } + } + } + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter number of vertices"); + int ve = sc.nextInt(); + BfsTraversal graph = new BfsTraversal(ve); + System.out.println("Enter number of edges"); + int e = sc.nextInt(); + for (int i = 0; i < e; i++) { + System.out.println("Enter starting vertex of the edge " + i); + int u = sc.nextInt(); + System.out.println("Enter ending vertex of the edge " + i); + int v = sc.nextInt(); + graph.insertEdge(u, v); + } + System.out.println("Breadth First Traversal for the graph is:"); + graph.BFS(0); + } +} diff --git a/Java/Count_Operations_to_Obtain_Zero.java b/Java/CountOperationsToObtainZero.java similarity index 90% rename from Java/Count_Operations_to_Obtain_Zero.java rename to Java/CountOperationsToObtainZero.java index 5ff2efce..4e393e41 100644 --- a/Java/Count_Operations_to_Obtain_Zero.java +++ b/Java/CountOperationsToObtainZero.java @@ -2,7 +2,7 @@ LEETCODE QUESTION : 2169. Count Operations to Obtain Zero */ -public class Count_Operations_to_Obtain_Zero { +public class CountOperationsToObtainZero { public int countOperations(int num1, int num2) { return helper(num1, num2, 0); diff --git a/Java/DFSTraversal.class b/Java/DFSTraversal.class new file mode 100644 index 00000000..12b1d5dc Binary files /dev/null and b/Java/DFSTraversal.class differ diff --git a/Java/DFSTraversal.java b/Java/DFSTraversal.java new file mode 100644 index 00000000..ee365697 --- /dev/null +++ b/Java/DFSTraversal.java @@ -0,0 +1,52 @@ +import java.util.*; + +class DFSTraversal { + private LinkedList adj[]; /* adjacency list representation */ + private boolean visited[]; + + /* Creation of the graph */ + DFSTraversal(int V) /* 'V' is the number of vertices in the graph */ + { + adj = new LinkedList[V]; + visited = new boolean[V]; + + for (int i = 0; i < V; i++) + adj[i] = new LinkedList(); + } + + /* Adding an edge to the graph */ + void insertEdge(int src, int dest) { + adj[src].add(dest); + } + + void DFS(int vertex) { + visited[vertex] = true; /* Mark the current node as visited */ + System.out.print(vertex + " "); + + // Iterator it = adj[vertex].listIterator(); + ListIterator ti = adj[vertex].listIterator(); + while (ti.hasNext()) { + int n = ti.next(); + if (!visited[n]) + DFS(n); + } + } + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter number of vertices"); + int ve = sc.nextInt(); + DFSTraversal graph = new DFSTraversal(ve); + System.out.println("Enter number of edges"); + int e = sc.nextInt(); + for (int i = 0; i < e; i++) { + System.out.println("Enter starting vertex of the edge " + i); + int u = sc.nextInt(); + System.out.println("Enter ending vertex of the edge " + i); + int v = sc.nextInt(); + graph.insertEdge(u, v); + } + System.out.println("Depth First Traversal for the graph is:"); + graph.DFS(0); + } +} diff --git a/Java/Determine_Color_of_a_Chessboard_Square.java b/Java/DetermineColorOfAChessboardSquare.java similarity index 85% rename from Java/Determine_Color_of_a_Chessboard_Square.java rename to Java/DetermineColorOfAChessboardSquare.java index 69bafd43..a6fd1114 100644 --- a/Java/Determine_Color_of_a_Chessboard_Square.java +++ b/Java/DetermineColorOfAChessboardSquare.java @@ -3,7 +3,7 @@ */ -public class Determine_Color_of_a_Chessboard_Square { +public class DetermineColorOfAChessboardSquare { public boolean squareIsWhite(String coordinates) { diff --git a/Java/even-odd-number-using-bitwise-and.java b/Java/EvenOddNumberUsingBitwiseAnd.java similarity index 96% rename from Java/even-odd-number-using-bitwise-and.java rename to Java/EvenOddNumberUsingBitwiseAnd.java index 64318083..f1a11332 100644 --- a/Java/even-odd-number-using-bitwise-and.java +++ b/Java/EvenOddNumberUsingBitwiseAnd.java @@ -1,5 +1,5 @@ import java.util.Scanner; -public class evenodd { +public class EvenOdd { public static void main(String[]args){ Scanner sc = new Scanner(System.in); System.out.println("enter the number"); diff --git a/Java/Fibonacci_pattern.java b/Java/FibonacciPattern.java similarity index 100% rename from Java/Fibonacci_pattern.java rename to Java/FibonacciPattern.java diff --git a/Java/5_Bit Manipulation/BitOperations.java b/Java/FiveBitManipulation/BitOperations.java similarity index 100% rename from Java/5_Bit Manipulation/BitOperations.java rename to Java/FiveBitManipulation/BitOperations.java diff --git a/Java/5_Bit Manipulation/BitwiseOperators.java b/Java/FiveBitManipulation/BitwiseOperators.java similarity index 100% rename from Java/5_Bit Manipulation/BitwiseOperators.java rename to Java/FiveBitManipulation/BitwiseOperators.java diff --git a/Java/5_Bit Manipulation/FastExponentiation.java b/Java/FiveBitManipulation/FastExponentiation.java similarity index 100% rename from Java/5_Bit Manipulation/FastExponentiation.java rename to Java/FiveBitManipulation/FastExponentiation.java diff --git a/Java/FiveBitManipulation/KthBitSet.java b/Java/FiveBitManipulation/KthBitSet.java new file mode 100644 index 00000000..6581c2a0 --- /dev/null +++ b/Java/FiveBitManipulation/KthBitSet.java @@ -0,0 +1,19 @@ +import java.util.*; + +public class KthBitSet { + public static void main(String[] args) { + Scanner sc= new Scanner(System.in); + int n=sc.nextInt(),k= sc.nextInt(); + /*Method 1 using left shift operator*/ + if((n & (1<<(k-1))) == 0 ) + System.out.println("NO"); + else + System.out.println("YES"); + + /*Method 2 using right shift operator*/ +// if(((n>>(k-1))&1) != 0) +// System.out.println("YES"); +// else +// System.out.println("NO"); + } +} diff --git a/Java/5_Bit Manipulation/OddEven.java b/Java/FiveBitManipulation/OddEven.java similarity index 100% rename from Java/5_Bit Manipulation/OddEven.java rename to Java/FiveBitManipulation/OddEven.java diff --git a/Java/FiveBitManipulation/SubSetWithBitwise.java b/Java/FiveBitManipulation/SubSetWithBitwise.java new file mode 100644 index 00000000..a458112b --- /dev/null +++ b/Java/FiveBitManipulation/SubSetWithBitwise.java @@ -0,0 +1,25 @@ +import java.util.*; + +public class SubSetWithBitwise { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + String s=sc.next(); + int i,k,n,n1; + int l=s.length(); + n=(int)Math.pow(2.0,l); + System.out.print(" "); + for(i=0;i>k)&1) == 1) + System.out.print(s.charAt(k)); + k++; + n1/=2; + } + System.out.println(); + } + } +} diff --git a/Java/HashCodeDemo.java b/Java/HashCodeDemo.java new file mode 100644 index 00000000..487feaae --- /dev/null +++ b/Java/HashCodeDemo.java @@ -0,0 +1,12 @@ +public class HashCodeDemo { + public static void main(String args[]){ + String text ="Ganga"; + String text1 ="GangaRiver"; + Integer e = text.hashCode(); + System.out.println(text1.hashCode()); + String str = text1.substring(0,5); + System.out.println(str); + Integer f = text1.hashCode(); + System.out.println(e.equals(f)); + } +} diff --git a/Java/LeetCodeN-Queens.java b/Java/LeetCodeN-Queens.java new file mode 100644 index 00000000..b29762b3 --- /dev/null +++ b/Java/LeetCodeN-Queens.java @@ -0,0 +1,67 @@ +/* Question Link: https://leetcode.com/problems/n-queens/ + * The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. + * Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. + * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. + */ + + + + + + +class Solution { + public List> solveNQueens(int n) { + List> results = new ArrayList<>(); + if(n ==0) return results; + backtrace(results, new ArrayList(), 0, n, new boolean[n]); + return results; + } + + public static void backtrace(List> result, List list, int level, int n, boolean[] used){ + if(level == n) result.add(new ArrayList(list)); + else{ + for(int i = 0; i < n; i++){ + if(used[i]) continue; + if(isValid(list, level, i, n)){ + list.add(createQueen(n, i)); + used[i] = true; + backtrace(result, list, level + 1, n, used); + used[i] = false; + list.remove(list.size() - 1); + } + } + } + } + public static boolean isValid(List list, int row, int column, int n){ + if(row > 0){ + String cmp = list.get(row - 1); + for(int i = 0; i < row; i++) + if(list.get(i).charAt(column) == 'Q') return false; + int tempRow = row; + int tempCol = column; + while(--tempRow >= 0 && --tempCol >= 0){ + if(list.get(tempRow).charAt(tempCol) == 'Q') return false; + } + tempRow = row; + tempCol = column; + while(--tempRow >= 0 && ++tempCol <= n-1) + if(list.get(tempRow).charAt(tempCol) == 'Q') return false; + } + return true; + } + private static String createQueen(int n, int index){ + StringBuilder sb = new StringBuilder(); + int i = 0; + for(; i < index; i++) + sb.append('.'); + sb.append('Q'); + for(++i; i < n; i++){ + sb.append('.'); + } + return sb.toString(); + } + + +} + +/*contributed by: nilesh05apr */ \ No newline at end of file diff --git a/Java/Leetcode-Median-of-2-sorted-arrays.java b/Java/Leetcode-Median-of-2-sorted-arrays.java new file mode 100644 index 00000000..b290667e --- /dev/null +++ b/Java/Leetcode-Median-of-2-sorted-arrays.java @@ -0,0 +1,60 @@ +// Problem link : https://leetcode.com/problems/median-of-two-sorted-arrays/description + +class Solution { +public double findMedianSortedArrays(int[] nums1, int[] nums2) { +int arr[]=new int[nums1.length+nums2.length]; + + int j=0; + int i=0; + int r=0; + while(inums2[j]) + { + arr[r]=nums2[j]; + j++; + r++; + } + else + { + arr[r]=nums1[i]; + r++; + arr[r]=nums2[j]; + r++; + i++; + j++; + } + + } + while(i st=new Stack<>(); + int count=0; + for(int i=0;i=arr.length){ + return 0; + } + if(dp[idx]!=-1){ + return dp[idx]; + } + int a=arr[idx]+max(arr,idx+2,dp); + int b=max(arr,idx+1,dp); + + return dp[idx]=Math.max(a,b); + } + public int rob(int[] nums) { + int []dp=new int[nums.length]; + for(int i=0;i maxHeap=new PriorityQueue<>(Collections.reverseOrder()); + PriorityQueue minHeap=new PriorityQueue<>(); + + public double[] medianSlidingWindow(int[] nums, int k) { + int i=0,j=0; + double[] ans=new double[nums.length-k+1]; + + while(j=nums[j]) + maxHeap.offer(nums[j]); + else minHeap.offer(nums[j]); + + if(maxHeap.size()>minHeap.size()+1) + minHeap.offer(maxHeap.poll()); + else if(maxHeap.size()minHeap.size()+1) + minHeap.offer(maxHeap.poll()); + else if(maxHeap.size()= 97 && ch <= 122 || ch >= 48 && ch <= 57) { + s1.append(ch); + } + } + + StringBuilder s2 = new StringBuilder(s1); + + reverse(s2); + + if (s1.toString().equals(s2.toString())) { + return true; + } else { + return false; + } + } + + static void reverse(StringBuilder s){ + int start=0,end=s.length()-1; + while(end>start){ + swap(s,start,end); + start++; + end--; + } + } + + static void swap(StringBuilder s,int a,int b){ + char temp; + temp=s.charAt(a); + s.setCharAt(a,s.charAt(b)); + s.setCharAt(b,temp); + } +} diff --git a/Java/Leetcode/Leetcode13.java b/Java/Leetcode/Leetcode13.java new file mode 100644 index 00000000..65dba5df --- /dev/null +++ b/Java/Leetcode/Leetcode13.java @@ -0,0 +1,79 @@ +package com.company; + +public class Leetcode13 { + public static void main(String[] args) { + String s="MCMXCIV"; + System.out.println(roman(s)); + } + + + static int roman(String s){ + int sum=0; + for (int i = 0; i < s.length(); i++) { + if(s.charAt(i)=='I'){ + if ( i+1max){ + max=sum; + } + } + return max; + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode1678.java b/Java/Leetcode/Leetcode1678.java new file mode 100644 index 00000000..4c869f12 --- /dev/null +++ b/Java/Leetcode/Leetcode1678.java @@ -0,0 +1,27 @@ +package com.company; + +public class Leetcode1678 { + public static void main(String[] args) { + String str="G()()()()(al)"; + String answer=interpret(str); + System.out.println(answer); + } + + public static String interpret(String command) { + int i=0,l=command.length(); + String updated=""; + while (i=1){ + x=n/26; + + if (x==0){ + y=n+64; + columnTitle=columnTitle+(char)y; + n=n/26; + } + + if (x>=1 && x<=26){ + y=x+64; + columnTitle=columnTitle+(char)y; + break; + } + + if (x>26){ + y=x%26; + y=y+64; + columnTitle=columnTitle+(char)y; + n=n/26; + } + + } + columnTitle=columnTitle+(char)((columnNumber%26)+64); + return columnTitle; + } +} diff --git a/Java/Leetcode/Leetcode1704.java b/Java/Leetcode/Leetcode1704.java new file mode 100644 index 00000000..558367cc --- /dev/null +++ b/Java/Leetcode/Leetcode1704.java @@ -0,0 +1,32 @@ +package com.company; + +public class Leetcode1704 { + public static void main(String[] args) { + String s="Sohail"; + System.out.println(halvesAreAlike(s)); + } + + + static boolean halvesAreAlike(String s) { + int c1 = 0, c2 = 0; + for (int i = 0; i < (s.length() / 2); i++) { + char ch = Character.toUpperCase(s.charAt(i)); + if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { + c1++; + } + } + for (int i = (s.length() / 2); i < s.length(); i++) { + char ch = Character.toUpperCase(s.charAt(i)); + if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { + c2++; + } + } + + if(c1==c2){ + return true; + } + else { + return false; + } + } +} diff --git a/Java/Leetcode/Leetcode1768.java b/Java/Leetcode/Leetcode1768.java new file mode 100644 index 00000000..b6d46b11 --- /dev/null +++ b/Java/Leetcode/Leetcode1768.java @@ -0,0 +1,29 @@ +package com.company; + +public class Leetcode1768 { + public static void main(String[] args) { + String w1="abc"; + String w2="pqr"; + System.out.println(merge(w1,w2)); + } + + static String merge(String w1,String w2){ + String str=""; + int l=Math.min(w1.length(),w2.length()); + StringBuilder s=new StringBuilder(); + for (int i = 0; i < l; i++) { + s.append(w1.charAt(i)); + s.append(w2.charAt(i)); + } + if(w1.length()>w2.length()){ + str=w1; + } + else{ + str=w2; + } + for (int i = l; i > items=new ArrayList<>(); + + int M = 3; +// for (int i = 0; i < M; i++) { +// items.add(new ArrayList<>()); +// } +// items.add({"phone","blue","pixel"}); +// items= {{"phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"}}; +// String ruleKey = "color", ruleValue = "silver"; + } + + public static int countMatches(List> items, String ruleKey, String ruleValue) { + int a=0,c=0; + if(ruleKey.equals("type")){ + a=0; + } else if (ruleKey.equals("color")){ + a=1; + } else if (ruleKey.equals("name")){ + a=2; + } + + for (int i = 0; i < items.size(); i++) { + if ((items.get(i)).get(a).equals(ruleValue)){ + c++; + } + } + return c; + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode190.java b/Java/Leetcode/Leetcode190.java new file mode 100644 index 00000000..b0914016 --- /dev/null +++ b/Java/Leetcode/Leetcode190.java @@ -0,0 +1,30 @@ +package com.company; + +public class Leetcode190 { + public static void main(String[] args) { + int n = 25; + int answer = reverseBits(n); + System.out.println(answer); + } + + static int reverseBit(int n) { + int rev = 0; + for (int i = 0; i <= 31; i++) { + rev = rev << 1; + rev = rev + (n & 1); + n = n >> 1; + } + return rev; + } + + static int reverseBits(int n) { + int res=0; + for(int i=0;i<32;i++) //length of word is 32 + { + res=res<<1; //this is like multiplying the number with 10 in decimal here we left shift it as in multiplying by 2 + res+=(n&1); //add number after taking it's & with 1 + n=n>>1; //divide number by 2 to get next digit + } + return res; + } +} diff --git a/Java/Leetcode/Leetcode191.java b/Java/Leetcode/Leetcode191.java new file mode 100644 index 00000000..f087d7cd --- /dev/null +++ b/Java/Leetcode/Leetcode191.java @@ -0,0 +1,21 @@ +package com.company; + + public class Leetcode191 { + public static void main(String[] args) { + int n = 429; + int answer = setBits(n); + System.out.println(answer); + } + + static int setBits(int n) { + int c = 0, i = 0; + while (i <= 31) { + if ((n & 1) != 0) { + c++; + } + n = n >> 1; + i++; + } + return c; + } + } \ No newline at end of file diff --git a/Java/Leetcode/Leetcode1967.java b/Java/Leetcode/Leetcode1967.java new file mode 100644 index 00000000..dcc7acc1 --- /dev/null +++ b/Java/Leetcode/Leetcode1967.java @@ -0,0 +1,41 @@ +package com.company; + +import java.util.ArrayList; + +public class Leetcode1967 { + public static void main(String[] args) { + String[] patterns = {"a","b","c"}; + String word = "aaaaabbbbb"; + System.out.println(numOfStrings(patterns,word)); + } + +// static int numOfStrings(String[] p, String word){ +// int c=0; +// for (int i = 0; i <=p.length-1 ; i++) { +// int l=p[i].length(); +// for (int j = 0; j <=word.length()-l ; j++) { +// StringBuilder s=new StringBuilder(word.substring(j,l)); +// if((s.toString()).equals(p[i])){ +// c++; +// break; +// } +// +// } +// } +// return c; +// } + + + public static int numOfStrings(String[] patterns, String word) { + int c=0; + for (int i = 0; i < patterns.length; i++) { + for (int j = 0; j < word.length() ; j++) { + if (word.substring(j).startsWith(patterns[i])){ + c++; + break; + } + } + } + return c; +} +} diff --git a/Java/Leetcode/Leetcode20.java b/Java/Leetcode/Leetcode20.java new file mode 100644 index 00000000..295bd446 --- /dev/null +++ b/Java/Leetcode/Leetcode20.java @@ -0,0 +1,23 @@ +package com.company; + +public class Leetcode20 { + public static void main(String[] args) { + String s=")){}[]"; + System.out.println(paranthesis(s)); + } + + static boolean paranthesis(String s){ + if(s.length()%2!=0){ + return false; + } + for (int i = 0; i =0 ; i--) { + str.append(s.charAt(i)); + } + for (int i = a+1; i < s.length(); i++) { + str.append(s.charAt(i)); + } + return str.toString(); + } +} diff --git a/Java/Leetcode/Leetcode2011.java b/Java/Leetcode/Leetcode2011.java new file mode 100644 index 00000000..eec6a39b --- /dev/null +++ b/Java/Leetcode/Leetcode2011.java @@ -0,0 +1,21 @@ +package com.company; + +public class Leetcode2011 { + public static void main(String[] args) { + String[] arr={"--X","X++","X++"}; + int answer=finalValueAfterOperations(arr); + System.out.println(answer); + } + + public static int finalValueAfterOperations(String[] operations) { + int count=0; + for (int i = 0; i < operations.length; i++) { + if (operations[i].charAt(1)==('+')){ + count++; + } else { + count--; + } + } + return count; + } +} diff --git a/Java/Leetcode/Leetcode202.java b/Java/Leetcode/Leetcode202.java new file mode 100644 index 00000000..38d18cea --- /dev/null +++ b/Java/Leetcode/Leetcode202.java @@ -0,0 +1,37 @@ +package com.company; + +public class Leetcode202 { + public static void main(String[] args) { + int n=19; + boolean answer=happyNumber(n); + System.out.println(answer); + + } + +// Linked List will be used in this bcoz cycle is forming. We can use slow and fast pointer method in this. + public static boolean happyNumber(int n){ + int slow=n; + int fast=n; + + do { + slow=square(slow); + fast=square(square(fast)); + } while (slow!=fast); + + if(slow==1){ + return true; + } + return false; + } + + private static int square(int n){ + int digit = 0; + int sum=0; + while (n!=0){ + digit=n%10; + sum=digit*digit+sum; + n=n/10; + } + return sum; + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode2114.java b/Java/Leetcode/Leetcode2114.java new file mode 100644 index 00000000..28f2abaf --- /dev/null +++ b/Java/Leetcode/Leetcode2114.java @@ -0,0 +1,18 @@ +package com.company; + +public class Leetcode2114 { + public static void main(String[] args) { + + } + + public static int mostWordsFound(String[] sentences) { + int max=0; + for (int i = 0; i < sentences.length; i++) { + String[] arr=sentences[i].split(" "); + if(arr.length>max){ + max=arr.length; + } + } + return max; + } +} diff --git a/Java/Leetcode/Leetcode2206.java b/Java/Leetcode/Leetcode2206.java new file mode 100644 index 00000000..5678b0f0 --- /dev/null +++ b/Java/Leetcode/Leetcode2206.java @@ -0,0 +1,8 @@ +class Solution { + public boolean divideArray(int[] nums) { + return Arrays.stream(nums) + .boxed() + .collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting())) + .values().stream().allMatch(e -> e % 2 == 0); + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode23.java b/Java/Leetcode/Leetcode23.java new file mode 100644 index 00000000..fe059079 --- /dev/null +++ b/Java/Leetcode/Leetcode23.java @@ -0,0 +1,27 @@ +/* +You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. +Merge all the linked-lists into one sorted linked-list and return it. +Input: lists = [[1,4,5],[1,3,4],[2,6]] +Output: [1,1,2,3,4,4,5,6] +*/ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + PriorityQueue q=new PriorityQueue<>((a,b)->a.val-b.val); + ListNode curr=new ListNode(0); + ListNode ans=curr; + + for(ListNode l:lists){ + while(l!=null){ + q.offer(l); + l=l.next; + } + } + + while(!q.isEmpty()){ + curr.next=q.poll(); + curr=curr.next; + curr.next=null; + } + return ans.next; + } +} diff --git a/Java/Leetcode/Leetcode268.java b/Java/Leetcode/Leetcode268.java new file mode 100644 index 00000000..b0fc468c --- /dev/null +++ b/Java/Leetcode/Leetcode268.java @@ -0,0 +1,46 @@ +package com.company; + +public class Leetcode268 { + public static void main(String[] args) { + int[] arr={9,6,4,2,3,5,7,0,1}; + int ans=missing(arr); + System.out.println(ans);; + } + + + static int missing(int[] arr){ + sort(arr); + + for(int i=0;i arr.length-1) { + i++; + continue; + } + + if (arr[i] != arr[charIndex]) { + swap(arr, i, charIndex); + } else { + i++; + } + } + } + + static void swap(int[] arr, int a, int b){ + int temp=arr[a]; + arr[a]=arr[b]; + arr[b]=temp; + } +} diff --git a/Java/Leetcode/Leetcode287.java b/Java/Leetcode/Leetcode287.java new file mode 100644 index 00000000..779e5d8d --- /dev/null +++ b/Java/Leetcode/Leetcode287.java @@ -0,0 +1,32 @@ +package com.company; + +import java.util.Arrays; + +public class Leetcode287 { + public static void main(String[] args) { + int[] arr={3,1,3,4,2}; + sort(arr); + System.out.println(arr[arr.length-1]); + + } + + static void sort(int[] arr){ + int i=0; + while(i> 1; + k++; + } + arr[j] = c; + } + return arr; + } + } \ No newline at end of file diff --git a/Java/Leetcode/Leetcode34.java b/Java/Leetcode/Leetcode34.java new file mode 100644 index 00000000..c315ce9b --- /dev/null +++ b/Java/Leetcode/Leetcode34.java @@ -0,0 +1,36 @@ +package com.company; + +public class Leetcode34 { + public static void main(String[] args) { + int[] arr={2,5,7,9,9,9,9,10,12,16}; + int target=9; + int first=search(arr,target,true); + int last=search(arr,target,false); + System.out.println("First Occurence At="+first); + System.out.println("Last Occurence At="+last); + + } + + static int search(int[] arr, int target,boolean isStart){ + int start=0,end=arr.length-1;int ans=-1; + while(end>=start){ + int mid=start+(end-start)/2; + if(target>arr[mid]){ + start=mid+1; + } + else if(target0){ + char ch= sb.charAt(0); + sb.deleteCharAt(0); + + for (int i = 0; i < sb.length(); i++) { + if(ch==sb.charAt(i)){ + count++; + sb.deleteCharAt(i); + i--; + } + } + answer=answer+count+ch; + count=1; + } + return answer; + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode442.java b/Java/Leetcode/Leetcode442.java new file mode 100644 index 00000000..9fb11c2f --- /dev/null +++ b/Java/Leetcode/Leetcode442.java @@ -0,0 +1,40 @@ +package com.company; + +import java.util.*; + +public class Leetcode442 { + public static void main(String[] args) { + int arr[]={4,3,2,7,8,2,3,1}; + List ans=duplicate(arr); + System.out.println(ans); + } + + + static List duplicate(int[] arr){ + int i=0; + while(i ans=new ArrayList<>(); + for(int j=0;j ans=new ArrayList<>(); + List ans=disappear(arr); + System.out.println(ans); + } + + static List disappear(int[] arr) { + int i = 0; + while (i < arr.length) { + int correctIndex = arr[i] - 1; + if (arr[i] != arr[correctIndex]) { + swap(arr, i, correctIndex); + } else { + i++; + } + } + + List ans = new ArrayList<>(); + for (int j = 0; j < arr.length; j++) { + if (arr[j] != j + 1) + { ans.add(j+1); + } + } + return ans; + } + + static void swap(int[] arr, int a, int b){ + int temp=arr[a]; + arr[a]=arr[b]; + arr[b]=temp; + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode476.java b/Java/Leetcode/Leetcode476.java new file mode 100644 index 00000000..a164cac2 --- /dev/null +++ b/Java/Leetcode/Leetcode476.java @@ -0,0 +1,13 @@ +package com.company; + +public class Leetcode476 { + public static void main(String[] args) { + int n = 5; + int ans = compliment(n); + System.out.println(ans); + } + + static int compliment(int n) { + return ~n; + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode557.java b/Java/Leetcode/Leetcode557.java new file mode 100644 index 00000000..00852ddf --- /dev/null +++ b/Java/Leetcode/Leetcode557.java @@ -0,0 +1,29 @@ +package com.company; + +public class Leetcode557 { + public static void main(String[] args) { + String s="Let's take LeetCode contest"; + String answer=reverseWords(s); + System.out.println(answer); + } + + public static String reverseWords(String s) { + int space=0; + StringBuilder sb=new StringBuilder(s); + sb.append(" "); + String updated=""; + while (sb.length()>1){ + space=sb.indexOf(" "); + String str = reverse(sb.substring(0, space)); + updated=updated+" "+str; + sb.delete(0,space+1); + } + return updated.trim(); + } + + public static String reverse(String s){ + StringBuilder sb=new StringBuilder(s); + sb.reverse(); + return sb.toString(); + } +} diff --git a/Java/Leetcode/Leetcode58.java b/Java/Leetcode/Leetcode58.java new file mode 100644 index 00000000..fb0cad38 --- /dev/null +++ b/Java/Leetcode/Leetcode58.java @@ -0,0 +1,19 @@ +package com.company; + +public class Leetcode58 { + public static void main(String[] args) { + String s=" fly me to the moon "; + System.out.println(length(s)); + } + + static int length(String str){ + StringBuilder s=new StringBuilder(str.trim()); + int l=0; + for (int i = s.length()-1; i >=0 ; i--) { + if(Character.isWhitespace(s.charAt(i))){ + return l=(s.substring(i+1).length()); + } + } + return s.length(); + } +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode628.java b/Java/Leetcode/Leetcode628.java new file mode 100644 index 00000000..f6b7b8d5 --- /dev/null +++ b/Java/Leetcode/Leetcode628.java @@ -0,0 +1,35 @@ +package com.company; + +public class Leetcode628 { + public static void main(String[] args) { + int[] arr={-1,-2,-3}; + int ans=product(arr); + System.out.println(ans); + } + + static int product(int[] arr){ + int i=0,prod=1; + while(iarr.length-4;j--){ + prod=arr[j]*prod; + } + return prod; + } + + + static void swap(int[] arr, int a, int b){ + int temp=arr[a]; + arr[a]=arr[b]; + arr[b]=temp; + } + +} \ No newline at end of file diff --git a/Java/Leetcode/Leetcode645.java b/Java/Leetcode/Leetcode645.java new file mode 100644 index 00000000..76c53ceb --- /dev/null +++ b/Java/Leetcode/Leetcode645.java @@ -0,0 +1,41 @@ +package com.company; + +import java.util.ArrayList; +import java.util.List; + +public class Leetcode645 { + public static void main(String[] args) { + int[] arr={1,2,2,4}; + int[] ans=disappear(arr); + System.out.println("Repeated:"+ans[0]); + System.out.println("Missing:"+ans[1]); + + } + + static int[] disappear(int[] arr) { + int i = 0; + while (i < arr.length) { + int correctIndex = arr[i] - 1; + if (arr[i] != arr[correctIndex]) { + swap(arr, i, correctIndex); + } else { + i++; + } + } + + int[] ans = new int[2]; + for (int j = 0; j < arr.length; j++) { + if (arr[j] != j + 1){ + ans[0]=arr[j]; + ans[1]=j+1; + } + } + return ans; + } + + static void swap(int[] arr, int a, int b){ + int temp=arr[a]; + arr[a]=arr[b]; + arr[b]=temp; + } +} diff --git a/Java/Leetcode/Leetcode657.java b/Java/Leetcode/Leetcode657.java new file mode 100644 index 00000000..a84f3a8a --- /dev/null +++ b/Java/Leetcode/Leetcode657.java @@ -0,0 +1,35 @@ +package com.company; + +public class Leetcode657 { + public static void main(String[] args) { + String s="LLUDRR"; + System.out.println(robot(s)); + } + + + static boolean robot(String s){ + int l=0,r=0,u=0,d=0; + for (int i = 0; i < s.length(); i++) { + char ch=s.charAt(i); + if(ch=='L' || ch=='l'){ + l++; + } + if(ch=='R' ||ch=='r' ){ + r++; + } + if(ch=='U' || ch=='u'){ + u++; + } + if(ch=='D' ||ch=='d' ){ + d++; + } + } + + if(l==r && u==d){ + return true; + } + else{ + return false; + } + } +} diff --git a/Java/Leetcode/Leetcode680.java b/Java/Leetcode/Leetcode680.java new file mode 100644 index 00000000..804c7480 --- /dev/null +++ b/Java/Leetcode/Leetcode680.java @@ -0,0 +1,55 @@ +package com.company; + +public class Leetcode680 { + public static void main(String[] args) { + StringBuilder s=new StringBuilder("sohail"); + System.out.println(palindrome(s)); + } + + static boolean palindrome(StringBuilder s){ + boolean ans=palin(s); + + if(ans){ + return true; + } + + for (int i = 0; i < s.length(); i++) { + StringBuilder s2=new StringBuilder(s); + s2.deleteCharAt(i); + ans=palin(s2); + if(ans){ + return true; + } + } + return false; + } + + + static boolean palin(StringBuilder s) { + StringBuilder s1 = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + char ch = Character.toLowerCase(s.charAt(i)); + if (ch >= 97 && ch <= 122 || ch >= 48 && ch <= 57) { + s1.append(ch); + } + } + + StringBuilder s2 = new StringBuilder(s1); + + reverse(s2); + + return s1.toString().equals(s2.toString()); + } + + static void reverse(StringBuilder s){ + int start=0,end=s.length()-1; + while(end>start){ + char temp; + temp=s.charAt(start); + s.setCharAt(start,s.charAt(end)); + s.setCharAt(end,temp); + start++; + end--; + } + } +} diff --git a/Java/Leetcode/Leetcode709.java b/Java/Leetcode/Leetcode709.java new file mode 100644 index 00000000..4fce7cfd --- /dev/null +++ b/Java/Leetcode/Leetcode709.java @@ -0,0 +1,21 @@ +package com.company; + +public class Leetcode709 { + public static void main(String[] args) { + String s="SoHail"; + System.out.println(lowerCase(s)); + } + + static String lowerCase(String s){ + StringBuilder str=new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + if(s.charAt(i)>=65 && s.charAt(i)<=90 ){ + str.append(Character.toLowerCase(s.charAt(i))); + } + else{ + str.append(s.charAt(i)); + } + } + return str.toString(); + } +} diff --git a/Java/Leetcode/Leetcode744.java b/Java/Leetcode/Leetcode744.java new file mode 100644 index 00000000..e07084c0 --- /dev/null +++ b/Java/Leetcode/Leetcode744.java @@ -0,0 +1,35 @@ +package com.company; + +public class Leetcode744 { + public static void main(String[] args) { + char[] arr={'c','f','j'}; + char target='c'; + + int ans=ceiling(arr,target); + + if(ans==-1){ + System.out.println("Empty Array"); + } + else + System.out.println("Ceiling="+arr[ans]); + } + + static int ceiling(char[] arr, char target){ + int start=0,end=arr.length-1; + if(arr.length==0){ + return -1; + } + + while(end>=start){ + int mid=start+(end-start)/2; + + if(target>=arr[mid]){ + start=mid+1; + } + else if(target arr[mid+1]) { + end = mid; + } else { + start = mid + 1; + } + } + return start; + } + +} diff --git a/Java/Leetcode-IteratorforCombination.java b/Java/Leetcode/LeetcodeIteratorForCombination.java similarity index 100% rename from Java/Leetcode-IteratorforCombination.java rename to Java/Leetcode/LeetcodeIteratorForCombination.java diff --git a/Java/Leetcode-LetterTilePossibilities.java b/Java/Leetcode/LeetcodeLetterTilePossibilities.java similarity index 100% rename from Java/Leetcode-LetterTilePossibilities.java rename to Java/Leetcode/LeetcodeLetterTilePossibilities.java diff --git a/Java/Leetcode_LRUCache.java b/Java/Leetcode/LeetcodeLruCache.java similarity index 100% rename from Java/Leetcode_LRUCache.java rename to Java/Leetcode/LeetcodeLruCache.java diff --git a/Java/Leetcode-N-th Tribonacci Number.java b/Java/Leetcode/LeetcodeNThTribonacciNumber.java similarity index 100% rename from Java/Leetcode-N-th Tribonacci Number.java rename to Java/Leetcode/LeetcodeNThTribonacciNumber.java diff --git a/Java/Leetcode-Reverse-Nodes-in-k-Group.java b/Java/Leetcode/LeetcodeReverseNodesInKGroup.java similarity index 100% rename from Java/Leetcode-Reverse-Nodes-in-k-Group.java rename to Java/Leetcode/LeetcodeReverseNodesInKGroup.java diff --git a/Java/Leetcode-Sum of All Subset XOR Totals.java b/Java/Leetcode/LeetcodeSumOfAllSubsetXorTotals.java similarity index 100% rename from Java/Leetcode-Sum of All Subset XOR Totals.java rename to Java/Leetcode/LeetcodeSumOfAllSubsetXorTotals.java diff --git a/Java/Leetcode-The-Skyline-Problem.java b/Java/Leetcode/LeetcodeTheSkylineProblem.java similarity index 100% rename from Java/Leetcode-The-Skyline-Problem.java rename to Java/Leetcode/LeetcodeTheSkylineProblem.java diff --git a/Java/Leetcode/leetcode_Valid Parentheses.java b/Java/Leetcode/leetcode_Valid Parentheses.java new file mode 100644 index 00000000..b63bb316 --- /dev/null +++ b/Java/Leetcode/leetcode_Valid Parentheses.java @@ -0,0 +1,23 @@ +class Solution { + bool isValid(tring s) { + stack st; + for(int i = 0; i < s.length(); i++){ + if(s[i] == '(' || s[i] == '{' || s[i] == '['){ + st.push(s[i]); + } + + else if(!st.empty()){ + if((s[i] == ')' && st.top() == '(') || (s[i] == '}' && st.top() == '{') || (s[i] == ']' && st.top() == '[') ){ + st.pop(); + } + else{ + return false; + } + } + else{ + return false; + } + } + return st.empty(); + } +} diff --git a/Java/Linked List/LinkedList.java b/Java/Linked List/LinkedList.java new file mode 100644 index 00000000..74eeb3ac --- /dev/null +++ b/Java/Linked List/LinkedList.java @@ -0,0 +1,76 @@ +//Author: Vaibhav Pandey +//Date Created: 06/03/2022 +//Title: Implementing Linked List data structure in Java from scratch + + +//Start of main LinkedList class +public class LinkedList{ + + //Node class for storing current node's value and the address to the next node + static class Node{ + Node next; + int value; + + //Constructor that initializes node's value + public Node(int value){ + this.value = value; + } + } + + //Initializing the first node to null + Node first = null; + + //Function for adding elements at the front of the list + public void addAtFront(Node node){ + //Assign the next node's address to first and store the current node's address in first + node.next = first; + first = node; + } + + //Function for adding elements at the end of the list + public void addAtEnd(Node node){ + //If the list is already empty, just assign the first address to the current node + if(first == null){ + first = node; + } + //If the list is not empty, traverse the list from the first element to the last element and add the current node at last + else{ + Node ptr = first; + while(ptr.next != null){ + ptr = ptr.next; + } + ptr.next = node; + } + } + + //Function for removing the first element of the list + public void removeFront(){ + //To remove the first element, just set the next element to first + first = first.next; + } + + + //Function to print the list + public void print(){ + //For printing just traverse the list from first to last + Node ptr = first.next; + System.out.print(first.value); + while(ptr != null){ + System.out.print(" -> " + ptr.value); + ptr = ptr.next; + } + System.out.println(" -> null"); + //The last element of the list points to null + } + + //Main function to run the LinkedList class + public static void main(String[] args){ + LinkedList list = new LinkedList(); + list.addAtEnd(new Node(5)); + list.addAtEnd(new Node(7)); + list.addAtFront(new Node(10)); + list.addAtEnd(new Node(2)); + list.print(); + } + +} \ No newline at end of file diff --git a/Java/Linked List/length_of_linkedList.java b/Java/Linked List/length_of_linkedList.java deleted file mode 100644 index ea92ae9d..00000000 --- a/Java/Linked List/length_of_linkedList.java +++ /dev/null @@ -1,52 +0,0 @@ -package LinkedList; - - class node { - - public T data; - public node next; - - public node(T data) { - this.data = data; - next = null; - } -} - -public class length_of_linkedList { - - public static node createLinkedList() { - - node n1 = new node<>(10); - node n2 = new node<>(20); - node n3 = new node<>(30); - node n4 = new node<>(40); - node n5 = new node<>(50); - - n1.next = n2; - n2.next = n3; - n3.next = n4; - n4.next = n5; - return n1; - - } - - public static int length1(node head) { - - int count = 0; - node temp = head; - while (temp != null) { - count++; - temp = temp.next; - } - return count; - - } - - public static void main(String[] args) { - - node head = createLinkedList(); - int ans = length1(head); - System.out.println(ans); - - } - -} \ No newline at end of file diff --git a/Java/LinkedList/Copy_List_with_Random_Pointer.java b/Java/LinkedList/Copy_List_with_Random_Pointer.java new file mode 100644 index 00000000..634351b6 --- /dev/null +++ b/Java/LinkedList/Copy_List_with_Random_Pointer.java @@ -0,0 +1,81 @@ +// https://leetcode.com/problems/copy-list-with-random-pointer/ + +/* +// Definition for a Node. +class Node { + int val; + Node next; + Node random; + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } +} +*/ + +// Using extra space - Map +class Solution { + public Node copyRandomList(Node head) { + if(head == null) return null; + + Node curr = head, newHead = new Node(0); + Node newCurr = newHead; + HashMap map = new HashMap(); + + while(curr != null){ + if(!map.containsKey(curr)){ + newCurr.next = new Node(curr.val); + map.put(curr, newCurr.next); + } else newCurr.next = map.get(curr); + + newCurr = newCurr.next; + + if(curr.random != null){ + if(!map.containsKey(curr.random)){ + newCurr.random = new Node(curr.random.val); + map.put(curr.random, newCurr.random); + } else newCurr.random = map.get(curr.random); + } + + curr = curr.next; + } + + return newHead.next; + } +} + +// Using constant space - inplace temp update +class Solution { + public Node copyRandomList(Node head) { + if(head == null) return null; + + Node curr = head, newHead = new Node(0); + Node newCurr = newHead, next = curr; + + while(curr != null){ + next = curr.next; + curr.next = new Node(curr.val); + curr.next.next = next; + curr = next; + } + + curr = head; + while(curr != null && curr.next != null){ + if(curr.random != null) curr.next.random = curr.random.next; + + curr = curr.next.next; + } + + curr = head; + while(curr != null && curr.next != null){ + next = curr.next.next; + newCurr.next = curr.next; + newCurr = newCurr.next; + curr.next = next; + curr = next; + } + + return newHead.next; + } +} diff --git a/Java/Linked List/LeetCode_61_Rotate_List.java b/Java/LinkedList/LeetCode61RotateList.java similarity index 100% rename from Java/Linked List/LeetCode_61_Rotate_List.java rename to Java/LinkedList/LeetCode61RotateList.java diff --git a/Java/LinkedList/LengthOfLinkedList.java b/Java/LinkedList/LengthOfLinkedList.java new file mode 100644 index 00000000..5f1157fd --- /dev/null +++ b/Java/LinkedList/LengthOfLinkedList.java @@ -0,0 +1,52 @@ +package LinkedList; + + class Node { + + public T data; + public LinkedList.Node next; + + public Node(T data) { + this.data = data; + next = null; + } +} + +public class LengthOfLinkedList { + + public static LinkedList.Node createLinkedList() { + + LinkedList.Node n1 = new LinkedList.Node<>(10); + LinkedList.Node n2 = new LinkedList.Node<>(20); + LinkedList.Node n3 = new LinkedList.Node<>(30); + LinkedList.Node n4 = new LinkedList.Node<>(40); + LinkedList.Node n5 = new LinkedList.Node<>(50); + + n1.next = n2; + n2.next = n3; + n3.next = n4; + n4.next = n5; + return n1; + + } + + public static int length1(LinkedList.Node head) { + + int count = 0; + LinkedList.Node temp = head; + while (temp != null) { + count++; + temp = temp.next; + } + return count; + + } + + public static void main(String[] args) { + + LinkedList.Node head = createLinkedList(); + int ans = length1(head); + System.out.println(ans); + + } + +} \ No newline at end of file diff --git a/Java/LinkedList/Linked-List-Implementation.java b/Java/LinkedList/Linked-List-Implementation.java new file mode 100644 index 00000000..8329fbf4 --- /dev/null +++ b/Java/LinkedList/Linked-List-Implementation.java @@ -0,0 +1,73 @@ +import java.io.*; + +public class LinkedList { + Node head; + // LINKED LIST NODE + static class Node + { + int data; + Node next; + // Constructor + Node(int d) + { + data = d; + next = null; + } + } + + // Method to insert a new node + public static LinkedList insert(LinkedList list, int data) + { + Node new_node = new Node(data); + // If the Linked List is empty, + // then make the new node as head + if (list.head == null) + { + list.head = new_node; + } + else + { + // Else traverse till the last node + // and insert the new_node there + Node last = list.head; + while (last.next != null) { + last = last.next; + } + // Insert the new_node at last node + last.next = new_node; + } + // Return the list by head + return list; + } + + // Method to print the LinkedList. + public static void printList(LinkedList list) + { + Node currNode = list.head; + System.out.print("LinkedList: "); + // Traverse through the LinkedList + while (currNode != null) { + // Print the data at current node + System.out.print(currNode.data + " "); + // Go to next node + currNode = currNode.next; + } + } + + // Driver code + public static void main(String[] args) + { + LinkedList list = new LinkedList(); + + list = insert(list, 1); + list = insert(list, 2); + list = insert(list, 3); + list = insert(list, 4); + list = insert(list, 5); + list = insert(list, 6); + list = insert(list, 7); + list = insert(list, 8); + + printList(list); + } +} \ No newline at end of file diff --git a/Java/Linked List/Linked_List_Cycle.java b/Java/LinkedList/LinkedListCycle.java similarity index 100% rename from Java/Linked List/Linked_List_Cycle.java rename to Java/LinkedList/LinkedListCycle.java diff --git a/Java/Linked List/Merge_Two_Sorted_List b/Java/LinkedList/MergeTwoSortedList.java similarity index 100% rename from Java/Linked List/Merge_Two_Sorted_List rename to Java/LinkedList/MergeTwoSortedList.java diff --git a/Java/Linked List/Middle_of_the_Linked_List.java b/Java/LinkedList/MiddleOfTheLinkedList.java similarity index 100% rename from Java/Linked List/Middle_of_the_Linked_List.java rename to Java/LinkedList/MiddleOfTheLinkedList.java diff --git a/Java/Linked List/Palindrome_Linked_List.java b/Java/LinkedList/PalindromeLinkedList.java similarity index 100% rename from Java/Linked List/Palindrome_Linked_List.java rename to Java/LinkedList/PalindromeLinkedList.java diff --git a/Java/Linked List/Reverse_Linked_List.java b/Java/LinkedList/ReverseLinkedList.java similarity index 96% rename from Java/Linked List/Reverse_Linked_List.java rename to Java/LinkedList/ReverseLinkedList.java index 94f11d29..b7c48f97 100644 --- a/Java/Linked List/Reverse_Linked_List.java +++ b/Java/LinkedList/ReverseLinkedList.java @@ -22,7 +22,7 @@ public class ListNode { } } -public class Reverse_Linked_List { +public class ReverseLinkedList { //Submit in leetcode from here :- public ListNode reverseList(ListNode head) { diff --git a/Java/Linked List/Reverse_Nodes_in_k-Group.java b/Java/LinkedList/ReverseNodesInKGroup.java similarity index 100% rename from Java/Linked List/Reverse_Nodes_in_k-Group.java rename to Java/LinkedList/ReverseNodesInKGroup.java diff --git a/Java/Majority_Element.java b/Java/Majority_Element.java new file mode 100644 index 00000000..66f73034 --- /dev/null +++ b/Java/Majority_Element.java @@ -0,0 +1,34 @@ +/* + * Question: + * Given an array nums of size n, return the majority element. + * The majority element is the element that appears more than ⌊n / 2⌋ times. + * + * I have solved this question and even optimised it using the famous Algorithm known as + * "Moore's Voting Algorithm" + * + * LeetCode Q - 169 + * + * + * Time Complexity - O(N) + * Space Complexity - O(1) + */ + +public class Majority_Element { + public static void main(String[] args) { + int arr[] = { 2, 2, 1, 1, 1, 2, 2 }; + System.out.println(majority(arr)); + } + + public static int majority(int nums[]) { + int c = 0, elm = 0; + for (int i = 0; i < nums.length; i++) { + if (c == 0) + elm = nums[i]; + if (elm == nums[i]) + c++; + else + c--; + } + return elm; + } +} diff --git a/Java/MatirixMultiplication b/Java/Matrix/MatirixMultiplication similarity index 100% rename from Java/MatirixMultiplication rename to Java/Matrix/MatirixMultiplication diff --git a/Java/Matrix Chain_Multiplication.java b/Java/Matrix/MatrixChainMultiplication.java similarity index 100% rename from Java/Matrix Chain_Multiplication.java rename to Java/Matrix/MatrixChainMultiplication.java diff --git a/Java/spiralmatrix.java b/Java/Matrix/SpiralMatrix.java similarity index 100% rename from Java/spiralmatrix.java rename to Java/Matrix/SpiralMatrix.java diff --git a/Java/MinimumTimeToColorRope.java b/Java/MinimumTimeToColorRope.java new file mode 100644 index 00000000..6bd7ffb0 --- /dev/null +++ b/Java/MinimumTimeToColorRope.java @@ -0,0 +1,40 @@ +/* + * + * Minimum Time to make the Rope Colorful. + * Leetcode Question - 1578. + * + * In this code I have used the Greedy Approach To solve this question. + */ + + +public class MinimumTimeToColorRope { + public static void main(String[] args) { + int time[] = {1,2,3,4,5}; //Time in Seconds + String colors = "abaac"; //Colors Sequence + System.out.println(minCost(colors, time)); //Total Time Taken to make the rope colorfull + } + public static int minCost(String colors, int[] neededTime) { + int sec = 0; + char c = ' '; + int cp = 0; + for(int i=0;i row; spaces--) { + System.out.print(" "); + } + if(row%2!=0){ + for (int i = 0; i <= row; i++) { + if (i%2!=0 || i != 1) { + if(i == 0 || i == row){ + System.out.print("* "); + } + else{ + System.out.print(" "); + } + } + } + } + else{ + for (int i = 0; i <= row; i++) { + System.out.print("* "); + } + } + System.out.println(); + } + } + } diff --git a/Java/Pattern-Questions/Question2.java b/Java/PatternQuestions/Question2.java similarity index 100% rename from Java/Pattern-Questions/Question2.java rename to Java/PatternQuestions/Question2.java diff --git a/Java/Pattern-Questions/Question3.java b/Java/PatternQuestions/Question3.java similarity index 100% rename from Java/Pattern-Questions/Question3.java rename to Java/PatternQuestions/Question3.java diff --git a/Java/Pattern-Questions/Question4.java b/Java/PatternQuestions/Question4.java similarity index 100% rename from Java/Pattern-Questions/Question4.java rename to Java/PatternQuestions/Question4.java diff --git a/Java/Pattern-Questions/Question5.java b/Java/PatternQuestions/Question5.java similarity index 100% rename from Java/Pattern-Questions/Question5.java rename to Java/PatternQuestions/Question5.java diff --git a/Java/Pattern-Questions/Question6.java b/Java/PatternQuestions/Question6.java similarity index 100% rename from Java/Pattern-Questions/Question6.java rename to Java/PatternQuestions/Question6.java diff --git a/Java/Pattern-Questions/Question7.java b/Java/PatternQuestions/Question7.java similarity index 100% rename from Java/Pattern-Questions/Question7.java rename to Java/PatternQuestions/Question7.java diff --git a/Java/Pattern-Questions/Question8.java b/Java/PatternQuestions/Question8.java similarity index 100% rename from Java/Pattern-Questions/Question8.java rename to Java/PatternQuestions/Question8.java diff --git a/Java/Pattern-Questions/Question9.java b/Java/PatternQuestions/Question9.java similarity index 100% rename from Java/Pattern-Questions/Question9.java rename to Java/PatternQuestions/Question9.java diff --git a/Java/RadixSort.java b/Java/RadixSort.java new file mode 100644 index 00000000..c19a396f --- /dev/null +++ b/Java/RadixSort.java @@ -0,0 +1,80 @@ +// Radix sort Java implementation + +import java.io.*; +import java.util.*; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of + // size n using Radix Sort + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/Java/Recursion/Binary_of_a_number.java b/Java/Recursion/Binary_of_a_number.java new file mode 100644 index 00000000..1a1d3620 --- /dev/null +++ b/Java/Recursion/Binary_of_a_number.java @@ -0,0 +1,20 @@ +import java.util.*; +class Binary_of_a_number +{ + static void Binary(int n) + { + if (n == 0) + return; + Binary(n / 2); + System.out.print(n % 2 + " "); + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter A Number"); + int n = I.nextInt(); + System.out.println("Binary Representation of the number : "); + Binary(n); + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/Checking_the_palindrome.java b/Java/Recursion/Checking_the_palindrome.java new file mode 100644 index 00000000..6df12136 --- /dev/null +++ b/Java/Recursion/Checking_the_palindrome.java @@ -0,0 +1,25 @@ +import java.util.*; + +class Checking_the_palindrome +{ + static boolean palin(String s, int l, int i) + { + if (i == l / 2) + return true; + boolean x = (s.charAt(i) == s.charAt(l - 1 - i)); // Boolean data can be used as 0 and 1 + return (x && palin(s, l, i + 1)); // In java booleans can be multiplied using relational operators only + } + + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter a String you want to check"); + String s = I.nextLine(); + System.out.print("The String is PalinDrome? "); + if (palin(s, s.length(), 0)) + System.out.print("YES"); + else + System.out.print("NO"); + I.close(); + } +} diff --git a/Java/Recursion/FactorialN.java b/Java/Recursion/FactorialN.java new file mode 100644 index 00000000..daa9a6c3 --- /dev/null +++ b/Java/Recursion/FactorialN.java @@ -0,0 +1,33 @@ +import java.util.*; +class FactorialN +{ + public static int f; //Global variable + static void fct(int n) //Tail recursive version + { + if (n <= 1) + return; + f *= n; + fct(n-1); //All Set and done + } + /* + static int fct(int n) //Head recursive version + { + if (n <= 1) + return 1; + return (n * fct(n-1)); + // this n, makes the function here head recursive, as the function + // will have to return to its parent to do the multiplication, + // hence tail elimination cant be used + } + */ + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter A Number"); + int n = I.nextInt(); + f = 1; + fct(n); + System.out.println("Your factorial is: " + f); + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/Fibonacci.java b/Java/Recursion/Fibonacci.java new file mode 100644 index 00000000..09ae1ff7 --- /dev/null +++ b/Java/Recursion/Fibonacci.java @@ -0,0 +1,36 @@ +import java.util.*; +class Fibonacci // if asked for a term always use bennet's formula, open purple register +{ + static void nth_fibo(int b, int c, int n) //better than f(n-1) + f(n-2), coz here a lot + { //overlapping subproblems occur + /* + if(n < 0) + return 0; + if(n < 2) + return n; + return(fibo(n-1) + fibo(n-2)); //tradional 2^n solution + */ + if (n == 2) //if u say 0 is the first term, else take n == 1 + { + System.out.println(c); + return; + } + //Uncomment to print the series + //System.out.print(c+b + " "); + nth_fibo(c, c + b, n - 1); //To print use System.out.println(c+b), above this statement + } + + public static void main(String args[]) { + Scanner I = new Scanner(System.in); + System.out.println("Enter the number n, to get the nth fibonacci number"); + int n = I.nextInt(); + if (n < 3) + System.out.println(n - 1); + else + { + System.out.println("0 1 "); + nth_fibo(0, 1, n); + } + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/N_to_1.java b/Java/Recursion/N_to_1.java new file mode 100644 index 00000000..93ba8a2d --- /dev/null +++ b/Java/Recursion/N_to_1.java @@ -0,0 +1,21 @@ +import java.util.*; +class N_to_1 //tail Recursive +{ + static void rec(int N) + { + //A label called Start is added here, + //This is called Tail Call Elimination + if(N == 0) + return; + System.out.print(N + " "); + rec(N-1); //Modern Compiler change it to [ n -> n-1, goto start] + } //This makes the execution faster + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter the value of N"); + int N = I.nextInt(); + rec(N); + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/Permutation.java b/Java/Recursion/Permutation.java new file mode 100644 index 00000000..88342e0e --- /dev/null +++ b/Java/Recursion/Permutation.java @@ -0,0 +1,58 @@ +import java.util.*; +class Permutation { + static String swap(String mystring, int i, int j) // function to swap the characters in the string + { + char ch[] = mystring.toCharArray(); + char tempo = ch[i]; + ch[i] = ch[j]; + ch[j] = tempo; + return String.valueOf(ch); + } + static void permutation(String s, int index) // To permuatate the string + { + if (index == s.length() - 1) // if the index equals the length, print the string + System.out.println(s); + for (int j = index; j < s.length(); j++) { + s = swap(s, j, index); // Swap the character to manipulate the string + permutation(s, index + 1); // Send it to get the permutation + s = swap(s, j, index); // Swap back to get the original string + } + } + public static void main(String args[]) { + Scanner I = new Scanner(System.in); + System.out.println("ENTER A STRING"); + String s = I.nextLine(); + System.out.println("Given Below are all the permutations of the string"); + permutation(s, 0); + I.close(); + } +} +// Time Complexity : N * N! +/* +//Cpp function to get the shit done, lexographically and unique elements +class Solution +{ + public: + set ans; + void permutate(string s, int in) + { + if(in == s.size()-1) + { + ans.insert(s); + return; + } + for(int j = in; j < s.size();j++) + { + swap(s[j],s[in]); + permutate(s, in + 1); + swap(s[j],s[in]); + } + } + vectorfind_permutation(string S) + { + permutate(S,0); + vector res(ans.begin(), ans.end()); + return res; + } +}; +*/ \ No newline at end of file diff --git a/Java/Recursion/README.md b/Java/Recursion/README.md new file mode 100644 index 00000000..3eb89e02 --- /dev/null +++ b/Java/Recursion/README.md @@ -0,0 +1 @@ +This Repository contains some basic recursion problems diff --git a/Java/Recursion/Repeat_Pattern.java b/Java/Recursion/Repeat_Pattern.java new file mode 100644 index 00000000..b8601848 --- /dev/null +++ b/Java/Recursion/Repeat_Pattern.java @@ -0,0 +1,43 @@ +import java.util.*; +class Repeat_Pattern +{ + static void pattern(int n) { + + if (n == 0) + return; + pattern(n - 1); + System.out.println(n); + pattern(n - 1); + } + + public static void main(String args[]) { + Scanner I = new Scanner(System.in); + System.out.println("Enter A Number\n"); + int n = I.nextInt(); + pattern(n); + I.close(); + } +} +/* + +Input + 4 + +Output +1 //Nothing before 1 so nothing afterwards +2 //Everything printed before is printed afterwards +1 +3 //Everything printed before is printed afterwards +1 +2 +1 +4 //Everything printed before is printed afterwards +1 +2 +1 +3 +1 +2 +1 + +*/ \ No newline at end of file diff --git a/Java/Recursion/Rope_cutting.java b/Java/Recursion/Rope_cutting.java new file mode 100644 index 00000000..8d3b48a3 --- /dev/null +++ b/Java/Recursion/Rope_cutting.java @@ -0,0 +1,65 @@ +import java.util.*; +class Rope_cutting +{ + static int get_max(int n, int a, int b, int c) + { + if(n < 1) + return n; + /* + // first drafts are bad at times + int x = -1 , y = -1, z = -1; + x = get_max(n-a,a,b,c); + y = get_max(n-b,a,b,c); + z = get_max(n-c,a,b,c); + x = (x > -1) ? x+1 : -1; + y = (y > -1) ? y+1 : -1; + z = (z > -1) ? z+1 : -1; + return (Math.max(x, Math.max(y,z))); + */ + int ans = Math.max(get_max(n-a,a,b,c),Math.max(get_max(n-b,a,b,c),get_max(n-c,a,b,c))); //Concise version of the above code + if(ans > -1) + return ans + 1; + return -1; + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + int n = I.nextInt(),a = I.nextInt(),b = I.nextInt(),c = I.nextInt(); + int ans = get_max(n,a,b,c); + System.out.println("Answer : " + ans); + I.close(); + } +} +//TIME COMPLEXITY = 3^N, WHERE N = LENGTH OF THE ROD + + + + +/* +//DP Solution for the same + #include //Given that a way to cut the ribbon exists therefore {a*x + b*y +c*z = n} + //Task is to maximise x+y+z + using namespace std; + int main() + { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + int n,a,b,c,x=-1,y=-1,z=-1; + cin >> n >> a >> b >> c; + int dp[n+1] = {}; + dp[0] = 0; + for(int i = 1;i<=n;i++,x = -1,y=-1,z=-1) + { + x = ((i >= a) ? dp[i-a] : -1); + y = ((i >= b) ? dp[i-b] : -1); + z = ((i >= c) ? dp[i-c] : -1); + if(x+y+z == -3) + dp[i] = -1; + else + dp[i] = max({x,y,z}) + 1; + } + cout << dp[n]; + return 0; + } +*/ \ No newline at end of file diff --git a/Java/Recursion/Smallest_power_of_x_less_than_equal_to_N.java b/Java/Recursion/Smallest_power_of_x_less_than_equal_to_N.java new file mode 100644 index 00000000..5a970013 --- /dev/null +++ b/Java/Recursion/Smallest_power_of_x_less_than_equal_to_N.java @@ -0,0 +1,18 @@ +import java.util.*; +public class Smallest_power_of_x_less_than_equal_to_N // O(floor(Logx(N))) +{ + static int power(int N, int x) + { + if (N < x) + return 0; + return 1 + power(N / x, x); + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter the Number N\nAnd the base X for which\nYou want to know smallest power P\nLess than or equal to N\n X^P <= N"); + int N = I.nextInt(), x = I.nextInt(); + System.out.println(power(N, x)); + I.close(); + } +} diff --git a/Java/Recursion/Subset_Sum.java b/Java/Recursion/Subset_Sum.java new file mode 100644 index 00000000..6ab62f9b --- /dev/null +++ b/Java/Recursion/Subset_Sum.java @@ -0,0 +1,24 @@ +import java.util.*; +class Subset_Sum +{ + static int subset(int arr[],int s, int i, int n) + { + if(i == n) + return ((s == 0) ? 1 : 0); + return subset(arr, s - arr[i], i+1, n) + subset(arr, s ,i+1, n); + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter the number of elements you want in the array"); + int N = I.nextInt(); + System.out.println("Enter the elements of the array"); + int a[] = new int[N]; + for(int i = 0; i < N; i++) + a[i] = I.nextInt(); + System.out.println("Enter the value of sum, you want to check in the array"); + int sum = I.nextInt(); + System.out.println("You have " + subset(a,sum,0,N) + " subsets in the array that can yield the given sum"); + I.close(); + } +} diff --git a/Java/Recursion/Subset_gen.java b/Java/Recursion/Subset_gen.java new file mode 100644 index 00000000..d0a65308 --- /dev/null +++ b/Java/Recursion/Subset_gen.java @@ -0,0 +1,24 @@ +import java.util.*; +class Subset_gen // Same as generating all the subsequence of a string +{ // Produces 2^N outputs + static void subset(String s, int i, int n, String a) // Same thing you have to follow that at a time, u can either choose a character or leave it + { + if (i == n) + { + System.out.println(a); + return; + } + subset(s, i + 1, n, a + s.charAt(i)); + subset(s, i + 1, n, a); + } + + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("ENTER A STRING"); + String s = I.nextLine(); // Considering all characters are distinct + System.out.println(); + subset(s, 0, s.length(), ""); + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/Sum_Of_Digits.java b/Java/Recursion/Sum_Of_Digits.java new file mode 100644 index 00000000..e08ac238 --- /dev/null +++ b/Java/Recursion/Sum_Of_Digits.java @@ -0,0 +1,18 @@ +import java.util.*; //Getting the sum of digits + +class Sum_of_Digits { + static int rec_sum(int n) + { + if (n == 0) + return 0; + return n % 10 + rec_sum(n / 10); //for product of digits chnge '+' with '*' + } + + public static void main(String args[]) { + Scanner I = new Scanner(System.in); + System.out.println("Enter A Number"); + int n = I.nextInt(); + System.out.println("Your Sum Of Digits is: " + rec_sum(n)); + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/Sum_of_first_N.java b/Java/Recursion/Sum_of_first_N.java new file mode 100644 index 00000000..3c4b2522 --- /dev/null +++ b/Java/Recursion/Sum_of_first_N.java @@ -0,0 +1,21 @@ +import java.util.*; +class Sum_of_first_N // Sum of first N natural numbers +{ + public static int sum; // Global variable + static void summation(int n) //n+1 system calls + { + if (n <= 0) + return; + sum += n; + summation(n - 1); + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter the Number N"); + int n = I.nextInt(); + summation(n); + System.out.println("The sum of first N number is : " + sum); + I.close(); + } +} \ No newline at end of file diff --git a/Java/Recursion/Tower_of_Hanoi.java b/Java/Recursion/Tower_of_Hanoi.java new file mode 100644 index 00000000..870a2857 --- /dev/null +++ b/Java/Recursion/Tower_of_Hanoi.java @@ -0,0 +1,44 @@ +/* + * A set up where there are 3 towers and discs of different sizes are to be transported from tower 1 to tower 3 + * Rules are Simple, solution isnt + * Rule 1: Only one disc moves at a time, + * Rule 2: Only the top most disc in a tower can be moved + * Rule 3: No larger disc can be placed on top of a smaller disc + */ +import java.util.*; + +class Tower_of_Hanoi { + // public static long step = 0; Global variable to get the number of steps, if + // you dont know the formula + + static void TOH(int n, char a, char b, char c) // TOH(n-1, source, using, destination); + { + /* + * The idea here is to get the (N - 1) discs [For the current value of N], from + * Tower A to Tower B using the Tower C + * Then Taking the Nth disc from Tower A to Tower C, the largest disc only moves + * once + * Then again getting the (N - 1) discs [For the current value of N], from Tower + * B to Tower C using the Tower A + */ + if (n == 0) + return; + // keeps switching B and C + TOH(n - 1, a, c, b); // The idea here is to get the n-1 discs from Tower A to tower B, using tower C + // step++; + System.out.println(a + " " + c); // Then send the Nth disc to tower C + TOH(n - 1, b, a, c); // Then again send the n-1 discs from tower B to Tower C using Tower A + } + + public static void main(String args[]) { + Scanner I = new Scanner(System.in); + //System.out.println("Enter the number of discs you want in the tower"); + int n = I.nextInt(); + System.out.println((long) (Math.pow(2, n) - 1)); + TOH(n, '1', '2', '3'); + //System.out.println("It took: " + (long) (Math.pow(2, n) - 1) + " Steps to do the task"); // Replace step with + // formula if you dont + // remember it + I.close(); + } +} diff --git a/Java/Recursion/joshephus.java b/Java/Recursion/joshephus.java new file mode 100644 index 00000000..8d96f2dc --- /dev/null +++ b/Java/Recursion/joshephus.java @@ -0,0 +1,37 @@ +import java.util.*; +class joshephus +{ + static int Jos(int n, int k) + { + if(n == 1) + return 1; + return (Jos(n - 1,k) + k-1) % n + 1; + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + int n = I.nextInt(), k = I.nextInt(); + System.out.println(Jos(n,k)); + I.close(); + } +} +/*when starting pos is 0 +import java.util.*; +class joshephus +{ + static int Jos(int n, int k) + { + if(n == 1) + return 0; + return (Jos(n - 1,k) + k) % n; + } + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + int n = I.nextInt(), k = I.nextInt(); + System.out.println(Jos(n,k)); + I.close(); + } +} + + */ \ No newline at end of file diff --git a/Java/Recursion/one_to_N.java b/Java/Recursion/one_to_N.java new file mode 100644 index 00000000..42d3e3be --- /dev/null +++ b/Java/Recursion/one_to_N.java @@ -0,0 +1,28 @@ +import java.util.*; +class one_to_N //Head Recursion +{ + static void rec(int N) //No other variable needed + { + if(N == 0) + return; + rec(N-1); + System.out.print(N + " "); + } + /* //Tail Recursion alternative + static void rec(int N, int i) //No other variable needed + { + if(i == N) + return; + System.out.print(N + " "); + rec(N,i+1); + } //Will be called using rec(N,0); + */ + public static void main(String args[]) + { + Scanner I = new Scanner(System.in); + System.out.println("Enter the value of N"); + int N = I.nextInt(); + rec(N); + I.close(); + } +} diff --git a/Java/SODUKO-SOLVER/soduko-solver.java b/Java/SODUKO-SOLVER/soduko-solver.java new file mode 100644 index 00000000..ad1821eb --- /dev/null +++ b/Java/SODUKO-SOLVER/soduko-solver.java @@ -0,0 +1,123 @@ +package com.ssaurel.sudoku; + +public class Sudoku { + + // we define a simple grid to solve. Grid is stored in a 2D Array + public static int[][] GRID_TO_SOLVE = { + {9,0,0,1,0,0,0,0,5}, + {0,0,5,0,9,0,2,0,1}, + {8,0,0,0,4,0,0,0,0}, + {0,0,0,0,8,0,0,0,0}, + {0,0,0,7,0,0,0,0,0}, + {0,0,0,0,2,6,0,0,9}, + {2,0,0,3,0,0,0,0,6}, + {0,0,0,2,0,0,9,0,0}, + {0,0,1,9,0,4,5,7,0}, + }; + + private int[][] board; + public static final int EMPTY = 0; // empty cell + public static final int SIZE = 9; // size of our Sudoku grids + + public Sudoku(int[][] board) { + this.board = new int[SIZE][SIZE]; + + for (int i = 0; i < SIZE; i++) { + for (int j = 0; j < SIZE; j++) { + this.board[i][j] = board[i][j]; + } + } + } + + // we check if a possible number is already in a row + private boolean isInRow(int row, int number) { + for (int i = 0; i < SIZE; i++) + if (board[row][i] == number) + return true; + + return false; + } + + // we check if a possible number is already in a column + private boolean isInCol(int col, int number) { + for (int i = 0; i < SIZE; i++) + if (board[i][col] == number) + return true; + + return false; + } + + // we check if a possible number is in its 3x3 box + private boolean isInBox(int row, int col, int number) { + int r = row - row % 3; + int c = col - col % 3; + + for (int i = r; i < r + 3; i++) + for (int j = c; j < c + 3; j++) + if (board[i][j] == number) + return true; + + return false; + } + + // combined method to check if a number possible to a row,col position is ok + private boolean isOk(int row, int col, int number) { + return !isInRow(row, number) && !isInCol(col, number) && !isInBox(row, col, number); + } + + // Solve method. We will use a recursive BackTracking algorithm. + // we will see better approaches in next video :) + public boolean solve() { + for (int row = 0; row < SIZE; row++) { + for (int col = 0; col < SIZE; col++) { + // we search an empty cell + if (board[row][col] == EMPTY) { + // we try possible numbers + for (int number = 1; number <= SIZE; number++) { + if (isOk(row, col, number)) { + // number ok. it respects sudoku constraints + board[row][col] = number; + + if (solve()) { // we start backtracking recursively + return true; + } else { // if not a solution, we empty the cell and we continue + board[row][col] = EMPTY; + } + } + } + + return false; // we return false + } + } + } + + return true; // sudoku solved + } + + public void display() { + for (int i = 0; i < SIZE; i++) { + for (int j = 0; j < SIZE; j++) { + System.out.print(" " + board[i][j]); + } + + System.out.println(); + } + + System.out.println(); + } + + public static void main(String[] args) { + Sudoku sudoku = new Sudoku(GRID_TO_SOLVE); + System.out.println("Sudoku grid to solve"); + sudoku.display(); + + // we try resolution + if (sudoku.solve()) { + System.out.println("Sudoku Grid solved with simple BT"); + sudoku.display(); + } else { + System.out.println("Unsolvable"); + } + } + +} diff --git a/Java/Searching-Algorithms/BFS/BST.java b/Java/SearchingAlgorithms/BFS/BST.java similarity index 99% rename from Java/Searching-Algorithms/BFS/BST.java rename to Java/SearchingAlgorithms/BFS/BST.java index 5ae644cd..87c374b2 100644 --- a/Java/Searching-Algorithms/BFS/BST.java +++ b/Java/SearchingAlgorithms/BFS/BST.java @@ -1,6 +1,6 @@ import java.util.LinkedList; import java.util.ArrayList; -public class BST{ +public class BST { Node root; BST(){ diff --git a/Java/Searching-Algorithms/BinarySearch.java b/Java/SearchingAlgorithms/BinarySearch.java similarity index 100% rename from Java/Searching-Algorithms/BinarySearch.java rename to Java/SearchingAlgorithms/BinarySearch.java diff --git a/Java/SearchingAlgorithms/BinarySearchSQRT.java b/Java/SearchingAlgorithms/BinarySearchSQRT.java new file mode 100644 index 00000000..0558ee3b --- /dev/null +++ b/Java/SearchingAlgorithms/BinarySearchSQRT.java @@ -0,0 +1,43 @@ +package Searching; + + +public class BinarySearchSQRT { + public static void main(String[] args) { + int n = 40; + int p = 3; + System.out.printf("%.3f",sqrt(n,p)); + + } + //time complexity: O(log n) + static double sqrt(int n, int p) + { + int start = 0; + int end = n; + double root = 0.0; + + while(start <= end) + { + int m = start + (end - start) / 2; + + if(m * m == n) + return m; + if(m * m > n) + { + end = m - 1; + } + else + start = m + 1; + } + double incr = 0.1; + for(int i = 0; i < p; i++) + { + while(root * root <= n) + root += incr; + root -= incr; + incr /= 10; + + } + return root; + } + } + diff --git a/Java/Searching-Algorithms/LinearSearch.java b/Java/SearchingAlgorithms/LinearSearch.java similarity index 100% rename from Java/Searching-Algorithms/LinearSearch.java rename to Java/SearchingAlgorithms/LinearSearch.java diff --git a/Java/Searching-Algorithms/oderAgonosticBinarySearch.java b/Java/SearchingAlgorithms/OderAgonosticBinarySearch.java similarity index 100% rename from Java/Searching-Algorithms/oderAgonosticBinarySearch.java rename to Java/SearchingAlgorithms/OderAgonosticBinarySearch.java diff --git a/Java/Searching-Algorithms/TernarySearch.java b/Java/SearchingAlgorithms/TernarySearch.java similarity index 100% rename from Java/Searching-Algorithms/TernarySearch.java rename to Java/SearchingAlgorithms/TernarySearch.java diff --git a/Java/Sorting Techniques/Bubble_Sort.java b/Java/SortingTechniques/BubbleSort.java similarity index 100% rename from Java/Sorting Techniques/Bubble_Sort.java rename to Java/SortingTechniques/BubbleSort.java diff --git a/Java/Sorting Techniques/CountSort.java b/Java/SortingTechniques/CountSort.java similarity index 100% rename from Java/Sorting Techniques/CountSort.java rename to Java/SortingTechniques/CountSort.java diff --git a/Java/Sorting Techniques/Cyclic_Sort.java b/Java/SortingTechniques/CyclicSort.java similarity index 93% rename from Java/Sorting Techniques/Cyclic_Sort.java rename to Java/SortingTechniques/CyclicSort.java index 0185fd85..aad7a6c2 100644 --- a/Java/Sorting Techniques/Cyclic_Sort.java +++ b/Java/SortingTechniques/CyclicSort.java @@ -1,4 +1,4 @@ -public class Cyclic_Sort{ +public class CyclicSort { public static void main(String[] args) { //test case int[] arr = {3, 1, 5, 4, 2}; diff --git a/Java/Sorting Techniques/Insertion_Sort b/Java/SortingTechniques/InsertionSort.java similarity index 100% rename from Java/Sorting Techniques/Insertion_Sort rename to Java/SortingTechniques/InsertionSort.java diff --git a/Java/MergeSort b/Java/SortingTechniques/MergeSort similarity index 100% rename from Java/MergeSort rename to Java/SortingTechniques/MergeSort diff --git a/Java/Sorting Techniques/MergeSort_Array.java b/Java/SortingTechniques/MergeSortArray.java similarity index 98% rename from Java/Sorting Techniques/MergeSort_Array.java rename to Java/SortingTechniques/MergeSortArray.java index 4713d0ef..f60a5d54 100644 --- a/Java/Sorting Techniques/MergeSort_Array.java +++ b/Java/SortingTechniques/MergeSortArray.java @@ -1,7 +1,7 @@ /** * Program to Sort an Array using Merge Sort */ -public class MergeSort_Array { +public class MergeSortArray { public static void main(String[] args) { int arr[] = {3,5,0,2,9,1,10,0,5,5,9,8}; diff --git a/Java/Sorting Techniques/QuickSort_Array.java b/Java/SortingTechniques/QuickSortArray.java similarity index 97% rename from Java/Sorting Techniques/QuickSort_Array.java rename to Java/SortingTechniques/QuickSortArray.java index b7c28b5f..bd27190e 100644 --- a/Java/Sorting Techniques/QuickSort_Array.java +++ b/Java/SortingTechniques/QuickSortArray.java @@ -1,7 +1,7 @@ /* Program to Sort an Array Using the QuickSort Sorting Algorithm */ -public class QuickSort_Array { +public class QuickSortArray { public static void main(String[] args) { int arr[] = {1000,6,3,5,2,8,9,12,200}; int n = arr.length; diff --git a/Java/Sorting Techniques/RadixSort.java b/Java/SortingTechniques/RadixSort.java similarity index 100% rename from Java/Sorting Techniques/RadixSort.java rename to Java/SortingTechniques/RadixSort.java diff --git a/Java/SortingTechniques/Recursivebubblesort.java b/Java/SortingTechniques/Recursivebubblesort.java new file mode 100644 index 00000000..99a03f6c --- /dev/null +++ b/Java/SortingTechniques/Recursivebubblesort.java @@ -0,0 +1,20 @@ +import java.util.Arrays; +public class Demo{ + static void bubble_sort(int my_arr[], int len_arr){ + if (len_arr == 1) + return; + for (int i=0; i my_arr[i+1]){ + int temp = my_arr[i]; + my_arr[i] = my_arr[i+1]; + my_arr[i+1] = temp; + } + bubble_sort(my_arr, len_arr-1); + } + public static void main(String[] args){ + int my_arr[] = {45, 67, 89, 31, 63, 0, 21, 12}; + bubble_sort(my_arr, my_arr.length); + System.out.println("The array after implementing bubble sort is "); + System.out.println(Arrays.toString(my_arr)); + } +} diff --git a/Java/Sorting Techniques/SelectionSort.java b/Java/SortingTechniques/SelectionSort.java similarity index 100% rename from Java/Sorting Techniques/SelectionSort.java rename to Java/SortingTechniques/SelectionSort.java diff --git a/Java/Stack/BalancedBrackets.java b/Java/Stack/BalancedBrackets.java new file mode 100644 index 00000000..5b6157f0 --- /dev/null +++ b/Java/Stack/BalancedBrackets.java @@ -0,0 +1,32 @@ +//Program to check for Balanced Brackets in Java + +import java.util.Stack; + +public class BalancedBrackets { + public static boolean isBalanced(String expression) { + Stack bracketStack = new Stack<>(); + int n = expression.length(); + for(int i = 0 ; i < n ; i++){ + char bracket = expression.charAt(i); + if(isNotB(bracket)) continue; + if(isOpeningB(bracket)) bracketStack.push(bracket); + else{ + if(!bracketStack.isEmpty() && validOpeningB(bracket) != bracketStack.peek()) return false; + else bracketStack.pop(); + } + } + return bracketStack.isEmpty(); + } + static boolean isNotB(char bracket){ + return !("(){}[]".contains(bracket + "")); + } + static boolean isOpeningB(char bracket){ + return "({[".contains(bracket + ""); + } + static char validOpeningB(char bracket){ + if(bracket == ')') return '('; + if(bracket == '}') return '{'; + if(bracket == ']') return '['; + return '\0'; + } +} \ No newline at end of file diff --git a/Java/Stack/Balanced_Brackets.java b/Java/Stack/Balanced_Brackets.java new file mode 100644 index 00000000..ca014d0c --- /dev/null +++ b/Java/Stack/Balanced_Brackets.java @@ -0,0 +1,38 @@ +//For a given a string expression containing only round brackets or parentheses, check if they are balanced or not. Brackets are said to be balanced if the bracket which opens last, closes first. + +package Stack; +import java.util.Stack; + +public class Balanced_Brackets { + + public static boolean checkBalanced(String str) { + Stack stack = new Stack<>(); + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + if (ch == '(' || ch == '{' || ch == '[') { + stack.push(ch); + } else if( ch=='}' || ch==')' || ch==']' ) { + + if(stack.isEmpty()) { + return false; + } + else if(ch==')' && stack.peek()=='('||ch==']'&& stack.peek()=='['||ch=='}'&& stack.peek()=='{') + stack.pop(); + else { + return false; + } + } + } + if(stack.isEmpty()) { + return true; + } + else { + return false; + } + } + + public static void main(String[] args) { + String string = "{ a + [ b+ (c + d)] + (e + f) }"; + System.out.println(checkBalanced(string)); + } +} diff --git a/Java/Stack/InfixToPostfix/InfixToPostfix_byManik.java b/Java/Stack/InfixToPostfix/InfixToPostfix_byManik.java new file mode 100644 index 00000000..d0793449 --- /dev/null +++ b/Java/Stack/InfixToPostfix/InfixToPostfix_byManik.java @@ -0,0 +1,58 @@ +import java.util.Stack; +import java.util.Scanner; +public class InfixToPostfix_byManik { + + static int precedence(char c){ + switch (c){ + case '+': + case '-': + return 1; //Since '+'&'-' are of same precedence + case '*': + case '/': + return 2; + case '^': + return 3; + } + return -1; + } + + static String infixToPostFix(String expression){ + + String result = ""; + Stack stack = new Stack<>(); + for (int i = 0; i 0){ + while(stack.isEmpty()==false && precedence(stack.peek())>=precedence(c)){ + result += stack.pop(); + } + stack.push(c); + }else if(c==')'){ + char x = stack.pop(); + while(x!='('){ + result += x; + x = stack.pop(); + } + }else if(c=='('){ + stack.push(c); + }else{ + //character is neither operator nor ( + result += c; + } + } + for (int i = 0; i <=stack.size() ; i++) { + result += stack.pop(); + } + return result; + } + + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + System.out.println("Enter the Expression"); + String Input=sc.next(); + System.out.println("Infix Expression: " + Input); + System.out.println("Postfix Expression: " + infixToPostFix(Input)); + } +} \ No newline at end of file diff --git a/Java/Stack/InfixToPrefix.java b/Java/Stack/InfixToPrefix.java new file mode 100644 index 00000000..8f45f8a4 --- /dev/null +++ b/Java/Stack/InfixToPrefix.java @@ -0,0 +1,42 @@ +//Java Program to convert Infix Expression to Prefix +import java.util.Stack; + +public class InfixToPrefix { + public static void main(String[] args) { + System.out.println("1+2+3 -> " + infix2Prefix("1+2+3")); + System.out.println("A^B-(C+D) -> " + infix2Prefix("A^B-(C+D)")); + System.out.println("(P/L+(F*J) -> " + infix2Prefix("(P/L+(F*J)")); + } + public static String infix2Prefix(String expression){ + if(!BalancedBrackets.isBalanced(expression)) return "Invalid Expression"; + Stack operatorStack = new Stack<>(); + StringBuilder prefixExpression = new StringBuilder(); + int n = expression.length(); + for(int i = n - 1 ; i >= 0 ; i--){ + char scanned = expression.charAt(i); + if(Character.isLetterOrDigit(scanned)) prefixExpression.append(scanned); + else if(scanned == ')') operatorStack.push(scanned); + else if(scanned == '('){ + while(!operatorStack.isEmpty() && operatorStack.peek() != ')'){ + prefixExpression.append(operatorStack.pop()); + } + if(!operatorStack.isEmpty()) operatorStack.pop(); + } + else if(operatorStack.isEmpty() || operatorStack.peek() == ')') operatorStack.push(scanned); + else{ + while(!operatorStack.isEmpty() && precedence(operatorStack.peek()) < precedence(scanned)){ + prefixExpression.append(operatorStack.pop()); + } + operatorStack.push(scanned); + } + } + while(!operatorStack.isEmpty()) prefixExpression.append(operatorStack.pop()); + return prefixExpression.reverse().toString(); + } + static int precedence(char operator){ + if(operator == '^') return 3; + if(operator == '*' || operator == '/') return 2; + if(operator == '+' || operator == '-') return 1; + return 0; + } +} diff --git a/Java/Stack/Merge_Intervals.java b/Java/Stack/MergeIntervals.java similarity index 100% rename from Java/Stack/Merge_Intervals.java rename to Java/Stack/MergeIntervals.java diff --git a/Java/Stack/infix-to-postfix.md b/Java/Stack/infix-to-postfix.md new file mode 100644 index 00000000..a8c75739 --- /dev/null +++ b/Java/Stack/infix-to-postfix.md @@ -0,0 +1,64 @@ +# Infix Notation + +Infix is the day to day notation that we use of format A + B type. The general form can be classified as (a op b) where a and b are operands(variables) and op is Operator. + +# Postfix Notation + +Postfix is notation that compiler uses/converts to while reading left to right and is of format AB+ type. The general form can be classified as (ab op) where a and b are operands(variables) and op is Operator. + +## Code + +``` +import java.util.Stack; + +public class InfixtoPostfix { + public static void main(String[] args) { + String exp = "a+b*(c^d-e)^(f+g*h)-i"; + System.out.println(infixToPostfix(exp)); + } + public static int Precidense(char ch) { + switch (ch){ + case '+': + case '-': + return 1; + + case '*': + case '/': + return 2; + + case '^': + return 3; + } + return -1; + } + + public static String infixToPostfix(String exp) { + String result = ""; + Stack stack = new Stack<>(); + + for (char c:exp.toCharArray()) { + if (Character.isLetterOrDigit(c)) + result += c; + else if (c == '(') + stack.push(c); + else if (c == ')') { + while (!stack.isEmpty() && stack.peek() != '(') + result += stack.pop(); + stack.pop(); + } + else {// an operator is encountered + while (!stack.isEmpty() && Precidense(c) <= Precidense(stack.peek())) + result += stack.pop(); + stack.push(c); + } + + } + while (!stack.isEmpty()){ + if(stack.peek() == '(') + return "Invalid Expression"; + result += stack.pop(); + } + return result; + } +} +``` diff --git a/Java/Stack/reverseasttring.cpp b/Java/Stack/reverseasttring.cpp new file mode 100644 index 00000000..45b4673f --- /dev/null +++ b/Java/Stack/reverseasttring.cpp @@ -0,0 +1,81 @@ +#include +#include +using namespace std; +stack st; +//pushin function to insert elements at correct position +void pushin(int t){ + if(st.size()==0){ + st.push(t); + return; + } + else{ + int val=st.top(); + st.pop(); + pushin(t); + st.push(val); + return; + } +} +//reverse function +void reverse(){ + if(st.size()==1)return; + int temp=st.top(); + st.pop(); + reverse(); + pushin(temp); + return; +} + +// Driver Code +int main() +{ + + // push elements into + // the stack + st.push(1); + st.push(2); + st.push(3); + st.push(4); + + cout<<"Original Stack"<v; + while(!st.empty()) + { + int p=st.top(); + st.pop(); + v.push_back(p); + } + + //display of reversed stack + for(int i=0;i ch2 = new ArrayList<>(); - - int maincount = 0; - - for(int i=0; i ch2 = new ArrayList<>(); + + int maincount = 0; + + for(int i=0; i st = new Stack<>(); + s+=" "; + String str = ""; + String ans=""; + for(int i =0;i nums[mid]) - start = mid + 1; - else - return mid; - } - return -1; - } -} diff --git a/Java/ceiling.java b/Java/ceiling.java new file mode 100644 index 00000000..3f1c1d0e --- /dev/null +++ b/Java/ceiling.java @@ -0,0 +1,36 @@ +public class Ceiling { + + public static void main(String[] args) { + int[] arr = {2, 3, 5, 9, 14, 16, 18}; + int target = 15; + int ans = ceiling(arr, target); + System.out.println(ans); + } + + // return the index of smallest no >= target + static int ceiling(int[] arr, int target) { + + // but what if the target is greater than the greatest number in the array + if (target > arr[arr.length - 1]) { + return -1; + } + int start = 0; + int end = arr.length - 1; + + while(start <= end) { + // find the middle element +// int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java + int mid = start + (end - start) / 2; + + if (target < arr[mid]) { + end = mid - 1; + } else if (target > arr[mid]) { + start = mid + 1; + } else { + // ans found + return mid; + } + } + return start; + } +} diff --git a/LeetCode Solutions/154_Find__Minimum_in_Rotated_Sorted_Array_II.cpp b/LeetCode Solutions/154_Find__Minimum_in_Rotated_Sorted_Array_II.cpp new file mode 100644 index 00000000..b13b6fa3 --- /dev/null +++ b/LeetCode Solutions/154_Find__Minimum_in_Rotated_Sorted_Array_II.cpp @@ -0,0 +1,21 @@ +class Solution +{ +public: + int findMin(vector &nums) + { + set st(nums.begin(), nums.end()); + vector v(st.begin(), st.end()); + // predicate nums[x]>=nums[0] /// tttttffffff aim--> finding first f + int low = 0, high = v.size() - 1; + while (low < high) + { + int mid = low + (high - low) / 2; + if (v[mid] >= v[0]) + low = mid + 1; + else + high = mid; + } + // turn low; + return min(v[0], v[low]); + } +}; \ No newline at end of file diff --git a/LeetCode Solutions/240_Search_a_2D_Matrix_II.cpp b/LeetCode Solutions/240_Search_a_2D_Matrix_II.cpp new file mode 100644 index 00000000..05988bf5 --- /dev/null +++ b/LeetCode Solutions/240_Search_a_2D_Matrix_II.cpp @@ -0,0 +1,51 @@ +// Name : Search_a_2D_Matrix_II +// Leetcode Problem 240 (Medium) +// Url : https://leetcode.com/problems/search-a-2d-matrix-ii/ + +// Approach 1 (Best Approach) +class Solution +{ +public: + bool searchMatrix(vector> &matrix, int target) + { + int j = matrix[0].size() - 1, i = 0; + while (1) + { + if (j < 0 || i > matrix.size() - 1) + return 0; + if (matrix[i][j] > target) + j--; + else if (matrix[i][j] < target) + i++; + else + return 1; + } + if (matrix[i][j] == target) + return 1; + return 0; + } +}; + +// Approach 2 + +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + for(int i=0;itarget) + return 0; + int low=0,high=matrix.size()-1; + while(low> &mt) + { + int n = mt.size(); + int tmp = 0; + for (int i = 0; i < n; i++) + { + for (int j = tmp; j < n; j++) + { + swap(mt[i][j], mt[j][i]); + } + tmp++; + } + for (int i = 0; i < n; i++) + { + for (int j = 0; j < (n / 2); j++) + { + swap(mt[i][j], mt[i][n - j - 1]); + } + } + } +}; diff --git a/LeetCode Solutions/918. Maximum Sum Circular Subarray.java b/LeetCode Solutions/918. Maximum Sum Circular Subarray.java new file mode 100644 index 00000000..34f90531 --- /dev/null +++ b/LeetCode Solutions/918. Maximum Sum Circular Subarray.java @@ -0,0 +1,23 @@ +/* +918. Maximum Sum Circular Subarray + +Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. +Input: nums = [1,-2,3,-2] +Output: 3 + +https://leetcode.com/problems/maximum-sum-circular-subarray/ +*/ + +class Solution { + public int maxSubarraySumCircular(int[] A) { + int total = 0, maxSum = A[0], curMax = 0, minSum = A[0], curMin = 0; + for (int a : A) { + curMax = Math.max(curMax + a, a); + maxSum = Math.max(maxSum, curMax); + curMin = Math.min(curMin + a, a); + minSum = Math.min(minSum, curMin); + total += a; + } + return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum; + } +} diff --git a/LeetCode Solutions/LargestRectangleInHistogram.md b/LeetCode Solutions/LargestRectangleInHistogram.md new file mode 100644 index 00000000..398c592d --- /dev/null +++ b/LeetCode Solutions/LargestRectangleInHistogram.md @@ -0,0 +1,62 @@ +class Solution { +private: + vector nextSmallerElement(vector arr, int n) { + stack s; + s.push(-1); + vector ans(n); + + for(int i=n-1; i>=0 ; i--) { + int curr = arr[i]; + while(s.top() != -1 && arr[s.top()] >= curr) + { + s.pop(); + } + //ans is stack ka top + ans[i] = s.top(); + s.push(i); + } + return ans; + } + + vector prevSmallerElement(vector arr, int n) { + stack s; + s.push(-1); + vector ans(n); + + for(int i=0; i= curr) + { + s.pop(); + } + //ans is stack ka top + ans[i] = s.top(); + s.push(i); + } + return ans; + } + +public: + int largestRectangleArea(vector& heights) { + int n= heights.size(); + + vector next(n); + next = nextSmallerElement(heights, n); + + vector prev(n); + prev = prevSmallerElement(heights, n); + + int area = INT_MIN; + for(int i=0; i s; + for(int i=0; ival)) and (r>(root->val))) or ((l>(root->val)) and (r<(root->val)))){ + return root; + } + else if((root->val==l) or (root->val==r)){ + return root; + } + else if(((root->val)>l) and ((root->val)>r)){ + return lca(root->left,l,r); + } + return lca(root->right,l,r); + + + } + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + return lca(root,p->val,q->val); +    } +}; \ No newline at end of file diff --git a/LeetCode Solutions/merge interval.java b/LeetCode Solutions/merge interval.java new file mode 100644 index 00000000..a772ea53 --- /dev/null +++ b/LeetCode Solutions/merge interval.java @@ -0,0 +1,56 @@ +public static List < Interval > mergeIntervals(Interval[] intervals) { + int n = intervals.length; + List < Interval > res = new ArrayList(); + + boolean vis[] = new boolean[n]; + + for (int i = 0; i < n; i++) { + if (vis[i]) { + continue; + } + + vis[i] = true; + int minS = intervals[i].start; + int maxE = intervals[i].finish; + + while (true) { + int c = 0; + + for (int j = 0; j < n; j++) { + if (!vis[j] && isOverlap(minS, maxE, intervals[j])) { + vis[j] = true; + minS = Math.min(minS, intervals[j].start); + maxE = Math.max(maxE, intervals[j].finish); + c++; + } + } + + if (c == 0) { + break; + } + } +res.add(new Interval(minS, maxE)); + } + + Collections.sort(res, new Comparator < Interval > () { + + public int compare(Interval a, Interval b) { + if (a.start == b.start) { + return a.finish - b.finish; + } + + return a.start - b.start; + } + + }); + + return res; +} + +public static boolean isOverlap(int minS, int maxE, Interval i) { + if (minS > i.finish || maxE < i.start) { + return false; + } + + return true; +} diff --git a/LeetCode Solutions/minDepth.txt b/LeetCode Solutions/minDepth.txt new file mode 100644 index 00000000..5911b7ca --- /dev/null +++ b/LeetCode Solutions/minDepth.txt @@ -0,0 +1,32 @@ +Problem Link - https://leetcode.com/problems/minimum-depth-of-binary-tree/description/ +/** + * 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: + int d=INT_MAX; + int minDepth(TreeNode* root) { + if(root==NULL){ + return 0; + } + if(root->left!=NULL and root->right!=NULL){ + int l= minDepth(root->left); + int r= minDepth(root->right); + return min(l,r)+1;} + else if(root->left==NULL){ + return minDepth(root->right)+1; + } + else if(root->right==NULL){ + return minDepth(root->left)+1; + } + return 1; +    } +}; \ No newline at end of file diff --git a/LeetCode Solutions/rightSideView.txt b/LeetCode Solutions/rightSideView.txt new file mode 100644 index 00000000..ddcdbcc2 --- /dev/null +++ b/LeetCode Solutions/rightSideView.txt @@ -0,0 +1,36 @@ +Problem Link - https://leetcode.com/problems/binary-tree-right-side-view/ +/** + * 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: + vectorv; + int rightView(TreeNode *root,int level,int &maxLevel){ + if (root == NULL) + { + return 0; + } + if (level > maxLevel) + { + v.push_back(root->val); + maxLevel = level; + } + rightView(root->right, level + 1, maxLevel); + rightView(root->left, level + 1, maxLevel); + return 0; + } + vector rightSideView(TreeNode* root) { + int level=0; + int maxLevel=-1; + rightView(root,level,maxLevel); + return v; +    } +}; \ No newline at end of file diff --git a/LeetCode Solutions/sortedArrayToBST.txt b/LeetCode Solutions/sortedArrayToBST.txt new file mode 100644 index 00000000..047e043d --- /dev/null +++ b/LeetCode Solutions/sortedArrayToBST.txt @@ -0,0 +1,30 @@ +Problem Link - https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ +/** + * 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* h(vector& nums,int s,int e){ + if(s>e){ + return NULL; + } + int mid=(s+e)/2; + TreeNode* root=new TreeNode(nums[mid]); + root->left=h(nums,s,mid-1); + root->right=h(nums,mid+1,e); + return root; + } + TreeNode* sortedArrayToBST(vector& nums) { + int s=0; + int e=nums.size()-1; + return h(nums,s,e); +    } +}; \ No newline at end of file diff --git a/Leetcode-solutions/Binary-search/ArrangingCoins.java b/Leetcode-solutions/Binary-search/ArrangingCoins.java new file mode 100644 index 00000000..7a934578 --- /dev/null +++ b/Leetcode-solutions/Binary-search/ArrangingCoins.java @@ -0,0 +1,41 @@ +public class ArrangingCoins { + public static void main(String[] args) { + int n = 1; + System.out.println(arrangeCoins2(n)); + } + + static int arrangeCoins(int n) { + long s = 1; + long e = n; + + while(s <= e){ + long m = s + (e-s)/2; + long coinsNeeded = (m * (m+1)) /2; + + if(coinsNeeded <= n){ + s = m+1; + } else{ + e= m-1; + } + } + return (int)e; + } + + static int arrangeCoins2(int n){ + long s = 1; + long e = n; + + while(s < e){ + long m = s + (e-s)/2; + long coinsNeeded = (m * (m+1)) /2; + + if(coinsNeeded <= n){ + s = m+1; + } else{ + e = m; + } + } + return (s * (s+1)) /2 <= n ? (int)s : (int)s-1; + } + +} diff --git a/Leetcode-solutions/Binary-search/Best Time to Buy and Sell Stock.cpp b/Leetcode-solutions/Binary-search/Best Time to Buy and Sell Stock.cpp new file mode 100644 index 00000000..95f39e72 --- /dev/null +++ b/Leetcode-solutions/Binary-search/Best Time to Buy and Sell Stock.cpp @@ -0,0 +1,127 @@ +/** +Say you have an array for which the ith element is the price of a given stock on day i. + +If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. + +Note that you cannot sell a stock before you buy one. + +Example 1: + +Input: [7,1,5,3,6,4] +Output: 5 +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Not 7-1 = 6, as selling price needs to be larger than buying price. +Example 2: + +Input: [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transaction is done, i.e. max profit = 0. +**/ + +//Runtime: 8 ms, faster than 99.32% of C++ online submissions for Best Time to Buy and Sell Stock. +//Memory Usage: 9.4 MB, less than 94.64% of C++ online submissions for Best Time to Buy and Sell Stock. + +class Solution { +public: + int maxProfit(vector& prices) { + if(prices.size() == 0) return 0; + + int ans = 0; + + int start = prices[0], end = prices[0]; + + for(int i = 0; i < prices.size(); i++){ + if(prices[i] < start){ + //restart as session + ans = max(ans, end - start); + start = prices[i]; + end = prices[i]; + }else{ + //continue current session + end = max(end, prices[i]); + } + } + ans = max(ans, end - start); + return ans; + } +}; + +/** +Approach 2: One Pass +Algorithm + +Say the given array is: + +[7, 1, 5, 3, 6, 4] + +If we plot the numbers of the given array on a graph, we get: + +The points of interest are the peaks and valleys in the given graph. We need to find the largest peak following the smallest valley. We can maintain two variables - minprice and maxprofit corresponding to the smallest valley and maximum profit (maximum difference between selling price and minprice) obtained so far respectively. +**/ + +/** +Time complexity : O(n). Only a single pass is needed. +Space complexity : O(1). Only two variables are used. +**/ + + +class Solution { +public: + int maxProfit(vector& prices) { + int valley = INT_MAX; + int ans = 0; + for(int i = 0; i < prices.size(); i++){ + if(prices[i] < valley){ + valley = prices[i]; + }else if(prices[i] - valley > ans){ + ans = prices[i] - valley; + } + } + return ans; + } +}; + +//Greedy +//Runtime: 4 ms, faster than 97.14% of C++ online submissions for Best Time to Buy and Sell Stock. +//Memory Usage: 7.5 MB, less than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock. +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + + int maxToTail = 0; + int profit, maxProfit = 0; + + for(int i = n-1; i >= 0; i--){ + maxToTail = max(maxToTail, prices[i]); + profit = max(maxToTail - prices[i], 0); + maxProfit = max(maxProfit, profit); + } + + return maxProfit; + } +}; + +//Greedy +//Runtime: 8 ms, faster than 49.52% of C++ online submissions for Best Time to Buy and Sell Stock. +//Memory Usage: 13 MB, less than 5.51% of C++ online submissions for Best Time to Buy and Sell Stock. +class Solution { +public: + int maxProfit(vector& prices) { + int ans = 0; + int buy = INT_MAX; + int cash = 0; + + for(int price : prices){ + /* + meaningless for first iteration, + in which buy is not set + */ + cash = max(cash, price-buy); + buy = min(buy, price); + ans = max(ans, cash); + } + + return ans; + } +}; diff --git a/Leetcode-solutions/Binary-search/CountNegGrid.java b/Leetcode-solutions/Binary-search/CountNegGrid.java new file mode 100644 index 00000000..b691fd1d --- /dev/null +++ b/Leetcode-solutions/Binary-search/CountNegGrid.java @@ -0,0 +1,21 @@ +public class CountNegGrid { + public static void main(String[] args) { + + } + + static int countNegatives(int[][] grid) { + int s = 0; + int e = grid[0].length-1; + int count = 0; + + while(s < grid.length && e >= 0){ + if(grid[s][e] < 0){ + count += grid.length - s; + e--; + } else{ + s++; + } + } + return count; + } +} diff --git a/Leetcode-solutions/Binary-search/FirstLastPos.java b/Leetcode-solutions/Binary-search/FirstLastPos.java new file mode 100644 index 00000000..baa4418e --- /dev/null +++ b/Leetcode-solutions/Binary-search/FirstLastPos.java @@ -0,0 +1,47 @@ +import java.util.Arrays; + +public class FirstLastPos { + public static void main(String[] args) { + int[] nums = {5,7,7,8,8,10}; + int target = 8; + int[] ans = firstLastPosition(nums, target); + System.out.println( Arrays.toString(ans) ); + } + + static int[] firstLastPosition(int[] nums, int target){ + int[] ans = {-1, -1}; + + ans[0] = serach(nums, target, true); + if(ans[0] == -1){ + return ans; + } + ans[1] = serach(nums, target, false); + return ans; + } + + static int serach(int[] nums, int target, boolean findingFirst){ + int s = 0; + int e = nums.length-1; + int ans = -1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(nums[m] == target){ + ans = m; + + if( findingFirst ){ + e = m-1; + } else{ + s = m+1; + } + } else if(nums[m] < target){ + s = m+1; + } else{ + e = m-1; + } + } + + return ans; + } +} diff --git a/Leetcode-solutions/Binary-search/FirstbadVersion.java b/Leetcode-solutions/Binary-search/FirstbadVersion.java new file mode 100644 index 00000000..ed154ee7 --- /dev/null +++ b/Leetcode-solutions/Binary-search/FirstbadVersion.java @@ -0,0 +1,43 @@ +public class FirstbadVersion { + public static void main(String[] args) { + int n = 1; + System.out.println( firstBadVersion2(n)); + } + + static int firstBadVersion(int n) { + int s = 1; + int e = n; + + while(s <= e){ + int m = s + (e-s)/2; + + if( isBadVersion(m) ){ + e = m-1; + } else{ + s = m+1; + } + } + + return s; + } + + static int firstBadVersion2(int n){ + int s = 1; + int e = n; + + while(s < e){ + int m = s + (e-s)/2; + + if(isBadVersion(m)){ + e = m; + } else{ + s = m+1; + } + } + return isBadVersion(s) ? s : s+1; + } + + static boolean isBadVersion(int n){ + return 1 == n; + } +} diff --git a/Leetcode-solutions/Binary-search/HIndex.java b/Leetcode-solutions/Binary-search/HIndex.java new file mode 100644 index 00000000..a87ae708 --- /dev/null +++ b/Leetcode-solutions/Binary-search/HIndex.java @@ -0,0 +1,24 @@ +public class HIndex { + public static void main(String[] args) { + int[] citations = {1,2,100}; + System.out.println(hIndex(citations)); + } + + static int hIndex(int[] citations) { + int s = 0; + int e = citations.length-1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(citations[m] >= (citations.length - m) ){ + e = m-1; + } + else{ + s = m+1; + } + } + return citations.length - s; + } + +} diff --git a/Leetcode-solutions/Binary-search/IntersectionOfTwoArrays.java b/Leetcode-solutions/Binary-search/IntersectionOfTwoArrays.java new file mode 100644 index 00000000..b8dbc220 --- /dev/null +++ b/Leetcode-solutions/Binary-search/IntersectionOfTwoArrays.java @@ -0,0 +1,52 @@ +import java.util.ArrayList; +import java.util.Arrays; + +public class IntersectionOfTwoArrays { + public static void main(String[] args) { + + } + + static int[] intersection(int[] nums1, int[] nums2) { + if(nums1.length > nums2.length){ + return intersection(nums2, nums1); + } + ArrayList list = new ArrayList<>(); + Arrays.sort(nums1); + + for(int num : nums2){ + + if(bS(nums1, num)){ + if(!list.contains(num)){ + list.add(num); + } + } + } + + int[] ans = new int[list.size()]; + + for(int i = 0 ; i < list.size() ; i++){ + ans[i] = list.get(i); + } + return ans; + } + + static boolean bS(int[] arr, int target){ + int s = 0; + int e = arr.length-1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(arr[m] == target){ + return true; + } + if(arr[m] < target){ + s = m+1; + } else{ + e = m-1; + } + } + return false; + } + +} diff --git a/Leetcode-solutions/Binary-search/KClosestElement.java b/Leetcode-solutions/Binary-search/KClosestElement.java new file mode 100644 index 00000000..a1cfb3da --- /dev/null +++ b/Leetcode-solutions/Binary-search/KClosestElement.java @@ -0,0 +1,35 @@ +import java.util.ArrayList; +import java.util.List; + +public class KClosestElement { + public static void main(String[] args) { + int[] arr = {1,1,2,2,2,2,2,3,3}; + System.out.println( findClosestElements(arr, 3, 3) ); + } + + static List findClosestElements(int[] arr, int k, int x) { + int s = 0; + int e = arr.length-k; + + while(s < e){ + int m = s + (e-s)/2; + + int indexJustAfterWindow = m+k; + while(indexJustAfterWindow <= e && arr[m] == arr[indexJustAfterWindow] ){ + indexJustAfterWindow++; + } + + if( Math.abs( arr[m] - x ) > Math.abs( x - arr[indexJustAfterWindow] ) ){ + s = m+1; + } else{ + e = m; + } + } + + List list = new ArrayList<>(); + for(int i = s; i < s +k ; i++){ + list.add( arr[i] ); + } + return list; + } +} diff --git a/Leetcode-solutions/Binary-search/KoKoEatingBanana.java b/Leetcode-solutions/Binary-search/KoKoEatingBanana.java new file mode 100644 index 00000000..69eb353d --- /dev/null +++ b/Leetcode-solutions/Binary-search/KoKoEatingBanana.java @@ -0,0 +1,42 @@ +public class KoKoEatingBanana { + public static void main(String[] args) { + int[] piles = {3,6,7,11}; + System.out.println(minEatingSpeed(piles, 8)); + } + + static int minEatingSpeed(int[] piles, int h) { + int s = 1; + int e = piles[0]; + for(int pile : piles){ + e = Math.max(e, pile); + } + + while(s < e){ + int m = s + (e-s)/2; + + if( canEatAllWithSpeed(piles, m, h) ){ + e = m; + } else{ + s = m+1; + } + } + return s; + } + + static boolean canEatAllWithSpeed(int[] piles, int allowedBananas, int h) { + int hoursNeeded = 0; + + for(int pile : piles){ + + // dekh agr mne allow kre h 4 banana in 1 hour or is pile main 10 h to 4 + 4 kha paegi or do bchange to 3 ghnte ab ek cheez dekh simple ye nh kr skti 10 /4 to vo seedha mtlb dedega ki 10 main kitne proper 4 ke piece bnenge baat smjh soch thoda thik h or fir ek check lga liyo ki agr modulo krke 0 nhi aaara to mtlb kya h iska ki abhi kuch bche h allowed se km mtlb 4 se km h to bss hour main 1 plus krde bss ab bss shant dimaag se soch aa jaega smjh or agr allowed to 4 h pr piles h 3 to 3 /4 0 aaega or aage bss ek plus ho jaega and that is right!! + hoursNeeded += pile/allowedBananas; + if(pile % allowedBananas != 0){ + hoursNeeded++; + } + } + + return hoursNeeded <= h; + } + + +} diff --git a/Leetcode-solutions/Binary-search/KthSmallestMultiplicationTable.java b/Leetcode-solutions/Binary-search/KthSmallestMultiplicationTable.java new file mode 100644 index 00000000..e6d850f6 --- /dev/null +++ b/Leetcode-solutions/Binary-search/KthSmallestMultiplicationTable.java @@ -0,0 +1,34 @@ +public class KthSmallestMultiplicationTable { + public static void main(String[] args) { + int m = 3; + int n = 3; + int k = 5; + System.out.println(findKthNumber(m, n, k)); + } + + static int findKthNumber(int m, int n, int k) { + int s = 1; + int e = m * n; + + while(s < e){ + int mid = s + (e-s)/2; + + if( isPotentialK(mid, m, n, k) ){ + e = mid; + } else{ + s = mid + 1; + } + } + return s; // or e as they both are pointing to the same element + } + + static boolean isPotentialK(int potential, int m, int n, int k) { + int count = 0; + for(int i = 1; i <= m ; i++){ + count += Math.min( (potential / i) , n ); //sun ye isliye kyunki ye hr row simply table h 1 se m tk ka, ab mujhe nikalna h hr row mai se 5 ya kisi num se kitne chhote to ye simploe nikl jaega, kse aise ki maan tujhe nikalna h ki 5 se chhote kitne num h 2 ke table mai to nikaal ki 5 2 ke table mai kahan aata h ya uska floor nikaal to ab 5 nhi aata to floor ya fr agr decial mai aaega na 5/2 = 2.5 to point to ht hi jaega int mai to 2 or haan yhi to h 2 ke table mai 5 se chhote 2 num h thike to ab ye potential/i waali baat to smjh aa gyi pr ye min kyu n se, isliye kyunki soch 1 ke table mai 5 se chhote ya baraabar kitne h 5/1 = 5 pr que mai given table to 3 tk jaari hna to mai ye thodi likh skti ki is row mai jisme 3 elements h usme 5 se chhote 5 elements h ab smjh gyi to kya hoga ki agr jada honge to fr wo min 3 ko lega or agr km honge to fr to whi h ans. huh!!! + } + return count >= k; + } + + +} diff --git a/Leetcode-solutions/Binary-search/Longest Substring Without Repeating Characters b/Leetcode-solutions/Binary-search/Longest Substring Without Repeating Characters new file mode 100644 index 00000000..5f901af0 --- /dev/null +++ b/Leetcode-solutions/Binary-search/Longest Substring Without Repeating Characters @@ -0,0 +1,26 @@ +class Solution { +public: + int lengthOfLongestSubstring(string str) { + int n = str.size(); + map mp; + int maxm = 0, prev = -1; + + for (int i = 0; i < n; i++) + { + if (mp.count(str[i]) == 0) + { + mp.insert({str[i], i}); + } + else + { + prev = max(prev, mp[str[i]]); + mp[str[i]] = i; + } + maxm = max(maxm, i - prev); + } + return maxm; + } +}; + +// The idea is checking whenever we find any letter which is repeating we can find previous position and find the diffrence +// we can check "repeating" by maintain hash functions like map diff --git a/Leetcode-solutions/Binary-search/LongestIncrSubSeq.java b/Leetcode-solutions/Binary-search/LongestIncrSubSeq.java new file mode 100644 index 00000000..9e1cf543 --- /dev/null +++ b/Leetcode-solutions/Binary-search/LongestIncrSubSeq.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; + +public class LongestIncrSubSeq { + public static void main(String[] args) { + int[] nums = {1,1,1,1,1,1}; + System.out.println(lengthOfLIS(nums)); + } + + static int lengthOfLIS(int[] nums) { + ArrayList list = new ArrayList<>(); + list.add(nums[0]); + + for(int i = 1 ; i < nums.length ; i++){ + + if( list.get( list.size() -1 ) < nums[i] ){ + list.add(nums[i]); + } else{ + int index = ceil(list, nums[i]); + list.set(index, nums[i]); + } + + } + + return list.size(); + } + + static int ceil(ArrayList list, int target){ + int s = 0; + int e = list.size() -1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(list.get(m) >= target){ + e = m-1; + } else{ + s = m+1; + } + } + return s; + } + +} diff --git a/Leetcode-solutions/Binary-search/MaxSubArraySum.java b/Leetcode-solutions/Binary-search/MaxSubArraySum.java new file mode 100644 index 00000000..e5f40d51 --- /dev/null +++ b/Leetcode-solutions/Binary-search/MaxSubArraySum.java @@ -0,0 +1,27 @@ +public class MaxSubArraySum { + public static void main(String[] args) { + int[] nums = {-2,1,-3,4,-1,2,1,-5,4}; + System.out.println(maxSubArray(nums)); + } + + static int maxSubArray(int[] nums) { + //kadane's algorithm + int max = nums[0]; + int curr = 0; + + for (int num : nums) { + + curr += num; + + if(max < curr){ + max = curr; + } + + if(curr < 0){ + curr = 0; + } + } + + return max; + } +} diff --git a/Leetcode-solutions/Binary-search/MedianOfTwoSortedArrays.java b/Leetcode-solutions/Binary-search/MedianOfTwoSortedArrays.java new file mode 100644 index 00000000..9e8b38dc --- /dev/null +++ b/Leetcode-solutions/Binary-search/MedianOfTwoSortedArrays.java @@ -0,0 +1,37 @@ +public class MedianOfTwoSortedArrays { + public static void main(String[] args) { + + } + + static double findMedianSortedArrays(int[] nums1, int[] nums2) { + if(nums2.length < nums1.length){ + return findMedianSortedArrays(nums2, nums1); + } + + int s = 0; + int e = nums1.length; + + while(s <= e){ + int cut1 = s + (e-s)/2; + int cut2 = (nums1.length + nums2.length) /2 - cut1; + + int l1 = cut1 <= 0 ? Integer.MIN_VALUE : nums1[cut1 - 1]; + int l2 = cut2 <= 0 ? Integer.MIN_VALUE : nums2[cut2 - 1]; + + int r1 = cut1 >= nums1.length ? Integer.MAX_VALUE : nums1[cut1]; + int r2 = cut2 >= nums2.length ? Integer.MAX_VALUE : nums2[cut2]; + + if( l1 > r2 ){ + e = cut1 - 1; + } else if( l2 > r1 ){ + s = cut1 + 1; + } else{ + return (nums1.length + nums2.length) % 2 == 0 ? + (float) ( Math.max(l1, l2) + Math.min(r1, r2) ) / 2 : + Math.min(r1, r2); + } + + } + return -1; + } +} diff --git a/Leetcode-solutions/Binary-search/MinInRotatated2.java b/Leetcode-solutions/Binary-search/MinInRotatated2.java new file mode 100644 index 00000000..60160c2c --- /dev/null +++ b/Leetcode-solutions/Binary-search/MinInRotatated2.java @@ -0,0 +1,34 @@ +public class MinInRotatated2 { + public static void main(String[] args) { + int[] nums = {2,2,0,1}; + System.out.println(findMin(nums)); + } + + static int findMin(int[] nums) { + int s = 0 ; + int e = nums.length-1; + + while (s < e) { + + while(s < e && nums[s] == nums[s+1]){ + s++; + } + while(s < e && nums[e] == nums[e-1]){ + e--; + } + + if(s == e){ + return nums[s]; + } + + int m = s + (e-s) /2; + if(nums[e] > nums[m]){ + e = m; + } else{ + s = m+1; + } + + } + return nums[s]; + } +} diff --git a/Leetcode-solutions/Binary-search/MinInRotatedArray.java b/Leetcode-solutions/Binary-search/MinInRotatedArray.java new file mode 100644 index 00000000..1ca78b9f --- /dev/null +++ b/Leetcode-solutions/Binary-search/MinInRotatedArray.java @@ -0,0 +1,22 @@ +public class MinInRotatedArray { + public static void main(String[] args) { + int[] nums = {3,4,5,1,2}; + System.out.println(findMin(nums)); + } + + static int findMin(int[] nums) { + int s = 0; + int e = nums.length-1; + + while(s < e){ + int m = s + (e-s)/2; + + if( nums[m] < nums[e]){ + e = m; + } else{ + s = m+1; + } + } + return nums[s]; + } +} diff --git a/Leetcode-solutions/Binary-search/MinSizeSubArrSum.java b/Leetcode-solutions/Binary-search/MinSizeSubArrSum.java new file mode 100644 index 00000000..17338bfb --- /dev/null +++ b/Leetcode-solutions/Binary-search/MinSizeSubArrSum.java @@ -0,0 +1,41 @@ +public class MinSizeSubArrSum { + public static void main(String[] args) { + int[] nums = {2,3,1,2,4,3}; + int target = 77; + System.out.println(minSubArrLength(target, nums)); + } + + static int minSubArrLength(int target, int[] nums){ + int s = 1; + int e = nums.length; + + while(s < e){ + int m = s + (e-s)/2; + + if( condition(nums, m, target) ){ + e = m; + } else{ + s = m+1; + } + } + + return condition(nums, s, target) ? s : 0; + } + + static boolean condition(int[] nums, int m, int target) { + for(int i = 0 ; i <= nums.length - m ; i++){ + + int sum = 0; + for(int j = i ; j-i < m ; j++){ + sum += nums[j]; + } + + if(sum >= target){ + return true; + } + } + return false; + } + + +} diff --git a/Leetcode-solutions/Binary-search/PeakElement.java b/Leetcode-solutions/Binary-search/PeakElement.java new file mode 100644 index 00000000..6710c31d --- /dev/null +++ b/Leetcode-solutions/Binary-search/PeakElement.java @@ -0,0 +1,22 @@ +public class PeakElement { + public static void main(String[] args) { + int[] nums = {1,2,3,1}; + System.out.println(findPeakElement(nums)); + } + + static int findPeakElement(int[] nums) { + int s = 0; + int e = nums.length-1; + + while(s < e){ + int m = s + (e-s)/2; + + if(nums[m] > nums[m+1]){ + e = m; + } else{ + s = m+1; + } + } + return s; + } +} diff --git a/Leetcode-solutions/Binary-search/PeakIndex.java b/Leetcode-solutions/Binary-search/PeakIndex.java new file mode 100644 index 00000000..6a97298b --- /dev/null +++ b/Leetcode-solutions/Binary-search/PeakIndex.java @@ -0,0 +1,22 @@ +public class PeakIndex { + public static void main(String[] args) { + int[] arr = {3,4,5,1}; + System.out.println(peakIndexInMountainArray(arr)); + } + + static int peakIndexInMountainArray(int[] arr) { + int s = 0; + int e = arr.length-1; + + while (s < e){ + int m = s + (e-s)/2; + + if(arr[m] > arr[m+1]){ + e = m; + } else{ + s = m+1; + } + } + return s; + } +} diff --git a/Leetcode-solutions/Binary-search/RemoveNthNodeFromEndLL.cpp b/Leetcode-solutions/Binary-search/RemoveNthNodeFromEndLL.cpp new file mode 100644 index 00000000..ccb05f6d --- /dev/null +++ b/Leetcode-solutions/Binary-search/RemoveNthNodeFromEndLL.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + int c=0; + if(!head) return head; + ListNode* run=new ListNode(0), *dup=run; + run->next=head; + ListNode* k=head; + while(k!=NULL) + { + if(c==n) + { + run=run->next; + } + else + c++; + k=k->next; + } + ListNode* temp=run->next; + run->next=run->next->next; + + return dup->next; + } +}; \ No newline at end of file diff --git a/Leetcode-solutions/Binary-search/RotatedBS.java b/Leetcode-solutions/Binary-search/RotatedBS.java new file mode 100644 index 00000000..3a40bcb8 --- /dev/null +++ b/Leetcode-solutions/Binary-search/RotatedBS.java @@ -0,0 +1,35 @@ +public class RotatedBS { + public static void main(String[] args) { + int[] nums = {4,5,6,7,0,1,2}; + int target = 0; + System.out.println(search(nums, target)); + } + + static int search(int[] nums, int target) { + int s = 0; + int e = nums.length-1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(nums[m] == target){ + return m; + } + + if(nums[m] >= nums[s]){ + if(target < nums[m] && target >= nums[s]){ + e = m-1; + } else{ + s = m+1; + } + } else{ + if(target > nums[m] && target <= nums[e]){ + s = m+1; + } else{ + e = m-1; + } + } + } + return -1; + } +} diff --git a/Leetcode-solutions/Binary-search/RotatedBSDuplicates.java b/Leetcode-solutions/Binary-search/RotatedBSDuplicates.java new file mode 100644 index 00000000..5d5bc9b5 --- /dev/null +++ b/Leetcode-solutions/Binary-search/RotatedBSDuplicates.java @@ -0,0 +1,44 @@ +public class RotatedBSDuplicates { + public static void main(String[] args) { + int[] nums = {4,5,6,7,0,1,2}; + int target = 0; + System.out.println(search(nums, target)); + } + + static boolean search(int[] nums, int target) { + int s = 0; + int e = nums.length-1; + + while(s <= e){ + + while(s < e && nums[s] == nums[s+1]){ + s++; + } + while (s < e && nums[e] == nums[e-1]){ + e--; + } + //after this the array will not have any duplicates + + int m = s + (e-s)/2; + + if(nums[m] == target){ + return true; + } + + if(nums[m] >= nums[s]){ + if(target < nums[m] && target >= nums[s]){ + e = m-1; + } else{ + s = m+1; + } + } else{ + if(target > nums[m] && target <= nums[e]){ + s = m+1; + } else{ + e = m-1; + } + } + } + return false; + } +} diff --git a/Leetcode-solutions/Binary-search/SearchInsertPosition.java b/Leetcode-solutions/Binary-search/SearchInsertPosition.java new file mode 100644 index 00000000..2375bff9 --- /dev/null +++ b/Leetcode-solutions/Binary-search/SearchInsertPosition.java @@ -0,0 +1,46 @@ +public class SearchInsertPosition { + public static void main(String[] args) { + int[] arr = {-9, -6, -1, 5, 11, 13, 16, 20}; + int target = 10; + System.out.println( binarySearch2(arr, target) ); + } + + static int binarySearch1(int[] arr, int target) { //or the name can be ceil the smallest number >= target (if target is present it will be the smallest num which is >= itself and if it's not present then it would be where ? the place where the smallest number after it is present this is nothing but ceiling + int s = 0; + int e = arr.length-1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(arr[m] <= target) { + s = m+1; + } else{ + e = m -1; + } + } + return s; //s will be always point to the smallest x and e will always be point to the greatest x + //for ex in this case we are finding the SMALLEST number that is >= to the target + } + + static int binarySearch2(int[] arr, int target) { + int s = 0; + int e = arr.length-1; + + while (s < e){ + int m = s + (e-s)/2; + + if( isGreaterEqual(arr[m], target) ) { + e = m; + } else{ + s = m+1; + } + } + return isGreaterEqual(arr[s], target) ? s : s + 1; //in the end s and e will point to the same value that is our answer and here the condition will break we can return s or e anything but s jada lgta kyunki s se smallest + //ye check ye h ki maanlo ek aisa num jo arr ke max se bhi bda ho jse 98 to iska ceil kya higa ya fir agr ye hota to kahan hita jb ye run hoga tb last mai s or e ek ko hi point krega or vo higa last index kyunki humne search space hi ye bnaya hua h to isliye ye return krne se pehle check ki ye bhi h ya nhi, agr h to thik nhi to s +1 hi h ans + } + + static boolean isGreaterEqual(int num, int target) { + return num >= target; + } + +} diff --git a/Leetcode-solutions/Binary-search/ShipCapacity.java b/Leetcode-solutions/Binary-search/ShipCapacity.java new file mode 100644 index 00000000..01359a67 --- /dev/null +++ b/Leetcode-solutions/Binary-search/ShipCapacity.java @@ -0,0 +1,44 @@ +public class ShipCapacity { + public static void main(String[] args) { + int[] weights = {1,2,3,4,5,6,7,8,9,10}; + System.out.println( shipWithinDays(weights, 5)); + } + + static int shipWithinDays(int[] weights, int days) { + int s = weights[0]; + int e = 0; + + for(int weight: weights){ + s = Math.max(s, weight); + e += weight; + } + + while (s < e) { + + int m = s + (e-s)/2; + + if( canShipWithMinWeight(weights, m, days) ){ + e = m; + } else{ + s = m+1; + } + } + return s; + } + + static boolean canShipWithMinWeight(int[] weights, int allowedWeight, int days) { + int daysNeeded = 1; + int sum = 0; + + for(int weight : weights){ + if(sum + weight <= allowedWeight){ + sum += weight; + } else{ + sum = weight; + daysNeeded++; + } + } + return daysNeeded <= days; + } + +} diff --git a/Leetcode-solutions/Binary-search/SingleElement.java b/Leetcode-solutions/Binary-search/SingleElement.java new file mode 100644 index 00000000..1e02b3b2 --- /dev/null +++ b/Leetcode-solutions/Binary-search/SingleElement.java @@ -0,0 +1,36 @@ +public class SingleElement { + public static void main(String[] args) { + int[] nums = {3,3,7,7,10,11,11}; + System.out.println(singleNonDuplicate(nums)); + } + + static int singleNonDuplicate(int[] nums) { + int s = 0; + int e = nums.length-1; + + while(s < e){ + int m = s + (e-s)/2; + + if( (m < e) && (nums[m] == nums[m +1]) ){ + + if( (m -s) % 2 == 0 ){ + s = m +2; + } else{ + e = m-1; + } + + } else if( (s < m) && (nums[m] == nums[m-1]) ){ + + if( (e-m) % 2 == 0 ){ + e = m-2; + } else{ + s = m+1; + } + + } else{ + return nums[m]; + } + } + return nums[s]; //or e + } +} diff --git a/Leetcode-solutions/Binary-search/SmallestLetter.java b/Leetcode-solutions/Binary-search/SmallestLetter.java new file mode 100644 index 00000000..4f5cc2a6 --- /dev/null +++ b/Leetcode-solutions/Binary-search/SmallestLetter.java @@ -0,0 +1,46 @@ +public class SmallestLetter { + public static void main(String[] args) { + char[] letters = {'c', 'f', 'j'}; + char target = 'c'; + System.out.println(nextGreatestLetter2(letters, target)); + } + + static char nextGreatestLetter(char[] letters, char target) { + int s = 0; + int e = letters.length-1; + + while(s <= e){ + int m = s + (e-s)/2; + + if(target < letters[m]){ + e = m-1; + } else { + s = m+1; + } + } + return letters[ s % letters.length ]; //or put a condition above like if target > letters[letters.length-1] then return 0 and here just return s + } + + static char nextGreatestLetter2(char[] letters, char target){ + if(target >= letters[letters.length-1]){ + return letters[0]; + } + + int s = 0; + int e = letters.length-1; + + while(s < e){ + int m = s + (e-s)/2; + + if(target < letters[m]){ + e = m-1; + } else{ + s = m+1; + } + } + return letters[s] > target ? letters[s] : letters[s+1]; + } + + + +} diff --git a/Leetcode-solutions/Binary-search/SplitArray.java b/Leetcode-solutions/Binary-search/SplitArray.java new file mode 100644 index 00000000..8e3fe742 --- /dev/null +++ b/Leetcode-solutions/Binary-search/SplitArray.java @@ -0,0 +1,43 @@ +public class SplitArray { + public static void main(String[] args) { + int[] nums = {7,2,5,10,8}; + int m = 2; + System.out.println(splitArray(nums, m)); + } + + static int splitArray(int[] nums, int m) { + int s = nums[0]; + int e = 0; + + for(int num : nums){ + s = num > s ? num : s; + e += num; + } + + while(s < e){ + int mid = s + (e-s)/2; + + if( isPotentialLargestSum(mid, nums, m) ){ + e = mid; + } else{ + s = mid + 1; + } + } + return s; //e is also ok as they both are pointing to the same element ie ans + } + + static boolean isPotentialLargestSum(int estimatedLargest, int[] nums, int piecesAsked) { + int pieces = 1; + int sum = 0; + + for(int num : nums){ + if(sum + num > estimatedLargest){ + sum = 0; + pieces++; + } + sum += num; + } + + return pieces <= piecesAsked; + } +} diff --git a/Leetcode-solutions/Binary-search/Sqrt.java b/Leetcode-solutions/Binary-search/Sqrt.java new file mode 100644 index 00000000..47f60607 --- /dev/null +++ b/Leetcode-solutions/Binary-search/Sqrt.java @@ -0,0 +1,41 @@ +public class Sqrt { + public static void main(String[] args) { + int n = 8; + System.out.println(sqrt2(n)); + } + + static int sqrt(int n){ + long s = 1; + long e = n; + + while(s <= e){ + long m = s + (e-s)/2; + + if(m * m <= n){ + s = m +1; + } else{ + e = m -1; + } + } + return (int)e; //e will always point to the greatest value satisfying the condition in this s <= e wala case doosre tarike se abhi dekhte h + } + + static int sqrt2(int n){ + long s = 1; + long e = n; + + while(s < e){ + long m = s + (e-s)/2; + + if(m * m <= n){ + s = m+1; + } else{ + e = m; + } + } + return s*s <= n ? (int)s: (int)s-1; + //idhr s-1 hoti h vo max value jo staisfy kregi condition ko lekin maano 1 ka sqrt to s or e dono hi 1 ko point krenge to is case mai loop run hi nhi hoga to kya krna h ki s-1 se pehle s ko dekhna h or agr ye satisfy krta h to yu hi bta s bda ya s-1 ? s hi na to bss use ho return nhi to simple s-1. + } + + +} diff --git a/Leetcode-solutions/Binary-search/ValidPerfectSquare.cpp b/Leetcode-solutions/Binary-search/ValidPerfectSquare.cpp new file mode 100644 index 00000000..62c45be5 --- /dev/null +++ b/Leetcode-solutions/Binary-search/ValidPerfectSquare.cpp @@ -0,0 +1,36 @@ +// Problem link : https://leetcode.com/problems/valid-perfect-square/ +// Time Complexity : O(log(n)) + +class Solution { +public: + + int findSqrt(int num) + { + int low = 1; + int high = num; + + int ans; + + while(low <= high){ + long long int mid = low + (high - low)/2; + if(mid * mid <= num){ + ans = mid; + low = mid + 1; + } + else{ // ( mid * mid ) is greater than num + high = mid - 1; + } + } + + return ans; + } + + bool isPerfectSquare(int num) { + + int sqrtN = findSqrt(num); + + if((sqrtN * sqrtN) == num) return true; + + return false; + } +}; \ No newline at end of file diff --git a/Leetcode-solutions/Binary-search/ValidPerfectSquare.java b/Leetcode-solutions/Binary-search/ValidPerfectSquare.java new file mode 100644 index 00000000..1ca765f2 --- /dev/null +++ b/Leetcode-solutions/Binary-search/ValidPerfectSquare.java @@ -0,0 +1,25 @@ +public class ValidPerfectSquare { + public static void main(String[] args) { + int num = 1; + System.out.println(isPerfectSquare(num)); + } + + static boolean isPerfectSquare(int num) { + long s = 1; + long e = (num/2) +1; + + while(s <= e){ + long m = s + (e-s)/2; + + if(m*m == num){ + return true; + } + if(m *m < num){ + s = m + 1; + } else{ + e = m-1; + } + } + return false; + } +} diff --git a/Leetcode-solutions/Binary-search/condition-2-mai-return b/Leetcode-solutions/Binary-search/condition-2-mai-return new file mode 100644 index 00000000..910b6986 --- /dev/null +++ b/Leetcode-solutions/Binary-search/condition-2-mai-return @@ -0,0 +1,125 @@ + 1. while(s < e).. (isme s=m+1 hi hoga e = m hi hoga) wale mai condition met krne ka mtlb h ki ok this can be my ans but ho skta h aage + isse bhi bde h or agr aage condition met kr gyi to obviously wo max hoga to condition met krne pr + s=m+1 ab agr tum socho ki kyu bhai m+1 kyu m kyu nhi kyunki ye ho skta hna ans, pr dekho BS mai end + mai do elements bch jate h or s hi m hota h or agr whi ans bhi hua to condition met krne pr agr humne + s = m kiya to wo usi ko assign hota rhega or it will result in infinite loop so s = m+1 krna h + + ab jb s= m+1 krre h to jb last condition jahan bhi met kri hogi vo konsa index hoga s-1 firse pdho + smjh aa jaega to isliye max humesha s-1 pr hoga + + pr ek cheez h jse maano neeche btaya hua h sqrt mai agr n 1 hua to, use pdhlena smjh aa jaega pr + bta du to return krna h is tarike se ki + + agr s satisfy krra h to s nhi to s-1 or agr s krra hoga to common sense se btao s bda ki s-1 ? + s hi na or hume krna kya h max return krna h to isliye s return krdo nhi to s-1; + + while(s < e){ + m = s + (e-s)/2; + + if( condition(m) ){ + s = m +1; + } else{ + e = m; + } + } + return condition(s) ? s : s-1; + + or min chahiye to + + while(s < e){ + m = s + (e-s)/2; + + if( condition(m) ){ + e = m; + } else{ + s = m+1; + } + } + return condition(s) ? s : s+1; + //ye cheez agge smjhayi h dursi dikkat krke or search insert position mai bhi h whan dekhlo + + + 2. while(s <= e).. (isme humesha s = m+1 or e = m-1 hi hoga) wale case mai kya hoga pehle mai kya tha + ki last mai s or e ek pr hi point krenge pr isme aisa nhi h ye apna traditional wala h isme simple poora + ka poora array traverse krenge or end mai simple hoga ki s point krega smallest pe or e krega biggest pe + kyu kyunki isme condition met krne pe max chaiye to hum kya krre h whi upr wali cheez or isme to sochne ka + kuch h nhi hume simple s = m+1 or e = m-1 krna h to end mai usme to kya hota tha do elemnt bchte the or jse + hi s or e ek pr point krte the hum break kr dete the pr isme last mai ek bchega or hum use bhi compare krenge + or fir agr whan pr met kri or hum max dhoond re h to kya krenge s = m+1 or yhi pr kya hoga ki meri baat + dhyaan se suno end mai isme ek element bchega or usko bhi compare kiya jaega abhi mai max ka bta rhi hu + agr condition met kri to kya h iska mtlb ki ye h humara ans or kya hoga ki s = m+1 ho jaega kyunki hum + or dekhne ki koshish krenge fir condition break ho jaegi kyunki s bda ho jaega e se or dhyaan se dekho + e kahan point krra h max element that is satisfying our condition or agr ye ans nhi tha to kon hoga + khud socho kya hua hoga do elemnts bche hinge pehle wala hi m bna hoga ab wo tha to humne kya kiya s=m+1 + ki dekhte h agge ho to or agr ab hum wahan h or wo nhi h to kya hoga max dhond re h or condition met + nhi kri to simple e = m-1 or is time m s or e k pr hi h ok, to ab kya hoga ki e = m-1 kyunki ye met + nhi krra last wala krra tha to jb e =m-1 hoga to wo whin pohoch jaega jo ans tha or loop bhi break ho + jaega kyunki s bda ho jaega or try to analyze e hi point krega max ko or s krega min ko isse yaad krlo + s se smallest or baaki bcha biggest to wo e hi hoga bss bss + + while(s <= e ){ + m = s + (e-s)/2; + + if( condition() ){ + s = m+1; + } else{ + e = m-1; + } + } + return e; simple! + + or min ya smallest x nikalna h is traditional method se to bss + + while(s <= e){ + m = s + (e-s)/2; + + if( condition() ){ + e = m-1; //ok this is can be our ans but we're finding smallest one or isse bhi chhote khan + peeche na or peeche kse jaenge e = m-1 + } else{ + s= m+1; + } + } + return s; simple! + + + +dekho jb aisa hna ki yhi find krna or agr ye nhi h to -1 return krna h to bss simple wala jo + h apna binary search vo hi lga do + +or achha binary search ye pta hna sorted arrays ke alava range main itna mst kaam krta h ya fir + kuch aisa hota hna ki jse ship capacity jsa question wahan bhi range nikalo or bs + +ab jo humara purana wala tarika hna wo bhi kr kisi mai lg jata h or end main kya hota h ki s point krega + smallest x pe or e humesha point krega greatest x pr + +pehle wale case main jo purana wala hi h usme koi dikkat nhi aati but second wale mai h thodi si dekhte h + vo + +dusre mai simple hota h ki in the end both s and e will point to the same element and that will be the +smallest x and the greatest x will be s-1 why beacuse when given condition met in the ques in which we're +finding max we just do s= m+1. + +dikkat aati h kyunki hum s < e tk chec krte h to jb hume max chahiye hota h to humara ans humesha +kahan hota h s-1 kyu kyunki condition met hone pr hum hi to krte h s= m+1 to to max num that is +satisfying our condition will be what s-1 but lets consider a ex if in sqrt que what we're doing +finding the max num satisfying our condition pr maano n ho 1 to s to hota hi 1 h or e bhi 1 ho +jaega to is 1 < 1 no so the loop will not run or hum s-1 kse return kr skte h fir to isliye pehle check +kro s se ki kya s satisfy krra h agr krra h to vo to bda hi h s-1 se or mujhe chahiye kya max to just +return it pr agr wo satisf nhi krra to return s-1; + +or dursi dikkat aati h jb hum min find krte h tb kya hota h ki agr satisfy krta to hum e = m krte +h nhi to s = m+1 ab isme koi dikkat wse to nhi aati pr maano jse insert position ya fir ceiling of a +number thik h to isme kya krna hota h smallest num >= target pr maano arr ka max elememt hi target se +chhota ho to? end mai s or e dono last element pr hi point krenge kyu kyunki is ques mai hum kya krre +h smallest nikal re h to condition met pr kya krte h e=m +or nhi hoti to krte h s= m+1 to bss jb koi element h hi nhi bda ya barabar target ke to sirf s = m+1 hi +hota rhega or end mai wo dono last elemnt pe aa jaenge wse to mostly ho jata h pr idhr ye bhi nhi h ans +to isliye return krne se pehle dekhlo ki ye jo s bhi h wo bhi h ki nhi agr wo nhi h to ya to +ques mai given hota h ki agr nhi h to -1 return kro, nhi to s +1 kyunki is case mai agr target max element se +bda h or ye sorted h to max kahan hoga last index pe or target usse bhi bda h to vo kahan hoga usse aage +or s se aage kya h s+1 + + + +baaki bss practice kro everything is just a pattern! \ No newline at end of file diff --git a/Leetcode-solutions/Binary-search/kthSmallestInMatrix.java b/Leetcode-solutions/Binary-search/kthSmallestInMatrix.java new file mode 100644 index 00000000..8b6e3cf2 --- /dev/null +++ b/Leetcode-solutions/Binary-search/kthSmallestInMatrix.java @@ -0,0 +1,44 @@ +public class kthSmallestInMatrix { + public static void main(String[] args) { + int[][] matrix = { + {1,5,9}, + {10,11,13}, + {12,13,15}, + }; + int k = 8; + System.out.println(kthSmallest(matrix, k)); + } + + static int kthSmallest(int[][] matrix, int k) { + int s = matrix[0][0]; + int e = matrix[ matrix.length-1 ][ matrix[0].length-1 ]; //wow + + while(s < e){ + int m = s + (e-s)/2; + + if( isPotentialK(matrix, m, k) ){ + e = m; + } else { + s = m+1; + } + } + return s; //or e as they are pointing to the same elm + } + + static boolean isPotentialK(int[][] matrix, int m, int k) { + int count = 0; + + int r = 0; + int c = matrix[0].length-1; + + while(r < matrix.length && c >= 0){ + if(matrix[r][c] <= m){ + count += c+1; + r++; + } else{ + c--; + } + } + return count >= k; + } +} diff --git a/Leetcode-solutions/Binary-search/searching_2D_matrix.cpp b/Leetcode-solutions/Binary-search/searching_2D_matrix.cpp new file mode 100644 index 00000000..564423d4 --- /dev/null +++ b/Leetcode-solutions/Binary-search/searching_2D_matrix.cpp @@ -0,0 +1,26 @@ +class Solution { + public: + bool searchMatrix(vector>& matrix, int target) { + if (matrix.empty()) + return false; + + const int m = matrix.size(); + const int n = matrix[0].size(); + int l = 0; + int r = m * n; + + while (l < r) { + const int mid = (l + r) / 2; + const int i = mid / n; + const int j = mid % n; + if (matrix[i][j] == target) + return true; + if (matrix[i][j] < target) + l = mid + 1; + else + r = mid; + } + + return false; + } +}; diff --git a/Leetcode-solutions/Symmetric_Tree/Readme.md b/Leetcode-solutions/Symmetric_Tree/Readme.md new file mode 100644 index 00000000..403bd858 --- /dev/null +++ b/Leetcode-solutions/Symmetric_Tree/Readme.md @@ -0,0 +1,3 @@ +# Leetcode question #101 + +[Click here to view the question on Leetcode.](https://leetcode.com/problems/symmetric-tree/) diff --git a/Leetcode-solutions/Symmetric_Tree/Symmetric_Tree.cpp b/Leetcode-solutions/Symmetric_Tree/Symmetric_Tree.cpp new file mode 100644 index 00000000..a5225f06 --- /dev/null +++ b/Leetcode-solutions/Symmetric_Tree/Symmetric_Tree.cpp @@ -0,0 +1,33 @@ + + + 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: + bool isSymmetric(TreeNode* root) { + + if(!root) + return true; + + return areMirror(root->left, root->right); + + } + + bool areMirror(TreeNode* t1, TreeNode* t2){ + if(!t1 || !t2) + return (t1 == t2); + + if(t1->val != t2->val) + return false; + + return ( areMirror(t1->left, t2->right) && areMirror(t1->right, t2->left) ); + + } +}; \ No newline at end of file diff --git a/Matrix/MatrixTranspose.cpp b/Matrix/MatrixTranspose.cpp new file mode 100644 index 00000000..c8953c0b --- /dev/null +++ b/Matrix/MatrixTranspose.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +int main() { + int a[10][10], transpose[10][10], row, column, i, j; + + cout << "Enter rows and columns of matrix: "; + cin >> row >> column; + + cout << "\nEnter elements of matrix: " << endl; + + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << "Enter element a" << i + 1 << j + 1 << ": "; + cin >> a[i][j]; + } + } + + cout << "\nEntered Matrix: " << endl; + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << " " << a[i][j]; + if (j == column - 1) + cout << endl << endl; + } + } + + for (int i = 0; i < row; ++i) + for (int j = 0; j < column; ++j) { + transpose[j][i] = a[i][j]; + } + + cout << "\nTranspose of Matrix: " << endl; + for (int i = 0; i < column; ++i) + for (int j = 0; j < row; ++j) { + cout << " " << transpose[i][j]; + if (j == row - 1) + cout << endl << endl; + } + + return 0; +} diff --git a/Matrix/sparseMatrix.c b/Matrix/sparseMatrix.c new file mode 100644 index 00000000..587fac70 --- /dev/null +++ b/Matrix/sparseMatrix.c @@ -0,0 +1,64 @@ +#include +#include + +int nonZero; + +void sparseMatrix(int arr[100][100],int rows,int columns){ + + int crr[rows][nonZero],p=0,q=0; + + for(int i=0;i0){ + crr[p][q]=i; + crr[p+1][q]=j; + crr[p+2][q]=arr[i][j]; + q++; + + } + } + } + + for(int f=0; f=nonZero){ + printf("\nSparse Matrix:\n"); + sparseMatrix(arr,rows,columns); + }else{ + printf("\nNot a sparse matrix"); + } + + + + + + + + return 0; +} diff --git a/Next Permutation.cpp b/Next Permutation.cpp new file mode 100644 index 00000000..a7a38af9 --- /dev/null +++ b/Next Permutation.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + void nextPermutation(vector& nums) { + next_permutation(nums.begin(),nums.end()); + } +}; diff --git a/PolynomialAddition.cpp b/PolynomialAddition.cpp new file mode 100644 index 00000000..c10bb88f --- /dev/null +++ b/PolynomialAddition.cpp @@ -0,0 +1,136 @@ +// Github username: Ansh-Kushwaha +// Aim: To store and add polynomials +// Date: 05/10/2022 + + +#include +using namespace std; + +struct term{ + int pow, coeff; + term *next; +}; + +typedef struct polynomial{ + term* addTerm(term *first, int p, int c){ //adding term to the polynomial + if(p<0){ + cout << "Undefined power" << endl; + return first; + } + if(first == NULL){ + term *tmp = new term; + tmp->pow = p; + tmp->coeff = c; + tmp->next = first; + first = tmp; + return first; + } + else{ + int pos = 1; + term *q = first; + term *nxt = NULL; + while(q->next!=NULL){ + nxt = q->next; + if(p > q->pow) + break; + else if(p < q->pow && p > nxt->pow){ + pos++; + break; + } + else{ + q = q->next; + pos++; + } + + } + if(p < q->pow && nxt == NULL){ + pos++; + } + if(pos==1){ + term* tmp = new term; + tmp->pow = p; + tmp->coeff = c; + tmp->next = q; + q = tmp; + return q; + } + else{ + term *tmp = new term; + tmp->pow = p; + tmp->coeff = c; + tmp->next = q->next; + q->next = tmp; + return first; + } + } + return first; + } + + term* add(term* one, term* two, term* res){ //combining two polynomials + while(one!=NULL && two!=NULL){ + if(one->pow == two->pow){ + res = addTerm(res, one->pow, (one->coeff+two->coeff)); + one = one->next; + two = two->next; + } + else if(one->pow < two->pow){ + res = addTerm(res, two->pow, two->coeff); + two = two->next; + } + else if(one->pow > two->pow){ + res = addTerm(res, one->pow, one->coeff); + one = one->next; + } + } + while(one!=NULL || two!=NULL){ + if(one!= NULL){ + res = addTerm(res, one->pow, one->coeff); + one = one->next; + } + if(two!= NULL){ + res = addTerm(res, two->pow, two->coeff); + two = two->next; + } + } + return res; + } + + void printPoly(term *first){ //function to print the stored polynomial + char var = 'x'; + while(first!=NULL){ + cout <coeff << var << "^" << first->pow << " "; + first = first->next; + if(!(first == NULL)) + cout << "+ "; + } + cout << endl; + } +}poly; //Data Structure (Linked List) based polynomial addition + +int main(){ + term *first1 = NULL; + poly p1; + first1 = p1.addTerm(first1, 0, 1); + first1 = p1.addTerm(first1, 5, 2); + first1 = p1.addTerm(first1, 3, 4); + first1 = p1.addTerm(first1, 4, 9); + + term *first2 = NULL; + poly p2; + first2 = p2.addTerm(first2, 0, 2); + first2 = p2.addTerm(first2, 5, 9); + first2 = p2.addTerm(first2, 3, 10); + first2 = p2.addTerm(first2, 7, 3); + + cout << "First Polynomial : " << endl; + p1.printPoly(first1); + cout << "Second Polynomial : " << endl; + p2.printPoly(first2); + cout << endl << endl; + + term *firstR = NULL; + poly result; + firstR = result.add(first1, first2, firstR); + cout << "Sum of polynomials : " << endl; + result.printPoly(firstR); +} diff --git a/Prime or not b/Prime or not new file mode 100644 index 00000000..2d1e1885 --- /dev/null +++ b/Prime or not @@ -0,0 +1,21 @@ +#include +using namespace std; +int main(){ + int num; + bool flag = 0; + cout<<"enter the number :- "; + cin>> num; + for(int i=2;i +using namespace std; +int main(){ + int i,j,a,b; + cin>>a>>b; + + for(i=a;i<=b;i++){ + for(j=2;j l[i+1] : + j = j+1 + else : + break +if j == n-1 : + print("YES") +else : + print("NO") diff --git a/Python/Dynamic_Programming/CountMinSteps.py b/Python/Dynamic_Programming/CountMinSteps.py new file mode 100644 index 00000000..3ce9404f --- /dev/null +++ b/Python/Dynamic_Programming/CountMinSteps.py @@ -0,0 +1,47 @@ +# QUESTION : Given a positive integer 'n', find and return the minimum number of steps + # that 'n' has to take to get reduced to 1. You can perform + # any one of the following 3 steps: +# 1.) Subtract 1 from it. (n = n - ­1) , +# 2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) , +# 3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ). + +from sys import stdin +from sys import maxsize as MAX_VALUE + + + +def countMinStepsToOne(n,dp) : + if n == 1: + return 0 + + if dp[n-1] == -1: + ans1 = countMinStepsToOne(n-1,dp) + dp[n-1] = ans1 + else: + ans1 = dp[n-1] + + ans2 = n-1 + + if n%2==0: + if dp[n//2] == -1: + ans2 = countMinStepsToOne(n//2,dp) + dp[n//2] = ans2 + else: + ans2 = dp[n//2] + + ans3 = n-1 + + if n%3 == 0: + if dp[n//3] == -1: + ans3 = countMinStepsToOne(n//3,dp) + dp[n//3] = ans3 + else: + ans3 = dp[n//3] + + return 1 + min(ans1,ans2,ans3) + + +#main +n = int(stdin.readline().rstrip()) +dp = [-1 for i in range(n)] +print(countMinStepsToOne(n,dp)) \ No newline at end of file diff --git a/Python/Dynamic_Programming/CountMinSteps_Iterative.py b/Python/Dynamic_Programming/CountMinSteps_Iterative.py new file mode 100644 index 00000000..30b35469 --- /dev/null +++ b/Python/Dynamic_Programming/CountMinSteps_Iterative.py @@ -0,0 +1,36 @@ +# QUESTION : Given a positive integer 'n', find and return the minimum number of steps + # that 'n' has to take to get reduced to 1. You can perform + # any one of the following 3 steps: +# 1.) Subtract 1 from it. (n = n - ­1) , +# 2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) , +# 3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ). + +# Now solve this iteratively : + +from sys import stdin +from sys import maxsize as MAX_VALUE + + + +def countMinStepsToOne(n,dp) : + dp[0] = 0 + dp[1] = 0 + i = 2 + while i<=n: + ans1 = dp[i-1] + ans2 = i-1 + if i%2 == 0: + ans2 = dp[i//2] + ans3 = i-1 + if i%3 == 0: + ans3 = dp[i//3] + ans = 1 + min(ans1,ans2,ans3) + dp[i] = ans + i += 1 + return dp[n] + + +#main +n = int(stdin.readline().rstrip()) +dp = [-1 for i in range(n+1)] +print(countMinStepsToOne(n,dp)) diff --git a/Python/Dynamic_Programming/Introduction.py b/Python/Dynamic_Programming/Introduction.py new file mode 100644 index 00000000..51735b47 --- /dev/null +++ b/Python/Dynamic_Programming/Introduction.py @@ -0,0 +1,42 @@ +# dynamic programming is like a recursion but here we will only deal with the case the + # subproblem is repeating itself. + + +# Fibonacci solution with the help of DP : + +def fibonacci(n,dp): + if n == 1 or n == 0: # base case + return n + if dp[n-1] == -1: # checking if value is not stored in the dp array + ans1 = fibonacci(n-1,dp) + dp[n-1] = ans1 # Also update the dp array after finding the value. + else: # if stored in the dp array then just use that value from there. + ans1 = dp[n-1] + if dp[n-2] == -1 : + ans2 = fibonacci(n-2,dp) + dp[n-2] = ans2 + else: + ans2 = dp[n-2] + + return ans1 + ans2 + + +# Iterative solution : + +def fibbI(n): + dp = [0 for i in range(n+1)] # creating a dp array within the function + dp[0] = 0 + dp[1] = 1 + i = 2 + while i<=n: + dp[i] = dp[i-1] + dp[i-2] # make a relation between the dp array elements by using the recursive relation. + i+=1 + return dp[n] + + +# main + +n= int(input()) +dp = [-1 for i in range(n+1)] +print(fibonacci(n,dp)) +print(fibbI(n)) diff --git a/Python/Dynamic_Programming/Longest_consecutive_subsequence.py b/Python/Dynamic_Programming/Longest_consecutive_subsequence.py new file mode 100644 index 00000000..a423a44b --- /dev/null +++ b/Python/Dynamic_Programming/Longest_consecutive_subsequence.py @@ -0,0 +1,47 @@ +# QUESTION : Given an array with N elements, you need to find the length of the + # longest subsequence in the given array such that all elements of the subsequence + # are sorted in strictly increasing order. + +from sys import stdin + +def lis(arr,i,n,dp): + if i == n: + return 0,0 + including_subsequence = 1 + + for j in range(i+1,n): + if arr[j]>arr[i]: + if dp[j] == -1: + result = lis(arr,j,n,dp) + dp[j] = result + ans = result[0] + else: + ans = dp[j][0] + + including_subsequence = max(including_subsequence,ans+1) + + if dp[i+1] == -1: + result = lis(arr,i+1,n,dp) + dp[i+1] = result + excluding_subsequence = result[1] + else: + excluding_subsequence = dp[i+1][1] + + overall_max_subsequence = max(excluding_subsequence,including_subsequence) + + return including_subsequence , overall_max_subsequence + + +def takeInput(): + #To take fast I/O + n=int(stdin.readline().strip()) + if n==0: + return list(),0 + arr=list(map(int,stdin.readline().strip().split( ))) + return arr,n + + +arr,n=takeInput() +dp = [-1 for i in range(n+1)] +ans = lis(arr,0,n,dp)[1] +print(ans) \ No newline at end of file diff --git a/Python/Dynamic_Programming/Longest_subsequence_iterative.py b/Python/Dynamic_Programming/Longest_subsequence_iterative.py new file mode 100644 index 00000000..ab1e5fee --- /dev/null +++ b/Python/Dynamic_Programming/Longest_subsequence_iterative.py @@ -0,0 +1,42 @@ +# QUESTION : Given an array with N elements, you need to find the length of the + # longest subsequence in the given array such that all elements of the subsequence + # are sorted in strictly increasing order. + + +# solve this by iterative method : + + +from sys import stdin + +def lis(arr,n): + dp = [[0 for i in range(2)] for _ in range(n+1)] + + for i in range(n-1,-1,-1): + + including_subsequence = 1 + for j in range(i+1,n): + if arr[j]>arr[i]: + ans = dp[j][0] + including_subsequence = max(including_subsequence,1+ans) + dp[i][0] = including_subsequence + excluding_max = dp[i+1][1] + overall_max = max(including_subsequence,excluding_max) + dp[i][1] = overall_max + + return dp[0][1] + + + +def takeInput(): + #To take fast I/O + n=int(stdin.readline().strip()) + if n==0: + return list(),0 + arr=list(map(int,stdin.readline().strip().split( ))) + return arr,n + + +arr,n=takeInput() + +ans = lis(arr,n) +print(ans) diff --git a/Python/Flattening of a linked list/solution.py b/Python/Flattening of a linked list/solution.py new file mode 100644 index 00000000..21bab25a --- /dev/null +++ b/Python/Flattening of a linked list/solution.py @@ -0,0 +1,124 @@ +# Python3 program for flattening a Linked List + + +class Node(): + def __init__(self, data): + self.data = data + self.right = None + self.down = None + + +class LinkedList(): + def __init__(self): + + # head of list + self.head = None + + # Utility function to insert a node at beginning of the + # linked list + def push(self, head_ref, data): + + # 1 & 2: Allocate the Node & + # Put in the data + new_node = Node(data) + + # Make next of new Node as head + new_node.down = head_ref + + # 4. Move the head to point to new Node + head_ref = new_node + + # 5. return to link it back + return head_ref + + def printList(self): + + temp = self.head + while(temp != None): + print(temp.data, end=" ") + temp = temp.down + + print() + + # An utility function to merge two sorted linked lists + def merge(self, a, b): + # if first linked list is empty then second + # is the answer + if(a == None): + return b + + # if second linked list is empty then first + # is the result + if(b == None): + return a + + # compare the data members of the two linked lists + # and put the larger one in the result + result = None + + if (a.data < b.data): + result = a + result.down = self.merge(a.down, b) + else: + result = b + result.down = self.merge(a, b.down) + + result.right = None + return result + + def flatten(self, root): + + # Base Case + if(root == None or root.right == None): + return root + # recur for list on right + + root.right = self.flatten(root.right) + + # now merge + root = self.merge(root, root.right) + + # return the root + # it will be in turn merged with its left + return root + + +# Driver's code +if __name__ == '__main__': + L = LinkedList() + + ''' + Let us create the following linked list + 5 -> 10 -> 19 -> 28 + | | | | + V V V V + 7 20 22 35 + | | | + V V V + 8 50 40 + | | + V V + 30 45 + ''' + L.head = L.push(L.head, 30) + L.head = L.push(L.head, 8) + L.head = L.push(L.head, 7) + L.head = L.push(L.head, 5) + + L.head.right = L.push(L.head.right, 20) + L.head.right = L.push(L.head.right, 10) + + L.head.right.right = L.push(L.head.right.right, 50) + L.head.right.right = L.push(L.head.right.right, 22) + L.head.right.right = L.push(L.head.right.right, 19) + + L.head.right.right.right = L.push(L.head.right.right.right, 45) + L.head.right.right.right = L.push(L.head.right.right.right, 40) + L.head.right.right.right = L.push(L.head.right.right.right, 35) + L.head.right.right.right = L.push(L.head.right.right.right, 20) + + # Function call + L.head = L.flatten(L.head) + + L.printList() + diff --git a/Python/Kruskal's_Algorithm.py b/Python/Kruskal's_Algorithm.py new file mode 100644 index 00000000..a74e868b --- /dev/null +++ b/Python/Kruskal's_Algorithm.py @@ -0,0 +1,69 @@ +# Kruskal's algorithm in Python + + +class Graph: + def __init__(self, vertices): + self.V = vertices + self.graph = [] + + def add_edge(self, u, v, w): + self.graph.append([u, v, w]) + + # Search function + + def find(self, parent, i): + if parent[i] == i: + return i + return self.find(parent, parent[i]) + + def apply_union(self, parent, rank, x, y): + xroot = self.find(parent, x) + yroot = self.find(parent, y) + if rank[xroot] < rank[yroot]: + parent[xroot] = yroot + elif rank[xroot] > rank[yroot]: + parent[yroot] = xroot + else: + parent[yroot] = xroot + rank[xroot] += 1 + + # Applying Kruskal algorithm + def kruskal_algo(self): + result = [] + i, e = 0, 0 + self.graph = sorted(self.graph, key=lambda item: item[2]) + parent = [] + rank = [] + for node in range(self.V): + parent.append(node) + rank.append(0) + while e < self.V - 1: + u, v, w = self.graph[i] + i = i + 1 + x = self.find(parent, u) + y = self.find(parent, v) + if x != y: + e = e + 1 + result.append([u, v, w]) + self.apply_union(parent, rank, x, y) + for u, v, weight in result: + print("%d - %d: %d" % (u, v, weight)) + + +g = Graph(6) +g.add_edge(0, 1, 4) +g.add_edge(0, 2, 4) +g.add_edge(1, 2, 2) +g.add_edge(1, 0, 4) +g.add_edge(2, 0, 4) +g.add_edge(2, 1, 2) +g.add_edge(2, 3, 3) +g.add_edge(2, 5, 2) +g.add_edge(2, 4, 4) +g.add_edge(3, 2, 3) +g.add_edge(3, 4, 3) +g.add_edge(4, 2, 4) +g.add_edge(4, 3, 3) +g.add_edge(5, 2, 2) +g.add_edge(5, 4, 3) +g.kruskal_algo() diff --git a/Python/Largest of the three numbers.py b/Python/Largest of the three numbers.py new file mode 100644 index 00000000..bcf44c0b --- /dev/null +++ b/Python/Largest of the three numbers.py @@ -0,0 +1,17 @@ +# Largest number from the given/entered three numbers + + +# Taking the input from the user +num1 = float(input("Enter the first number - ")) +num2 = float(input("Enter the second number - ")) +num3 = float(input("Enter the third number - ")) + +#if, elif, else blocks +if(num1 >= num2) and (num1 >= num3): + largest = num1 +elif(num2 >= num3) and (num2 >= num1): + largest = num2 +else: + largest = num3 + +print("The largest number is", largest) \ No newline at end of file diff --git a/Python/LetterCombinationsOfPhoneNumber.py b/Python/LetterCombinationsOfPhoneNumber.py new file mode 100644 index 00000000..2493fd65 --- /dev/null +++ b/Python/LetterCombinationsOfPhoneNumber.py @@ -0,0 +1,39 @@ +""" + +https://leetcode.com/problems/letter-combinations-of-a-phone-number/ +Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. + +""" +class Solution(object): + def letterCombinations(self, digits): + """ + :type digits: str + :rtype: List[str] + """ + val="" + finalset=[] + count=0 + dic={ + 2:"abc", + 3:"def", + 4:"ghi", + 5:"jkl", + 6:"mno", + 7:"pqrs", + 8:"tuv", + 9:"wxyz", + } + if len(digits)==0: + return finalset + def letter(nums,digits,count,val): + if count==len(nums): + finalset.append(val) + return + a=int(digits[0]) + p=dic[a] + for i in range(0,len(p)): + letter(nums,digits[1:],count+1,val+p[i]) + letter(digits,digits,0,val) + return finalset + + diff --git a/Python/Searching-Algorithms/Depth_first_search.py b/Python/Searching-Algorithms/Depth_first_search.py new file mode 100644 index 00000000..0e8b712d --- /dev/null +++ b/Python/Searching-Algorithms/Depth_first_search.py @@ -0,0 +1,22 @@ +# Using a Python dictionary to act as an adjacency list +graph = { + '5' : ['3','7'], + '3' : ['2', '4'], + '7' : ['8'], + '2' : [], + '4' : ['8'], + '8' : [] +} + +visited = set() # Set to keep track of visited nodes of graph. + +def dfs(visited, graph, node): #function for dfs + if node not in visited: + print (node) + visited.add(node) + for neighbour in graph[node]: + dfs(visited, graph, neighbour) + +# Driver Code +print("Following is the Depth-First Search") +dfs(visited, graph, '5') diff --git a/Python/Searching-Algorithms/Jump_search.py b/Python/Searching-Algorithms/Jump_search.py new file mode 100644 index 00000000..4e474175 --- /dev/null +++ b/Python/Searching-Algorithms/Jump_search.py @@ -0,0 +1,81 @@ +# Python3 code to implement Jump Search + +import math + + +def jumpSearch( arr , x , n ): + + + + # Finding block size to be jumped + + step = math.sqrt(n) + + + + # Finding the block where element is + + # present (if it is present) + + prev = 0 + + while arr[int(min(step, n)-1)] < x: + + prev = step + + step += math.sqrt(n) + + if prev >= n: + + return -1 + + + + # Doing a linear search for x in + + # block beginning with prev. + + while arr[int(prev)] < x: + + prev += 1 + + + + # If we reached next block or end + + # of array, element is not present. + + if prev == min(step, n): + + return -1 + + + + # If element is found + + if arr[int(prev)] == x: + + return prev + + + + return -1 + +# Driver code to test function + +arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, + + 34, 55, 89, 144, 233, 377, 610 ] + +x = 55 + +n = len(arr) + +# Find the index of 'x' using Jump Search + +index = jumpSearch(arr, x, n) + +# Print the index where 'x' is located + +print("Number" , x, "is at index" ,"%.0f"%index) + diff --git a/Python/binary_search.py b/Python/Searching-Algorithms/binary_search.py similarity index 91% rename from Python/binary_search.py rename to Python/Searching-Algorithms/binary_search.py index 960123c8..ea000683 100644 --- a/Python/binary_search.py +++ b/Python/Searching-Algorithms/binary_search.py @@ -6,7 +6,7 @@ def search(self, nums: List[int], target: int) -> int: while low <= high: - mid = (high + low) // 2 + mid = low + (high - low) // 2 # If x is greater, ignore left half if nums[mid] < target: @@ -22,4 +22,4 @@ def search(self, nums: List[int], target: int) -> int: # If we reach here, then the element was not present return -1 - \ No newline at end of file + diff --git a/Python/Searching-Algorithms/interpolation_search.py b/Python/Searching-Algorithms/interpolation_search.py new file mode 100644 index 00000000..ab5eb290 --- /dev/null +++ b/Python/Searching-Algorithms/interpolation_search.py @@ -0,0 +1,81 @@ +# Python3 program to implement +# interpolation search +# with recursion + +# If x is present in arr[0..n-1], then +# returns index of it, else returns -1. + + + +def interpolationSearch(arr, lo, hi, x): + + + # Since array is sorted, an element present + + # in array must be in range defined by corner + + if (lo <= hi and x >= arr[lo] and x <= arr[hi]): + + + # Probing the position with keeping + + # uniform distribution in mind. + + pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * + + (x - arr[lo])) + + + # Condition of target found + + if arr[pos] == x: + + return pos + + + # If x is larger, x is in right subarray + + if arr[pos] < x: + + return interpolationSearch(arr, pos + 1, + + hi, x) + + + # If x is smaller, x is in left subarray + + if arr[pos] > x: + + return interpolationSearch(arr, lo, + + pos - 1, x) + + return -1 + +# Driver code + + +# Array of items in which +# search will be conducted + +arr = [10, 12, 13, 16, 18, 19, 20, + + 21, 22, 23, 24, 33, 35, 42, 47] + +n = len(arr) + +# Element to be searched + +x = 18 + +index = interpolationSearch(arr, 0, n - 1, x) + + +if index != -1: + + print("Element found at index", index) + +else: + + print("Element not found") + diff --git a/Python/Searching-Algorithms/linear-search.py b/Python/Searching-Algorithms/linear-search.py new file mode 100644 index 00000000..dc156b57 --- /dev/null +++ b/Python/Searching-Algorithms/linear-search.py @@ -0,0 +1,16 @@ +#Linear Search Program +def linear_search(l,key): + for i in l: + if i==key: + return i + return -1 +l=[1,5,2,7,3] +k=2 +f=linear_search(l,k) +if f!=-1: + print("Key element is at %d index"%f) +else: + print("Element not found") +#if k=(any number which is not in the list) +#Output: Element not found +#Otherwise it prints "Key element is at {index of that element in list} index" diff --git a/Python/Sorting-Techniques/bucket_sort.py b/Python/Sorting-Techniques/bucket_sort.py new file mode 100644 index 00000000..589aa7fe --- /dev/null +++ b/Python/Sorting-Techniques/bucket_sort.py @@ -0,0 +1,32 @@ + +# Bucket Sort in Python + + +def bucketSort(array): + bucket = [] + + # Create empty buckets + for i in range(len(array)): + bucket.append([]) + + # Insert elements into their respective buckets + for j in array: + index_b = int(10 * j) + bucket[index_b].append(j) + + # Sort the elements of each bucket + for i in range(len(array)): + bucket[i] = sorted(bucket[i]) + + # Get the sorted elements + k = 0 + for i in range(len(array)): + for j in range(len(bucket[i])): + array[k] = bucket[i][j] + k += 1 + return array + + +array = [.42, .32, .33, .52, .37, .47, .51] +print("Sorted Array in descending order is") +print(bucketSort(array)) diff --git a/Python/Sorting-Techniques/heapSort.py b/Python/Sorting-Techniques/heapSort.py new file mode 100644 index 00000000..f934d145 --- /dev/null +++ b/Python/Sorting-Techniques/heapSort.py @@ -0,0 +1,36 @@ +def heapify(arr, N, i): + largest = i + l = 2 * i + 1 + r = 2 * i + 2 + + if l < N and arr[largest] < arr[l]: + largest = l + + if r < N and arr[largest] < arr[r]: + largest = r + + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + + heapify(arr, N, largest) + +def heapSort(arr): + N = len(arr) + + for i in range(N//2 - 1, -1, -1): + heapify(arr, N, i) + + for i in range(N-1, 0, -1): + arr[i], arr[0] = arr[0], arr[i] + heapify(arr, i, 0) + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + + heapSort(arr) + N = len(arr) + + print("Sorted array is") + for i in range(N): + print("%d" % arr[i], end=" ") + diff --git a/Python/Sorting-Techniques/selectionSort.py b/Python/Sorting-Techniques/selectionSort.py new file mode 100644 index 00000000..f5182219 --- /dev/null +++ b/Python/Sorting-Techniques/selectionSort.py @@ -0,0 +1,47 @@ + +# program for selection sort +#selections sort takes O(n^2) time complexity + + + +#program starts from here +def selectionSort( itemsList ): + n = len( itemsList ) + for i in range( n - 1 ): + minValueIndex = i + + for j in range( i + 1, n ): + if itemsList[j] < itemsList[minValueIndex] : + minValueIndex = j + + if minValueIndex != i : + temp = itemsList[i] + itemsList[i] = itemsList[minValueIndex] + itemsList[minValueIndex] = temp + + return itemsList + +# Selection sort in Python + +# time complexity O(n^2) + +#sorting by finding min_index +#CODE = +def selectionSort(array, size): + + for ind in range(size): + min_index = ind + + for j in range(ind + 1, size): + # select the minimum element in every iteration + if array[j] < array[min_index]: + min_index = j + # swapping the elements to sort the array + (array[ind], array[min_index]) = (array[min_index], array[ind]) + +arr = [-2, 45, 0, 11, -9,88,-97,-202,747] +size = len(arr) +selectionSort(arr, size) +print('The array after sorting in Ascending Order by selection sort is:') +print(arr) + diff --git a/Python/Sorting-Techniques/selection_sort.py b/Python/Sorting-Techniques/selection_sort.py new file mode 100644 index 00000000..1c7a7d61 --- /dev/null +++ b/Python/Sorting-Techniques/selection_sort.py @@ -0,0 +1,24 @@ +# Selection sort in Python + +# time complexity O(n^2) + +#sorting by finding min_index + +#CODE = +def selectionSort(array, size): + + for ind in range(size): + min_index = ind + + for j in range(ind + 1, size): + # select the minimum element in every iteration + if array[j] < array[min_index]: + min_index = j + # swapping the elements to sort the array + (array[ind], array[min_index]) = (array[min_index], array[ind]) + +arr = [-2, 45, 0, 11, -9,88,-97,-202,747] +size = len(arr) +selectionSort(arr, size) +print('The array after sorting in Ascending Order by selection sort is:') +print(arr) diff --git a/Python/all sorting methods.py b/Python/all sorting methods.py new file mode 100644 index 00000000..6a44c3d8 --- /dev/null +++ b/Python/all sorting methods.py @@ -0,0 +1,176 @@ +# BUBBLE SORT +def bubblesort(customList): + for i in range(len(customList)-1): #O(n) + for j in range(len(customList)-i-1): #O(n) + if customList[j]>customList[j+1]: #O(1) + customList[j],customList[j+1]=customList[j+1],customList[j] + print(customList) +# cList=[2,1,3,6,9,7,4,8,5] +# bubblesort(cList) + +# SELECTION SORT +def selectionSort(customList): + for i in range(len(customList)): + min_index = i + for j in range(i+1,len(customList)): + if customList[min_index] > customList[j]: + min_index = j + customList[i],customList[min_index] = customList[min_index],customList[i] + print(customList) + +# cList=[2,1,3,6,9,7,4,8,5] +# selectionSort(cList) + + + +# INSERTION SORT + +def insertionSort(customList): + for i in range(1,len(customList)): + key=customList[i] + j=i-1 + while j>=0 and key < customList[j]: + customList[j+1] = customList[j] + j -= 1 + customList[j+1] = key + return customList + +# cList=[2,1,3,6,9,7,4,8,5] +# print(insertionSort(cList)) + +# BUCKET SORT + +import math +from xmlrpc.server import MultiPathXMLRPCServer + +def bucketSort(customList): + numberofBuckets = round(math.sqrt(len(customList))) + maxValue = max(customList) + arr =[] + + for i in range(numberofBuckets): + arr.append([]) + for j in customList: + index_b = math.ceil(j*numberofBuckets/maxValue) + arr[index_b-1].append(j) + + for i in range(numberofBuckets): + arr[i] = insertionSort(arr[i]) + + k = 0 + for i in range(numberofBuckets): + for j in range(len(arr[i])): + customList[k] = arr[i][j] + k+=1 + return customList + + + +# cList=[2,1,3,6,9,7,4,8,5] +# print(bucketSort(cList)) + + +# MERGE SORT ALGORITHM + +def merge(customList, l, m, r): + n1 = m - l + 1 + n2 = r - m + + L =[0]*(n1) + R =[0]*(n2) + + for i in range(0,n1): + L[i] = customList[l+i] + + for j in range(0,n2): + R[j] = customList[m+1+j] + + i = 0 + j = 0 + k = l + while i < n1 and j int: + if n == 1: + return 1 + if n == 2: + return 2 + if n == 3: + return 6 + if n == 4: + return 7 + if n % 4 == 0: + return n+1 + if n % 4 == 1 or n % 4 == 2: + return n+2 + if n % 4 == 3: + return n-1 diff --git a/Python/findClosestNumberr.py b/Python/findClosestNumberr.py new file mode 100644 index 00000000..7e65f105 --- /dev/null +++ b/Python/findClosestNumberr.py @@ -0,0 +1,37 @@ +def get_closest(val1, val2, t): + if abs(val1 - t) <= abs(val2 - t): + return val1 + else: + return val2 + + +def find_closest(arr, n, t): + """ + Using Binary Search find the number closest + to target in the given sorted array + """ + if t <= arr[0]: + return arr[0] + elif t >= arr[n - 1]: + return arr[n - 1] + left, right = 0, n + while left < right: + mid = (left + right) // 2 + if arr[mid] == t: + return arr[mid] + elif t < arr[mid]: + if mid > 0 and arr[mid - 1] < t: + return get_closest(arr[mid - 1], arr[mid], t) + right = mid + else: + if mid < n - 1 and arr[mid + 1] > t: + return get_closest(arr[mid], arr[mid + 1], t) + left = mid + 1 + return arr[mid] + + +if __name__ == "__main__": + array = [1, 2, 4, 5, 6, 6, 8, 9] + size = len(array) + target = 7 + print(find_closest(array, size, target)) diff --git a/Python/floyd_warshal.py b/Python/floyd_warshal.py new file mode 100644 index 00000000..51c8e271 --- /dev/null +++ b/Python/floyd_warshal.py @@ -0,0 +1,37 @@ +# Floyd Warshall Algorithm in python + + +# The number of vertices +nV = 4 + +INF = 999 + + +# Algorithm implementation +def floyd_warshall(G): + distance = list(map(lambda i: list(map(lambda j: j, i)), G)) + + # Adding vertices individually + for k in range(nV): + for i in range(nV): + for j in range(nV): + distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) + print_solution(distance) + + +# Printing the solution +def print_solution(distance): + for i in range(nV): + for j in range(nV): + if(distance[i][j] == INF): + print("INF", end=" ") + else: + print(distance[i][j], end=" ") + print(" ") + + +G = [[0, 3, INF, 5], + [2, 0, INF, 4], + [INF, 1, 0, INF], + [INF, INF, 2, 0]] +floyd_warshall(G) diff --git a/Python/floyd_warshall.py b/Python/floyd_warshall.py new file mode 100644 index 00000000..68eb5cd1 --- /dev/null +++ b/Python/floyd_warshall.py @@ -0,0 +1,11 @@ +def floyd_warshall(graph): + """ + Floyd-Warshall algorithm for finding shortest paths in a graph. + """ + dist = graph + n = len(graph) + for k in range(n): + for i in range(n): + for j in range(n): + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + return dist diff --git a/Python/hashtables/firstRecurringnum.py b/Python/hashtables/firstRecurringnum.py new file mode 100644 index 00000000..9a14ef39 --- /dev/null +++ b/Python/hashtables/firstRecurringnum.py @@ -0,0 +1,23 @@ +# finding the first recurring character in a list using a hashtable +def func(mylist): + + for i in range(0, len(mylist)): + for j in range(i+1, len(mylist)): + if mylist[i] == mylist[j]: + return mylist[i] + return 0 + + +def hashtable(mylist): + mydict = {} + for i in range(0, len(mylist)): + if mylist[i] in mydict: + return mylist[i] + else: + mydict[mylist[i]] = i + return 0 + + +mylist = [2, 3, 54, 55, 2, 90, 34, 3, 54] +x = hashtable(mylist) +print(x) diff --git a/Python/ip_hostname.py b/Python/ip_hostname.py new file mode 100644 index 00000000..6e46a3df --- /dev/null +++ b/Python/ip_hostname.py @@ -0,0 +1,4 @@ +import socket + +print(socket.gethostbyname(socket.gethostname())) +print(socket.gethostname()) \ No newline at end of file diff --git a/Python/linked_list_cycle_2.py b/Python/linked_list_cycle_2.py new file mode 100644 index 00000000..776e0dd6 --- /dev/null +++ b/Python/linked_list_cycle_2.py @@ -0,0 +1,15 @@ +class Solution: + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + slow, fast = head, head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + break + else: + return None + slow = head + while slow != fast: + slow = slow.next + fast = fast.next + return diff --git a/Python/minimum_path_sum.py b/Python/minimum_path_sum.py new file mode 100644 index 00000000..5064c5d6 --- /dev/null +++ b/Python/minimum_path_sum.py @@ -0,0 +1,17 @@ +//LEETCODE- 64. Minimum Path Sum + def minPathSum(self, grid: List[List[int]]) -> int: + nR = len(grid) + nC = len(grid[0]) + adj = [(1, 0), (0, 1)] + + @cache + def dfs(r, c): + if r == nR - 1 and c == nC - 1: + return grid[r][c] + paths = [] + for a, b in adj: + r2, c2 = r + a, c + b + if 0 <= r2 < nR and 0 <= c2 < nC: + paths.append(dfs(r2, c2)) + return grid[r][c] + min(paths) + return dfs(0, 0) diff --git a/Python/passwordGenerator.py b/Python/passwordGenerator.py new file mode 100644 index 00000000..8931f5a9 --- /dev/null +++ b/Python/passwordGenerator.py @@ -0,0 +1,7 @@ +import random +import string +print("Welcome to the Password Generator!") +total = string.ascii_letters + string.digits + string.punctuation +length = int(input("How many characters would you like in your password? ")) +password = "".join(random.sample(total, length)) +print(f"Your secure password is: {password}") diff --git a/Python/plagiarism.py b/Python/plagiarism.py new file mode 100644 index 00000000..e6f47bfc --- /dev/null +++ b/Python/plagiarism.py @@ -0,0 +1,15 @@ +from difflib import SequenceMatcher + + +def findSimilarity(f1, f2): + with open(f1, errors="ignore") as file1, open(f2, errors="ignore") as file2: + f1_content = file1.read() + f2_content = file2.read() + similarity = SequenceMatcher(None, f1_content, f2_content).ratio() + print(f"The files are {similarity*100}% similar") + + +if __name__ == '__main__': + f1 = input("Enter path for first file:") + f2 = input("Enter path for second file: ") + findSimilarity(f1, f2) diff --git a/Python/queue via stack.py b/Python/queue via stack.py new file mode 100644 index 00000000..79a26116 --- /dev/null +++ b/Python/queue via stack.py @@ -0,0 +1,32 @@ +# implement a queue using two stacks + +class Stack(): + def __init__(self): + self.list=[] + + def __len__(self): + return len(self.list) + + def push(self,item): + self.list.append(item) + + def pop(self): + if len(self.list)==0: + return None + return self.list.po() + +class QueueviaStack(): + def __init__(self): + self.inStack=Stack() + self.outStack=Stack() + + def enqueue(self,item): + self.inStacl.push(item) + + def dequeue(self): + while len(self.inStack): + self.outStack.push(self.inStack.pop()) + result=self.outStack.pop() + while len(self.outStack): + self.inStack.push(self.outStack.pop()) + return result \ No newline at end of file diff --git a/Python/radix_sort.py b/Python/radix_sort.py new file mode 100644 index 00000000..3eb12539 --- /dev/null +++ b/Python/radix_sort.py @@ -0,0 +1,56 @@ +def countingSortForRadix(inputArray, placeValue): + # We can assume that the number of digits used to represent + # all numbers on the placeValue position is not grater than 10 + countArray = [0] * 10 + inputSize = len(inputArray) + + # placeElement is the value of the current place value + # of the current element, e.g. if the current element is + # 123, and the place value is 10, the placeElement is + # equal to 2 + for i in range(inputSize): + placeElement = (inputArray[i] // placeValue) % 10 + countArray[placeElement] += 1 + + for i in range(1, 10): + countArray[i] += countArray[i-1] + + # Reconstructing the output array + outputArray = [0] * inputSize + i = inputSize - 1 + while i >= 0: + currentEl = inputArray[i] + placeElement = (inputArray[i] // placeValue) % 10 + countArray[placeElement] -= 1 + newPosition = countArray[placeElement] + outputArray[newPosition] = currentEl + i -= 1 + + return outputArray + +def radixSort(inputArray): + # Step 1 -> Find the maximum element in the input array + maxEl = max(inputArray) + + # Step 2 -> Find the number of digits in the `max` element + D = 1 + while maxEl > 0: + maxEl /= 10 + D += 1 + + # Step 3 -> Initialize the place value to the least significant place + placeVal = 1 + + # Step 4 + outputArray = inputArray + while D > 0: + outputArray = countingSortForRadix(outputArray, placeVal) + placeVal *= 10 + D -= 1 + + return outputArray + +input = [2,20,61,997,1,619] +print(input) +sorted = radixSort(input) +print(sorted) diff --git a/Python/sendEmail.py b/Python/sendEmail.py new file mode 100644 index 00000000..84065a89 --- /dev/null +++ b/Python/sendEmail.py @@ -0,0 +1,30 @@ +# importing the module + +import smtplib + +sender_add = "sender123@gmail.com" +receiver_add = "reciver789@gmail.com" +password = "password" + +# creating the SMTP server object by giving SMPT server address and port number + +smtp_server = smtplib.SMTP("smtp.gmail.com", 587) +smtp_server.ehlo() # setting the ESMTP protocol + +smtp_server.starttls() # setting up to TLS connection +smtp_server.ehlo() # calling the ehlo() again as encryption happens on calling startttls() + +smtp_server.login(sender_add, password) + +msg_to_be_sent = """ +Hello, receiver! +Hope you are doing well. +Welcome to PythonGeeks! +""" + +# sending the mail by specifying the from and to address and the message + +smtp_server.sendmail(sender_add, receiver_add, msg_to_be_sent) +print("Successfully the mail is sent") # priting a message on sending the mail + +smtp_server.quit() diff --git a/Python/stack using linked list.py b/Python/stack using linked list.py new file mode 100644 index 00000000..cfdc545a --- /dev/null +++ b/Python/stack using linked list.py @@ -0,0 +1,72 @@ +class Node: + def __init__(self,value=None): + self.value = value + self.next=next + +class LinkedList: + def __init__(self): + self.head=None + + def __iter__(self): + curNode=self.head + while curNode: + yield curNode + curNode=curNode.next + +class Stack: + def __init__(self): + self.LinkedList=LinkedList() + + def __str__(self): + values=[str(x.value) for x in self.LinkedList] + return '\n'.join(values) + + def isEmpty(self): + if self.LinkedList.head == None: + return True + else: + return False + + def push(self,value): + node=Node(value) + node.next=self.LinkedList.head + self.LinkedList.head = node + + #pop + def pop(self): + if self.isEmpty(): + print("there is no element in the stack") + else: + nodeValue=self.LinkedList.head.value + self.LinkedList.head=self.LinkedList.head.next + return nodeValue + + # peek + def peek(self): + if self.isEmpty(): + print("there is no element in the stack") + else: + nodeValue=self.LinkedList.head.value + return nodeValue + + + + # delete entire stack + def delete(self): + self.list=None + + +customStack = Stack() +customStack.push(1) +customStack.push(2) +customStack.push(3) +print(customStack) + +print("\n") +customStack.pop() +print(customStack) + +print("\n") + +print(customStack.peek()) +print(customStack) \ No newline at end of file diff --git a/README.md b/README.md index ea8443ae..c21bbcd6 100644 --- a/README.md +++ b/README.md @@ -15,30 +15,2196 @@ Steps to contribute in this repository 3. Add useful code for the open-source community 4. Make pull request 5. Now, it time for review (Don't worry, our team we will review your Pull Request(PR) within 12 hours. -## Maintainers (Our Team for HacktoberFest) + +### Thanks for your contribution! +### Regards, +### Team CodeMistic +[![Linkedin](https://img.shields.io/badge/-LinkedIn-blue?style=flat-square&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/company/codemistic/)](https://www.linkedin.com/company/codemistic/) +[![Twitter](https://img.shields.io/badge/-Twitter-%231DA1F2.svg?style=flat-square&logo=twitter&logoColor=white&link=https://www.twitter.com/codemistic/)](https://www.twitter.com/codemistic/) +[![Instagram](https://img.shields.io/badge/-Instagram-red?style=flat-square&logo=Instagram&logoColor=white&link=https://www.instagram.com/codemistic.in/)](https://www.instagram.com/codemistic.in/) +[![GitHub](https://img.shields.io/badge/-Github-%23100000.svg?&style=flat-square&logo=github&logoColor=white&link=https://www.github.com/codemistic/)](https://www.github.com/codemistic/) +[![views](https://komarev.com/ghpvc/?username=codemistic&label=Profile%20views&color=0e75b6&style=flat)](https://github.com/codemistic) + +Telegram for codemistic Group + +### Maintainers + + + + + + + +
+ + Gantavya +
+ Gantavya Malviya +
+
+ +### Contributors - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -
- - Gantavya + + + Gantavya +
+ Gantavya Malviya +
+
+ + Aman5989/ +
+ Aman5989 +
+
+ + Sourav +
+ Sourav Naskar +
+
+ + adi/ +
+ adi +
+
+ + Rohit +
+ Rohit Singh +
+
+ + divyaa1511/ +
+ divyaa1511 +
+
+ + Aishal +
+ Aishal Gupta +
+
+ + Adarsh +
+ Adarsh jaiswal +
+
+ + Pratyaksha +
+ Pratyaksha Newalkar +
+
+ + Gaurish +
+ Gaurish Ojha +
+
+ + naman +
+ naman jain +
+
+ + Yash +
+ Yash Suthar +
+
+ + Parth +
+ Parth Saini +
+
+ + Gaurisha +
+ Gaurisha R Srivastava +
+
+ + Vishwajeet +
+ Vishwajeet Shivaji Hogale +
+
+ + varun +
+ varun jain +
+
+ + rohansrivastava5491/ +
+ rohansrivastava5491 +
+
+ + RYANRANAUT/ +
+ RYANRANAUT +
+
+ + Mercapto/ +
+ Mercapto +
+
+ + Dhruv +
+ Dhruv Solanki +
+
+ + Rakesh +
+ Rakesh Sabale +
+
+ + pranava7/ +
+ pranava7 +
+
+ + Shiva +
+ Shiva Abhishek +
+
+ + Ankita +
+ Ankita Patil +
+
+ + Ebenezer +
+ Ebenezer R. +
+
+ + Rohit +
+ Rohit Yadav +
+
+ + Shubham +
+ Shubham Kumar +
+
+ + Shashank +
+ Shashank Singh +
+
+ + Github_User/ +
+ Github_User +
+
+ + Kanishka +
+ Kanishka Gour +
+
+ + Kalyan/ +
+ Kalyan +
+
+ + Himanshu +
+ Himanshu Kumar Sharma +
+
+ + CHALLANIKITHA/ +
+ CHALLANIKITHA +
+
+ + Baibhav/ +
+ Baibhav +
+
+ + Adarsh +
+ Adarsh Soni +
+
+ + Akshat +
+ Akshat Jain +
+
+ + Saksham +
+ Saksham Sharma +
+
+ + Sanskar +
+ Sanskar Goyal +
+
+ + Sarthak +
+ Sarthak Verma +
+
+ + Shubh +
+ Shubh Rastogi +
+
+ + Siddhant +
+ Siddhant Singh +
+
+ + Sujit +
+ Sujit Jaunjal +
+
+ + SwagsShivamOp/ +
+ SwagsShivamOp +
+
+ + Vkwinner/ +
+ Vkwinner +
+
+ + Yash +
+ Yash Gautam +
+
+ + alex-2003-47/ +
+ alex-2003-47 +
+
+ + gantavya123/ +
+ gantavya123 +
+
+ + gantavya1234/ +
+ gantavya1234 +
+
+ + lnctcoders/ +
+ lnctcoders +
+
+ + rishi +
+ rishi chaitanya Tiwari +
+
+ + shivamsingh67/ +
+ shivamsingh67 +
+
+ + Aakash +
+ Aakash Singh +
+
+ + Aakriti +
+ Aakriti Awasthi +
+
+ + Abhijeet +
+ Abhijeet Tiwari +
+
+ + Anish +
+ Anish Agarwal +
+
+ + Arpita +
+ Arpita Das +
+
+ + Ayush +
+ Ayush Agrawal +
+
+ + Ayush +
+ Ayush Kumar Shukla +
+
+ + BhaswatiR/ +
+ BhaswatiR +
+
+ + Saar +
+ Saar Agrawal +
+
+ + Dhiraj +
+ Dhiraj Jadhav +
+
+ + Dhruv +
+ Dhruv Verma +
+
+ + John +
+ John Abraham +
+
+ + Kalyan +
+ Kalyan Mishra +
+
+ + Kushagra +
+ Kushagra Rawat +
+
+ + Naman +
+ Naman Paliwal +
+
+ + Narpat +
+ Narpat Aanjana +
+
+ + Nikhil +
+ Nikhil Dhariwal +
+
+ + Rohit +
+ Rohit Kumar +
+
+ + Om +
+ Om Prakash +
+
+ + Rahul +
+ Rahul Kumar +
+
+ + Navdhare +
+ Navdhare Saurav Rajendra +
+
+ + Soham +
+ Soham Datta +
+
+ + Sparsh +
+ Sparsh kishore kumar +
+
+ + Yash +
+ Yash Bansal +
+
+ + aayush920/ +
+ aayush920 +
+
+ + Pratik +
+ Pratik Joshi +
+
+ + gantavya12/ +
+ gantavya12 +
+
+ + Adarsh/ +
+ Adarsh +
+
+ + Anish +
+ Anish Tiwari +
+
+ + Joseph2001-braganza/ +
+ Joseph2001-braganza +
+
+ + Pritom +
+ Pritom Karmokar +
+
+ + Sanjay +
+ Sanjay Sathyanarayanan +
+
+ + Paras +
+ Paras Sharma +
+
+ + Nishitbariya/ +
+ Nishitbariya +
+
+ + Harsh +
+ Harsh Bhatt +
+
+ + Shaury +
+ Shaury R Srivastava +
+
+ + Asha/ +
+ Asha +
+
+ + Arun +
+ Arun Singh Kushwaha +
+
+ + Abhishek +
+ Abhishek Mallick +
+
+ + Aayush +
+ Aayush Patel +
+
+ + Abhishek +
+ Abhishek Bhattacharjee +
+
+ + Aarush +
+ Aarush Kansal +
+
+ + Amit +
+ Amit Das +
+
+ + avishagoyal08/ +
+ avishagoyal08 +
+
+ + Vaibhav +
+ Vaibhav Varshney +
+
+ + Umang +
+ Umang Devanshu +
+
+ + Sugash +
+ Sugash Srimari R +
+
+ + Sudhir8787/ +
+ Sudhir8787 +
+
+ + Solaris/ +
+ Solaris +
+
+ + Siddharth +
+ Siddharth Reddy Anthireddy +
+
+ + Shubham +
+ Shubham S Jagtap +
+
+ + ShreyasiDebnath/ +
+ ShreyasiDebnath +
+
+ + Abhimanyu +
+ Abhimanyu Chauhan +
+
+ + lifeashaze/ +
+ lifeashaze +
+
+ + namita27/ +
+ namita27 +
+
+ + PAKHI +
+ PAKHI VASHISHTH +
+
+ + priyayadav19054/ +
+ priyayadav19054 +
+
+ + sameer-19/ +
+ sameer-19 +
+
+ + siddharth +
+ siddharth jain +
+
+ + Shreyas +
+ Shreyas Kamath +
+
+ + Md +
+ Md Shafaullah +
+
+ + Namrata/ +
+ Namrata +
+
+ + PRABHAT +
+ PRABHAT KUMAR MISHRA +
+
+ + Rai_M/ +
+ Rai_M +
+
+ + ADITYA +
+ ADITYA SAI +
+
+ + Alok +
+ Alok Khansali +
+
+ + ABHISHEK +
+ ABHISHEK KUMAR DEY +
+
+ + Anshu +
+ Anshu Pandey +
+
+ + Arya +
+ Arya Singh +
+
+ + Aswin +
+ Aswin Dev S P +
+
+ + Bhaswati +
+ Bhaswati Roy +
+
+ + Dipendra +
+ Dipendra Raghav +
+
+ + Jheyanth +
+ Jheyanth CS +
+
+ + Juhii16/ +
+ Juhii16 +
+
+ + Bhushan +
+ Bhushan K +
+
+ + Lokesh +
+ Lokesh Medharimetla +
+
+ + Manas +
+ Manas Rai +
+
+ + Md +
+ Md Tausif Siddiqui +
+
+ + Niladri +
+ Niladri Das +
+
+ + RASHIKA +
+ RASHIKA RAWAT +
+
+ + Ronica +
+ Ronica Singh +
+
+ + Samrat +
+ Samrat Dawn +
+
+ + SavvyShivam/ +
+ SavvyShivam +
+
+ + Shreyan +
+ Shreyan Haldankar +
+
+ + Shakti +
+ Shakti Maddheshiya +
+
+ + Taneesha +
+ Taneesha Suwandarachchi +
+
+ + Tandrima +
+ Tandrima Singha +
+
+ + Tamanna +
+ Tamanna Sharma +
+
+ + SwetaDas16/ +
+ SwetaDas16 +
+
+ + Sumit +
+ Sumit Kumar Rai +
+
+ + Sudhanshu +
+ Sudhanshu Purohit +
+
+ + Storm_Chaser/ +
+ Storm_Chaser +
+
+ + Soyeb +
+ Soyeb Sarkar +
+
+ + Rituraj +
+ Rituraj Dey +
+
+ + Tanmoy +
+ Tanmoy Sengupta +
+
+ + Tanuj +
+ Tanuj Sharma +
+
+ + Timi/ +
+ Timi +
+
+ + Tunwase +
+ Tunwase Ayobami +
+
+ + Utkarsh +
+ Utkarsh Rai +
+
+ + Vaibhav/ +
+ Vaibhav +
+
+ + Vandana +
+ Vandana Singh +
+
+ + Vardaan +
+ Vardaan Raj Singh +
+
+ + Vinamra/ +
+ Vinamra +
+
+ + Nishant/ +
+ Nishant +
+
+ + Rusheel +
+ Rusheel Dalal +
+
+ + Susajjit +
+ Susajjit kumar Singh +
+
+ + Sachin +
+ Sachin Kamath +
+
+ + Sachin +
+ Sachin Kant +
+
+ + Sam/ +
+ Sam +
+
+ + Sandeep +
+ Sandeep V +
+
+ + Sanjanabharadwaj25/ +
+ Sanjanabharadwaj25 +
+
+ + Sarthak +
+ Sarthak Rajput +
+
+ + Sarthak +
+ Sarthak Kurothe +
+
+ + Shalin +
+ Shalin Bhavsar +
+
+ + Shitij +
+ Shitij Agrawal +
+
+ + Shreya +
+ Shreya Gupta +
+
+ + Shubham +
+ Shubham Kashyap +
+
+ + Shubham +
+ Shubham Rajendra Burad +
+
+ + sid/ +
+ sid +
+
+ + Sinu +
+ Sinu Xavier +
+
+ + sohandiginnk/ +
+ sohandiginnk +
+
+ + Sohan +
+ Sohan Agashimani +
+
+ + Soumili +
+ Soumili Chakraborty +
+
+ + priyanshu +
+ priyanshu mundra +
+
+ + Rahul/ +
+ Rahul +
+
+ + raju121097/ +
+ raju121097 +
+
+ + rohinipatil89/ +
+ rohinipatil89 +
+
+ + RUDRANEEL +
+ RUDRANEEL DUTTA +
+
+ + Rupesh +
+ Rupesh Piwal +
+
+ + Sahan +
+ Sahan Mondal +
+
+ + sajjad +
+ sajjad rahman +
+
+ + sanu-020/ +
+ sanu-020 +
+
+ + shrutij1247/ +
+ shrutij1247 +
+
+ + snatchysquid/ +
+ snatchysquid +
+
+ + MD +
+ MD SOHAIL ANSARI +
+
+ + Sourav +
+ Sourav khan +
+
+ + swarup-0508/ +
+ swarup-0508 +
+
+ + Kirtan +
+ Kirtan Kushwah +
+
+ + Vansh +
+ Vansh Chopra +
+
+ + ridhi16/ +
+ ridhi16 +
+
+ + Daniel +
+ Daniel Deychev +
+
+ + Yusman/ +
+ Yusman +
+
+ + zebi29/ +
+ zebi29 +
+
+ + Vishal/ +
+ Vishal +
+
+ + Vishal +
+ Vishal Sharma +
+
+ + Vishesh +
+ Vishesh Gupta +
+
+ + Yasir +
+ Yasir Jafri +
+
+ + Aman +
+ Aman Ali +
+
+ + adityasingh0149/ +
+ adityasingh0149 +
+
+ + Aman +
+ Aman Yadav +
+
+ + ankit20214/ +
+ ankit20214 +
+
+ + Arhum +
+ Arhum Khan +
+
+ + Arpit +
+ Arpit Ghura +
+
+ + Ashutosh +
+ Ashutosh Saxena +
+
+ + Bhavy +
+ Bhavy Khatter +
+
+ + Harsh +
+ Harsh Bhikadiya +
+
+ + hruday007/ +
+ hruday007 +
+
+ + jenna/ +
+ jenna +
+
+ + @devkshitij7/ +
+ @devkshitij7 +
+
+ + Masoom +
+ Masoom Mishra +
+
+ + Sudhakar +
+ Sudhakar Singh +
+
+ + Nihar +
+ Nihar Bansal +
+
+ + Nikita +
+ Nikita Singh +
+
+ + Nilesh +
+ Nilesh Das +
+
+ + Aniruddho +
+ Aniruddho Mitra +
+
+ + Anisha +
+ Anisha Shende +
+
+ + Ansh +
+ Ansh Kushwaha +
+
+ + Anshsahu0802/ +
+ Anshsahu0802 +
+
+ + Anshul +
+ Anshul Nigam +
+
+ + Anshuman +
+ Anshuman Shukla +
+
+ + Apoorv +
+ Apoorv Chandrakar +
+
+ + Aratrik +
+ Aratrik Basak +
+
+ + Armaan +
+ Armaan Khan +
+
+ + Arnav +
+ Arnav Agarwal +
+
+ + Arpit +
+ Arpit Rath +
+
+ + Arya +
+ Arya Gupta +
+
+ + Auro +
+ Auro Saswat Raj +
+
+ + Av-nish/ +
+ Av-nish +
+
+ + Ayush +
+ Ayush Kedia +
+
+ + Ayush +
+ Ayush Rawat +
+
+ + Bhavna +
+ Bhavna Panjwani +
+
+ + Rik +
+ Rik Chatterjee +
+
+ + ANURAG +
+ ANURAG TIWARI +
+
+ + Paolo +
+ Paolo Cretaro +
+
+ + ADITYA +
+ ADITYA PATHAK +
+
+ + AMAN +
+ AMAN SHRIVASTAVA +
+
+ + ARYAN +
+ ARYAN GULATI +
+
+ + Aayush +
+ Aayush Girdhar +
+
+ + Abhiram +
+ Abhiram J +
+
+ + Abhiroop
- Gantavya Malviya + Abhiroop Singh
- - Adarsh + + Abhishek
- Adarsh jaiswal + Abhishek Kumar +
+
+ + Abhishek +
+ Abhishek Srivastava +
+
+ + Achintya +
+ Achintya Saxena +
+
+ + Adithyan +
+ Adithyan Madhu +
+
+ + Aditya +
+ Aditya Mandage +
+
+ + Aditya +
+ Aditya Raj +
+
+ + Agrim +
+ Agrim Jain +
+
+ + Aiyan +
+ Aiyan Faras +
+
+ + akshay-gidwani-psl/ +
+ akshay-gidwani-psl +
+
+ + Akshay +
+ Akshay Khatter +
+
+ + AmanDekate1/ +
+ AmanDekate1 +
+
+ + Amelia +
+ Amelia Dutta +
+
+ + Aneesh +
+ Aneesh Gupta +
+
+ + Aniket +
+ Aniket Bindhani +
+
+ + Shrey +
+ Shrey Midha +
+
+ + Mohammad +
+ Mohammad Palla +
+
+ + Mohammed +
+ Mohammed Imtiyaz +
+
+ + Mohit +
+ Mohit Gaur +
+
+ + Mohit +
+ Mohit Patni +
+
+ + Muhammad +
+ Muhammad Noorani +
+
+ + Muhammad +
+ Muhammad Sameer Farooq +
+
+ + Nakul +
+ Nakul Bhangale +
+
+ + Nayan +
+ Nayan Koshta +
+
+ + Nitya +
+ Nitya Anuga +
+
+ + Pavan/ +
+ Pavan +
+
+ + Prajwal/ +
+ Prajwal +
+
+ + PranathiJyothi/ +
+ PranathiJyothi +
+
+ + Prashantsetia/ +
+ Prashantsetia +
+
+ + Pratik +
+ Pratik Agrawal +
+
+ + Raghav +
+ Raghav Babbar +
+
+ + Rahmat +
+ Rahmat Sulistio +
+
+ + Rahul +
+ Rahul Singh Gurjar +
+
+ + Raj +
+ Raj +
+
+ + Dibendu +
+ Dibendu G. +
+
+ + Divyansh +
+ Divyansh Pratap Singh +
+
+ + Durgesh +
+ Durgesh Sahu +
+
+ + firejoust/ +
+ firejoust +
+
+ + Harshit +
+ Harshit kumar +
+
+ + Bhupesh +
+ Bhupesh Jain +
+
+ + Hiya +
+ Hiya Shivnani +
+
+ + Jashan +
+ Jashan Warraich +
+
+ + Jayesh +
+ Jayesh Kumavat +
+
+ + Jeetu +
+ Jeetu Gupta +
+
+ + Zayd/ +
+ Zayd +
+
+ + Kapadiatathya/ +
+ Kapadiatathya +
+
+ + Aditya +
+ Aditya Shukla +
+
+ + Kartikey +
+ Kartikey Tandon +
+
+ + Kashish +
+ Kashish Ahuja +
+
+ + Kashish +
+ Kashish Lakhara +
+
+ + Kasun +
+ Kasun Hewagama +
+
+ + Lisha +
+ Lisha Kothari +
+
+ + Dhruv +
+ Dhruv Gupta +
+
+ + ManikSingh29/ +
+ ManikSingh29
- -## Top Contributors -Update in progress.... + + -### Thanks for visiting! -### Regards, -### Team CodeMistic -[![Linkedin](https://img.shields.io/badge/-LinkedIn-blue?style=flat-square&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/company/codemistic/)](https://www.linkedin.com/company/codemistic/) -[![Twitter](https://img.shields.io/badge/-Twitter-%231DA1F2.svg?style=flat-square&logo=twitter&logoColor=white&link=https://www.twitter.com/codemistic/)](https://www.twitter.com/codemistic/) -[![Instagram](https://img.shields.io/badge/-Instagram-red?style=flat-square&logo=Instagram&logoColor=white&link=https://www.instagram.com/codemistic.in/)](https://www.instagram.com/codemistic.in/) -[![GitHub](https://img.shields.io/badge/-Github-%23100000.svg?&style=flat-square&logo=github&logoColor=white&link=https://www.github.com/codemistic/)](https://www.github.com/codemistic/) -[![views](https://komarev.com/ghpvc/?username=codemistic&label=Profile%20views&color=0e75b6&style=flat)](https://github.com/codemistic) - -Telegram for codemistic Group diff --git a/Soduko-solver.java b/Soduko-solver.java deleted file mode 100644 index c67a88c5..00000000 --- a/Soduko-solver.java +++ /dev/null @@ -1,55 +0,0 @@ -class Solution { -public void solveSudoku(char[][] board) -{ -solvsss(board); -} -public boolean solvsss(char[][] board) -{ -for(int i=0;i +using namespace std; + +/*class Stack{ + private: + char *arr; + int size; + int top=-1; + public: + + Stack(int n){ + size=n; + arr=new char[size]; + } + + void push(string t){ + + if(top==size-1){ + cout<<"stack overflow"<=0;i--){ + cout< s; + + string n =" Saar"; + + for(int i=0;i +using namespace std; + +class Node{ + public: + int data; + Node *next; +}; + +class Stack{ + private: + Node *top; + public: + Stack(){top=NULL;} + + void push(int x); + int pop(); + void display(); +}; + +void Stack::push(int x){ + Node *t=new Node; + if(t==NULL) + cout<<"Stack is Flow"<data=x; + t->next=top; + top=t; + } +} + +int Stack::pop(){ + int x=-1; + if(top==NULL){ + cout<<"Stack is Emplty"<data; + Node *t=top; + top=top->next; + delete t; + + } + return x; +} + +void Stack::display(){ + Node *p=top; + while(p!=NULL){ + cout<data<<" "; + p=p->next; + } + cout< +#include +struct Stack +{ + int size; + int top; + int *S; +}; +void create(struct Stack *st) +{ + printf("Enter Size"); + scanf("%d", &st->size); + st->top = -1; + st->S = (int *)malloc(st->size * sizeof(int)); +} +void Display(struct Stack st) +{ + int i; + for (i = st.top; i >= 0; i--) + printf("%d ", st.S[i]); + printf("\n"); +} +void push(struct Stack *st, int x) +{ + if (st->top == st->size - 1) + printf("Stack overflow\n"); + else + { + st->top++; + st->S[st->top] = x; + } +} +int pop(struct Stack *st) +{ + int x = -1; + if (st->top == -1) + printf("Stack Underflow\n"); + else + { + x = st->S[st->top--]; + } + return x; +} +int peek(struct Stack st, int index) +{ + int x = -1; + if (st.top - index + 1 < 0) + printf("Invalid Index \n"); + x = st.S[st.top - index + 1]; + return x; +} +int isEmpty(struct Stack st) +{ + if (st.top == -1) + return 1; + return 0; +} +int isFull(struct Stack st) +{ + return st.top == st.size - 1; +} +int stackTop(struct Stack st) +{ + if (!isEmpty(st)) + return st.S[st.top]; + return -1; +} +int main() +{ + struct Stack st; + create(&st); + push(&st, 10); + push(&st, 20); + push(&st, 30); + push(&st, 40); + printf("%d \n", peek(st, 2)); + Display(st); + return 0; +} \ No newline at end of file diff --git a/Stack/stack_implementation_using_array.cpp b/Stack/stack_implementation_using_array.cpp new file mode 100644 index 00000000..0fdf5f1b --- /dev/null +++ b/Stack/stack_implementation_using_array.cpp @@ -0,0 +1,69 @@ +#include +using namespace std; + +class stack1 +{ +private: + int size; + int top; + vector s; + +public: + stack1(int n){ + size=n; + s.resize(n); + top=-1; + } + + void display() + { + int i; + for (i = top; i >= 0; i--) + { + cout< &chars) + { + + char temp = chars[0]; + int cnt = 0, n = chars.size(); + for (int i = 0; i < n; i++) + { + if (chars[i] == temp) + cnt++; + else + { + chars.erase(chars.begin(), chars.begin() + i); + i = 0; + n -= cnt; + chars.push_back(temp); + if (cnt != 1) + { + string k = to_string(cnt); + for (auto x : k) + chars.push_back(x); + } + temp = chars[i]; + cnt = 1; + continue; + } + } + chars.erase(chars.begin(), chars.begin() + cnt); + chars.push_back(temp); + if (cnt != 1) + { + string k = to_string(cnt); + for (auto x : k) + chars.push_back(x); + } + return chars.size(); + } +}; \ No newline at end of file diff --git a/String/extract_words_string.exe b/String/extract_words_string.exe new file mode 100644 index 00000000..66b0cbf1 Binary files /dev/null and b/String/extract_words_string.exe differ diff --git a/String/police.cpp b/String/police.cpp new file mode 100644 index 00000000..72e9e138 --- /dev/null +++ b/String/police.cpp @@ -0,0 +1,30 @@ +#include +#include +using namespace std; +int main(){ + long long a[100000]; + long long n; + long long c=0,p=0,sum=0; + cin>>n; + for(int i=0;i>a[i]; + for(int i=0;i +using namespace std; + +void reverse(string &s, int start, int end){ + if(start>=end) return ; + swap(s[start],s[end]); + reverse(s,start+1,end-1); + } + +string reverseWords(string s) { + int start = 0; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#define ll long long +#define dd double +using namespace std; +int main() { + ios::sync_with_stdio(false); + ll n, m, k; cin >> n >> m >> k; + ll sum = 0; + for (ll i = 1; i <= k; i++) { + sum += n * i; + } + sum -= m; + if (sum <= 0) { + cout << "0" << endl; + } + else { + cout << sum << endl; + } +} diff --git a/String/translation.cpp b/String/translation.cpp new file mode 100644 index 00000000..1a68d067 --- /dev/null +++ b/String/translation.cpp @@ -0,0 +1,13 @@ +#include +#include +int main(){ + char str1[105],str2[105],count=0; + scanf("%s%s",str1,str2); + int length=strlen(str1); + for(int i=0;i>& board) { + solve(board); + } + + bool solve(vector>& board){ + for(int i=0; i>& board, int row, int col){ + for(int i=0; i<9; i++){ + if(board[i][col] == c) return false; + if(board[row][i] == c) return false; + if(board[3*(row/3)+(i/3)][3*(col/3)+(i%3)] == c) return false; + } + return true; + } +}; diff --git a/Towerofhanoi.java b/Towerofhanoi.java new file mode 100644 index 00000000..fc658413 --- /dev/null +++ b/Towerofhanoi.java @@ -0,0 +1,21 @@ +package com.JournalDev; +public class Main { + static void towerOfHanoi(int n, char from_rod, char to_rod, char helper_rod) + { + if (n == 1) + { + System.out.println("Take disk 1 from rod " + from_rod + " to rod " + to_rod); + return; + } + towerOfHanoi(n-1, from_rod, helper_rod, to_rod); + System.out.println("Take disk " + n + " from rod " + from_rod + " to rod " + to_rod); + towerOfHanoi(n-1, helper_rod, to_rod, from_rod); + } + + public static void main(String args[]) + { + int n = 5; + towerOfHanoi(n,'A','C', 'B'); + } + +} diff --git a/Trees/BST.C b/Trees/BST.C new file mode 100644 index 00000000..4a590a85 --- /dev/null +++ b/Trees/BST.C @@ -0,0 +1,173 @@ +#include +#include + +struct Node +{ + struct Node *lchild; + int data; + struct Node *rchild; +} *root = NULL; + +void Insert(int key) +{ + struct Node *t = root; + struct Node *r, *p; + + if (root == NULL) + { + p = (struct Node *)malloc(sizeof(struct Node)); + p->data = key; + p->lchild = p->rchild = NULL; + root = p; + return; + } + while (t != NULL) + { + r = t; + if (key < t->data) + t = t->lchild; + else if (key > t->data) + t = t->rchild; + else + return; + } + p = (struct Node *)malloc(sizeof(struct Node)); + p->data = key; + p->lchild = p->rchild = NULL; + + if (key < r->data) + r->lchild = p; + else + r->rchild = p; +} + +void Inorder(struct Node *p) +{ + if (p) + { + Inorder(p->lchild); + printf("%d ", p->data); + Inorder(p->rchild); + } +} + +struct Node *Search(int key) +{ + struct Node *t = root; + + while (t != NULL) + { + if (key == t->data) + return t; + else if (key < t->data) + t = t->lchild; + else + t = t->rchild; + } + return NULL; +} + +struct Node *RInsert(struct Node *p, int key) +{ + struct Node *t = NULL; + if (p == NULL) + { + t = (struct Node *)malloc(sizeof(struct Node)); + t->data = key; + t->lchild = t->rchild = NULL; + return t; + } + if (key < p->data) + p->lchild = RInsert(p->lchild, key); + else if (key > p->data) + p->rchild = RInsert(p->rchild, key); + return p; +} + +int Height(struct Node *p) +{ + int x, y; + if (p == NULL) + return 0; + x = Height(p->lchild); + y = Height(p->rchild); + return x > y ? x + 1 : y + 1; +} + +struct Node *InPre(struct Node *p) +{ + while (p && p->rchild != NULL) + p = p->rchild; + return p; +} + +struct Node *InSucc(struct Node *p) +{ + while (p && p->lchild != NULL) + p = p->lchild; + return p; +} + +struct Node *Delete(struct Node *p, int key) +{ + struct Node *q = NULL; + if (p == NULL) + return NULL; + if (p->lchild == NULL && p->rchild == NULL) + { + if (p == root) + root = NULL; + free(p); + return NULL; + } + + if (key < p->data) + p->lchild = Delete(p->lchild, key); + else if (key > p->data) + p->rchild = Delete(p->rchild, key); + else + { + if (Height(p->lchild) > Height(p->rchild)) + { + q = InPre(p->lchild); + p->data = q->data; + p->lchild = Delete(p->lchild, q->data); + } + else + { + q = InSucc(p->rchild); + p->data = q->data; + p->rchild = Delete(p->rchild, q->data); + } + } + return p; +} + +int main() +{ + struct Node *temp; + + root = RInsert(root, 10); + RInsert(root, 10); + RInsert(root, 40); + RInsert(root, 20); + RInsert(root, 30); + RInsert(root, 25); + RInsert(root, 35); + RInsert(root, 55); + + Delete(root, 30); + + Inorder(root); + printf("\n"); + + temp = Search(20); + if (temp != NULL) + printf("Element %d is found\n", temp->data); + else + { + printf("Element is not found\n"); + } + + return 0; +} \ No newline at end of file diff --git a/Trees/Binary_tree_Array.c b/Trees/Binary_tree_Array.c new file mode 100644 index 00000000..f7573320 --- /dev/null +++ b/Trees/Binary_tree_Array.c @@ -0,0 +1,93 @@ +#include + + +int complete_node = 15; + +char tree[] = {'\0', 'D', 'A', 'F', 'E', 'B', 'R', 'T', 'G', 'Q', '\0', '\0', 'V', '\0', 'J', 'L'}; + +// funtion to get parent +int get_parent(int index) +{ + if(tree[index]!='\0' && index>1 && index<=complete_node) //root has no parent + return index/2; + return -1; +} + +int get_right_child(int index) +{ + // node is not null + // and the result must lie within the number of nodes for a complete binary tree + if(tree[index]!='\0' && ((2*index)+1)<=complete_node) + return (2*index)+1; + // right child doesn't exist + return -1; +} + +int get_left_child(int index) +{ + // node is not null + // and the result must lie within the number of nodes for a complete binary tree + if(tree[index]!='\0' && (2*index)<=complete_node) + return 2*index; + // left child doesn't exist + return -1; +} + +void preorder(int index) +{ + // checking for valid index and null node + if(index>0 && tree[index]!='\0') + { + printf(" %c ",tree[index]); // visiting root + preorder(get_left_child(index)); //visiting left subtree + preorder(get_right_child(index)); //visiting right subtree + } +} + +void postorder(int index) +{ + // checking for valid index and null node + if(index>0 && tree[index]!='\0') + { + postorder(get_left_child(index)); //visiting left subtree + postorder(get_right_child(index)); //visiting right subtree + printf(" %c ",tree[index]); //visiting root + } +} + +void inorder(int index) +{ + // checking for valid index and null node + if(index>0 && tree[index]!='\0') + { + inorder(get_left_child(index)); //visiting left subtree + printf(" %c ",tree[index]); //visiting root + inorder(get_right_child(index)); // visiting right subtree + } +} + +int is_leaf(int index) +{ + // to check of the indices of the left and right children are valid or not + if(!get_left_child(index) && !get_right_child(index)) + return 1; + // to check if both the children of the node are null or not + if(tree[get_left_child(index)]=='\0' && tree[get_right_child(index)]=='\0') + return 1; + return 0; // node is not a leaf +} + +int get_max(int a, int b) +{ + return (a>b) ? a : b; +} + +int get_height(int index) +{ + // if the node is a leaf the the height will be 0 + // the height will be 0 also for the invalid cases + if(tree[index]=='\0' || index<=0 || is_leaf(index)) + return 0; + // height of node i is 1+ maximum among the height of left subtree and the height of right subtree + return(get_max(get_height(get_left_child(index)), get_height(get_right_child(index)))+1); +} diff --git a/Trees/BottomView.cpp b/Trees/BottomView.cpp new file mode 100644 index 00000000..f9092e93 --- /dev/null +++ b/Trees/BottomView.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +class Tree { + public: + int data; + int hd; + Tree *left; + Tree *right; + +}; + +Tree* newNode(int data){ + Tree *new_node = new Tree(); + new_node->data = data; + new_node->hd = 0; + new_node->left = NULL; + new_node->right = NULL; + return new_node; + +} + +void setHorizontalDistance(Tree* root, int hd){ + + if(root == NULL)return; + + root->hd = hd; + setHorizontalDistance(root->left, hd-1); + setHorizontalDistance(root->right, hd +1); +} +void bottomView(Tree *root, map>&m, int d){ +if(root == NULL)return; +if(m[root->hd].first < d){ +m[root->hd].first = d; +m[root->hd].second = root->data; +} +if(root->left) +bottomView(root->left, m, d+1 ); + +if(root->right) +bottomView(root->right, m, d+1); +} + +int main(){ + + Tree *root = newNode(20); + root->left = newNode(8); + root->right = newNode(22); + root->left->left = newNode(5); + root->left->right = newNode(3); + root->right->left = newNode(4); + root->right->right = newNode(25); + root->left->right->left = newNode(10); + root->left->right->right = newNode(14); + + setHorizontalDistance(root, 0); + + map>m; + bottomView(root, m, 1); + + for(auto x: m){ + cout< inorder, int curr, int s, int e) + { + for(int i=s; i<=e; i++) + { + if(inorder[i]==curr) + return i; + } + return -1; + } + TreeNode *constructTree(vector& preorder, vector& inorder, int s, int e) + { + if(s>e) + return NULL; + int curr = preorder[i++]; + TreeNode *node = new TreeNode(curr); + int pos = search(inorder, curr, s, e); + node->left=constructTree(preorder, inorder, s, pos-1); + node->right=constructTree(preorder, inorder, pos+1, e); + return node; + } + TreeNode* buildTree(vector& preorder, vector& inorder) { + int n=inorder.size(); + return constructTree(preorder, inorder, 0,n-1); + } +}; diff --git a/Trees/Convert Binary Tree to Doubly Linked List.cpp b/Trees/Convert Binary Tree to Doubly Linked List.cpp new file mode 100644 index 00000000..98f19323 --- /dev/null +++ b/Trees/Convert Binary Tree to Doubly Linked List.cpp @@ -0,0 +1,46 @@ +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +}; + +class Solution +{ + public: + void leftNode(Node* root, stack&st) + { + while(root!=NULL) + { + st.push(root); + root=root->left; + } + } + + Node * bToDLL(Node *root) + { + stack st; + leftNode(root,st); + Node *d=newNode(-1), *p=d; + while(!st.empty()) + { + Node *node=st.top(); + st.pop(); + p->right=node; + node->left=p; + p=node; + leftNode(node->right,st); + } + Node *head=d->right; + head->left=NULL; + p->right=NULL; + delete(d); + return head; + } +}; + diff --git a/Trees/LCA.cpp b/Trees/LCA.cpp new file mode 100644 index 00000000..90355e86 --- /dev/null +++ b/Trees/LCA.cpp @@ -0,0 +1,77 @@ +// Program to find "Least Common Ancestor" of two nodes by "Binary Lifting Technique" + +#include +using namespace std; + +int n, l, timer; +vector> adj; +vector tin, tout; +vector> up; + +void dfs(int v, int p) +{ + tin[v] = ++timer; + up[v][0] = p; + for (int i = 1; i <= l; ++i) + up[v][i] = up[up[v][i-1]][i-1]; + + for (int u : adj[v]) { + if (u != p) + dfs(u, v); + } + + tout[v] = ++timer; +} + +bool is_ancestor(int u, int v) +{ + return tin[u] <= tin[v] and tout[u] >= tout[v]; +} + +int lca(int u, int v) +{ + if (is_ancestor(u, v)) + return u; + if (is_ancestor(v, u)) + return v; + for (int i = l; i >= 0; --i) { + if (!is_ancestor(up[u][i], v)) + u = up[u][i]; + } + return up[u][0]; +} + +void preprocess(int root) { + tin.resize(n); + tout.resize(n); + timer = 0; + l = ceil(log2(n)); + up.assign(n, vector(l + 1)); + dfs(root, root); +} + +void solve(){ + int q; + cin>>n>>q; + adj.resize(n + 1); + for(int i = 1;i < n;i++){ + int x; + cin>>x; + x--; + adj[x].push_back(i); + adj[i].push_back(x); + } + preprocess(0); + while(q--){ + int x, y; + cin>>x>>y; + x--;y--; + int ans = lca(x, y); + cout<left){ + root->left->next=root->right; + + if(root->next){ + root->right->next=root->next->left; + } + + connect(root->left); + connect(root->right); + } + return root; + + } +}; \ No newline at end of file diff --git a/Trees/Leetcode-222. Count Complete Tree Nodes.cpp b/Trees/Leetcode-222. Count Complete Tree Nodes.cpp new file mode 100644 index 00000000..b6991cb6 --- /dev/null +++ b/Trees/Leetcode-222. Count Complete Tree Nodes.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vectornum; + int countNodes(TreeNode* root) { + if(root==NULL)return 0; + queueq; + q.push(root); + while(!q.empty()){ + TreeNode*curr = q.front(); + num.push_back(curr->val); + if(curr->left!=NULL) + q.push(curr->left); + if(curr->right!=NULL) + q.push(curr->right); + q.pop(); + } + return num.size(); + } +}; \ No newline at end of file diff --git a/Trees/Leetcode-226. Invert Binary Tree.cpp b/Trees/Leetcode-226. Invert Binary Tree.cpp new file mode 100644 index 00000000..2c79c3c5 --- /dev/null +++ b/Trees/Leetcode-226. Invert Binary Tree.cpp @@ -0,0 +1,8 @@ +TreeNode* invertTree(TreeNode* root) { + if (root) { + invertTree(root->left); + invertTree(root->right); + swap(root->left, root->right); + } + return root; +} \ No newline at end of file diff --git a/Trees/Leetcode-230. Kth Smallest Element in a BST.cpp b/Trees/Leetcode-230. Kth Smallest Element in a BST.cpp new file mode 100644 index 00000000..28a8bd18 --- /dev/null +++ b/Trees/Leetcode-230. Kth Smallest Element in a BST.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vectornum; + int kthSmallest(TreeNode* root, int k) { + queueq; + q.push(root); + while(!q.empty()){ + TreeNode*curr = q.front(); + num.push_back(curr->val); + if(curr->left!=NULL) + q.push(curr->left); + if(curr->right!=NULL) + q.push(curr->right); + q.pop(); + } + sort(num.begin(), num.end()); + return num[k-1]; + } +}; \ No newline at end of file diff --git a/Trees/Leetcode-623. Add One Row to Tree.cpp b/Trees/Leetcode-623. Add One Row to Tree.cpp new file mode 100644 index 00000000..5f55441c --- /dev/null +++ b/Trees/Leetcode-623. Add One Row to Tree.cpp @@ -0,0 +1,82 @@ +/** + * 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: + + // getting all parent nodes for which we want to append nodes + void getBfs(TreeNode* root, int depth , vector&v){ + if(depth==1 && root!=NULL){ + v.push_back(root); + return; + } + if(root==NULL)return; + + getBfs(root->left , depth-1 , v); + getBfs(root->right , depth-1 , v); + + return; + } + + //creating nodes + TreeNode* createNode(int val){ + TreeNode *temp=new TreeNode; + temp->val = val; + return temp; + } + + + TreeNode* addOneRow(TreeNode* root, int val, int depth) { + + //if depth ==1 + if(depth==1){ + TreeNode* temp = createNode(val); + temp ->left = root; + return temp; + } + + + vectorv; + getBfs(root , depth-1 , v); + int s = v.size(); + + for(int i=0; ileft && t->right){ + temp1->left=t->left; + temp2->right=t->right; + t->left = temp1; + t->right = temp2; + } + else if(t->left && t->right==NULL){ + temp1->left=t->left; + t->left = temp1; + t->right = temp2; + } + else if(t->left==NULL && t->right){ + temp2->right=t->right; + t->left = temp1; + t->right = temp2; + } + else{ + t->left = temp1; + t->right = temp2; + } + } + + + return root; + + + } +}; \ No newline at end of file diff --git a/Trees/Level Order Traversal of Binart Tree.cpp b/Trees/Level Order Traversal of Binart Tree.cpp new file mode 100644 index 00000000..bc623350 --- /dev/null +++ b/Trees/Level Order Traversal of Binart Tree.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + void burnTree(TreeNode *root, int time, vector> &ans) + { + if(root==NULL) + return; + if(time==ans.size()) + ans.push_back({}); + ans[time].push_back(root->val); + burnTree(root->left, time+1, ans); + burnTree(root->right, time+1, ans); + } + vector> levelOrder(TreeNode* root) { + vector> ans; + burnTree(root, 0, ans); + return ans; + } +}; diff --git a/Trees/addOneRowToTree.cpp b/Trees/addOneRowToTree.cpp new file mode 100644 index 00000000..d330c76e --- /dev/null +++ b/Trees/addOneRowToTree.cpp @@ -0,0 +1,143 @@ + +#include +#include +using namespace std; +struct TreeNode{ + int val; + TreeNode *left,*right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +/* + + Intuition + Use queues to peform bfs and traverse the tree. When you reach depth - 1 , + perform the operations mentioned in the question + + Approach + There are two cases when you reach depth - 1 using bfs. + Assume curr is the current node at depth - 1 + + * curr->left != NULL + * curr->left == NULL + The code handles the above two cases. + There is also one edge case that the code can't handle. + If the depth is 1 which means we need to add the new_node as the root node. + + So we have to write a seperate code to handle depth = 1 case. +*/ +TreeNode* addOneRow(TreeNode* root, int val, int depth) { + + int d = 0; + if(d == (depth - 1)){ + TreeNode *new_node = new TreeNode(val); + new_node->left = root; + root = new_node; + return root; + } + queue q; + q.push(root); + while(!q.empty()){ + int size = q.size(); + d++; + for(int i=0;ileft){ + TreeNode *temp = curr->left; + new_node->left = temp; + curr->left = new_node; + } + else{ + curr->left = new_node; + } + if(curr->right){ + TreeNode *temp = curr->right; + new_node1->right = temp; + curr->right = new_node1; + } + else{ + curr->right = new_node1; + } + + } + if(curr->left) + q.push(curr->left); + if(curr->right) + q.push(curr->right); + + } + if(d == (depth-1)) + break; + } + return root; +} +======= +/* + +623. Add One Row to Tree +Problem Link: https://leetcode.com/problems/add-one-row-to-tree/description/ +Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. + +Note that the root node is at depth 1. + +The adding rule is: + +Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root. +cur's original left subtree should be the left subtree of the new left subtree root. +cur's original right subtree should be the right subtree of the new right subtree root. +If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree. + +Input: root = [4,2,6,3,1,5], val = 1, depth = 2 +Output: [4,1,1,2,null,null,6,3,1,5] + +Input: root = [4,2,null,3,1], val = 1, depth = 3 +Output: [4,2,null,1,1,3,null,null,1] + +*/ + +/** + * 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: + void dfs(TreeNode* root, int val, int depth,int k){ + if(!root)return; + if(depth==k+1){ + TreeNode *templ=new TreeNode(val); + TreeNode *l=root->left; + root->left=templ; + templ->left=l; + TreeNode *tempr=new TreeNode(val); + TreeNode *r=root->right; + root->right=tempr; + tempr->right=r; + } + dfs(root->left,val,depth,k+1); + dfs(root->right,val,depth,k+1); + return; + } + TreeNode* addOneRow(TreeNode* root, int val, int depth) { + if(depth==1){ + TreeNode *temp=new TreeNode(val); + temp->left=root; + return temp; + } + dfs(root,val,depth,1); + return root; + } +}; + diff --git a/Trees/avltree.c b/Trees/avltree.c new file mode 100644 index 00000000..8bbaab84 --- /dev/null +++ b/Trees/avltree.c @@ -0,0 +1,228 @@ +#include +#include + +// Create Node +struct Node +{ + int key; + struct Node *left; + struct Node *right; + int height; +}; + +int max(int a, int b); + +// Calculate height +int height(struct Node *N) +{ + if (N == NULL) + return 0; + return N->height; +} + +int max(int a, int b) +{ + return (a > b) ? a : b; +} + +// Create a node +struct Node *newNode(int key) +{ + struct Node *node = (struct Node *) + malloc(sizeof(struct Node)); + node->key = key; + node->left = NULL; + node->right = NULL; + node->height = 1; + return (node); +} + +// Right rotate +struct Node *rightRotate(struct Node *y) +{ + struct Node *x = y->left; + struct Node *T2 = x->right; + + x->right = y; + y->left = T2; + + y->height = max(height(y->left), height(y->right)) + 1; + x->height = max(height(x->left), height(x->right)) + 1; + + return x; +} + +// Left rotate +struct Node *leftRotate(struct Node *x) +{ + struct Node *y = x->right; + struct Node *T2 = y->left; + + y->left = x; + x->right = T2; + + x->height = max(height(x->left), height(x->right)) + 1; + y->height = max(height(y->left), height(y->right)) + 1; + + return y; +} + +// Get the balance factor +int getBalance(struct Node *N) +{ + if (N == NULL) + return 0; + return height(N->left) - height(N->right); +} + +// Insert node +struct Node *insertNode(struct Node *node, int key) +{ + // Find the correct position to insertNode the node and insertNode it + if (node == NULL) + return (newNode(key)); + + if (key < node->key) + node->left = insertNode(node->left, key); + else if (key > node->key) + node->right = insertNode(node->right, key); + else + return node; + + // Update the balance factor of each node and + // Balance the tree + node->height = 1 + max(height(node->left), + height(node->right)); + + int balance = getBalance(node); + if (balance > 1 && key < node->left->key) + return rightRotate(node); + + if (balance < -1 && key > node->right->key) + return leftRotate(node); + + if (balance > 1 && key > node->left->key) + { + node->left = leftRotate(node->left); + return rightRotate(node); + } + + if (balance < -1 && key < node->right->key) + { + node->right = rightRotate(node->right); + return leftRotate(node); + } + + return node; +} + +struct Node *minValueNode(struct Node *node) +{ + struct Node *current = node; + + while (current->left != NULL) + current = current->left; + + return current; +} + +// Delete a nodes +struct Node *deleteNode(struct Node *root, int key) +{ + // Find the node and delete it + if (root == NULL) + return root; + + if (key < root->key) + root->left = deleteNode(root->left, key); + + else if (key > root->key) + root->right = deleteNode(root->right, key); + + else + { + if ((root->left == NULL) || (root->right == NULL)) + { + struct Node *temp = root->left ? root->left : root->right; + + if (temp == NULL) + { + temp = root; + root = NULL; + } + else + *root = *temp; + free(temp); + } + else + { + struct Node *temp = minValueNode(root->right); + + root->key = temp->key; + + root->right = deleteNode(root->right, temp->key); + } + } + + if (root == NULL) + return root; + + // Update the balance factor of each node and + // balance the tree + root->height = 1 + max(height(root->left), + height(root->right)); + + int balance = getBalance(root); + if (balance > 1 && getBalance(root->left) >= 0) + return rightRotate(root); + + if (balance > 1 && getBalance(root->left) < 0) + { + root->left = leftRotate(root->left); + return rightRotate(root); + } + + if (balance < -1 && getBalance(root->right) <= 0) + return leftRotate(root); + + if (balance < -1 && getBalance(root->right) > 0) + { + root->right = rightRotate(root->right); + return leftRotate(root); + } + + return root; +} + +// Print the tree +void printPreOrder(struct Node *root) +{ + if (root != NULL) + { + printf("%d ", root->key); + printPreOrder(root->left); + printPreOrder(root->right); + } +} + +int main() +{ + struct Node *root = NULL; + + root = insertNode(root, 2); + root = insertNode(root, 1); + root = insertNode(root, 7); + root = insertNode(root, 4); + root = insertNode(root, 5); + root = insertNode(root, 3); + root = insertNode(root, 8); + + printPreOrder(root); + + root = deleteNode(root, 3); + + printf("\nAfter deletion: "); + printPreOrder(root); + + return 0; +} \ No newline at end of file diff --git a/Trees/binary-tree-level-order-traversal.cpp b/Trees/binary-tree-level-order-traversal.cpp new file mode 100644 index 00000000..018e4d78 --- /dev/null +++ b/Trees/binary-tree-level-order-traversal.cpp @@ -0,0 +1,64 @@ +#include + +using namespace std; + +/** + * Question Link:- https://leetcode.com/problems/binary-tree-level-order-traversal/ + * 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) {} + * }; + */ + +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: + vector> levelOrder(TreeNode* root) { + if(!root) return {}; + + vector> v; + + queue q; + q.push(root); + + + + while(!q.empty()){ + int siz = q.size(); + + vector level; + + for(int i=0;ival); + q.push(node->left); + q.push(node->right); + } + + } + if(!level.empty()){ + v.push_back(level); + } + + } + + + return v; + } +}; \ No newline at end of file diff --git a/Trees/binary-tree-zigzag-level-order-traversal.cpp b/Trees/binary-tree-zigzag-level-order-traversal.cpp new file mode 100644 index 00000000..2bdb7dd0 --- /dev/null +++ b/Trees/binary-tree-zigzag-level-order-traversal.cpp @@ -0,0 +1,70 @@ +#include + +using namespace std; + +/** + * Question Link:- https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ + * 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) {} + * }; + */ + +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: + vector> zigzagLevelOrder(TreeNode* root) { + + vector> ans; + if(!root) return ans; + + queue q; + + q.push(root); + bool flag =false; + + while(!q.empty()){ + int size = q.size(); + vector level; + + for(int i=0;ival) ; + + if(node->left) q.push(node->left); + if(node->right) q.push(node->right); + + + + } + + + flag = !flag; + if(flag == false) + reverse(level.begin() , level.end()) ; + + + ans.push_back(level) ; + + + } + return ans; + + } +}; \ No newline at end of file diff --git a/Trees/binarytreetraversal.c b/Trees/binarytreetraversal.c new file mode 100644 index 00000000..f6110420 --- /dev/null +++ b/Trees/binarytreetraversal.c @@ -0,0 +1,90 @@ + #include + #include + + struct tnode { + int data; + struct tnode *left, *right; + }; + + struct tnode *root = NULL; + + + struct tnode * createNode(int data) { + struct tnode *newNode; + newNode = (struct tnode *) malloc(sizeof(struct tnode)); + newNode->data = data; + newNode->left = NULL; + newNode->right = NULL; + return (newNode); + } + + + void insertion(struct tnode **node, int data) { + if (!*node) { + *node = createNode(data); + } else if (data < (*node)->data) { + insertion(&(*node)->left, data); + } else if (data > (*node)->data) { + insertion(&(*node)->right, data); + } + } + void postOrder(struct tnode *node) { + if (node) { + postOrder(node->left); + postOrder(node->right); + printf("%d ", node->data); + } + return; + } + + + void preOrder(struct tnode *node) { + if (node) { + printf("%d ", node->data); + preOrder(node->left); + preOrder(node->right); + } + return; + } + + + void inOrder(struct tnode *node) { + if (node) { + inOrder(node->left); + printf("%d ", node->data); + inOrder(node->right); + } + return; + } + + int main() { + int data, ch; + while (1) { + printf("\n1. Insertion\n2. Pre-order\n"); + printf("3. Post-order\n4. In-order\n"); + printf("5. Exit\nEnter your choice:"); + scanf("%d", &ch); + switch (ch) { + case 1: + printf("Enter ur data:"); + scanf("%d", &data); + insertion(&root, data); + break; + case 2: + preOrder(root); + break; + case 3: + postOrder(root); + break; + case 4: + inOrder(root); + break; + case 5: + exit(0); + default: + printf(" wrong option\n"); + break; + } + } + return 0; + } \ No newline at end of file diff --git a/Trees/burningTree.cpp b/Trees/burningTree.cpp new file mode 100644 index 00000000..46e6ff6b --- /dev/null +++ b/Trees/burningTree.cpp @@ -0,0 +1,175 @@ +// Burning tree + + +#include +using namespace std; + +struct Node { + int data; + Node *left; + Node *right; + + Node (int val) { + data = val; + left = right = NULL; + } +}; + + +Node *buildTree (string str) { + // Corner Case + if (str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for (string str; iss >> str;) + ip.push_back(str); + + // Create the root of the tree + Node *root = new Node (stoi (ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while (!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node *currNode = queue.front(); + queue.pop(); + + // Get the current Node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if (currVal != "N") { + + // Create the left child for the current Node + currNode->left = new Node (stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if (i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if (currVal != "N") { + + // Create the right child for the current Node + currNode->right = new Node (stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + + + + +class Solution { + public: + Node* createParentMapping(Node* root, int target, map &nodeToParent){ + Node* res = NULL; + + queue q; + q.push(root); + nodeToParent[root] = NULL; + + while(!q.empty()){ + Node* front = q.front(); + q.pop(); + if(front->data == target){ + res = front; + } + if(front->left){ + nodeToParent[front->left] = front; + q.push(front->left); + } + if(front->right){ + nodeToParent[front->right] = front; + q.push(front->right); + } + } + return res; + } + + int burnTree(Node* targetNode, map nodeToParent){ + map visited; + queue q; + q.push(targetNode); + visited[targetNode] = true; + + int ans = 0; + + while(!q.empty()){ + bool flag = 0; + int size = q.size(); + for(int i=0; ileft && !visited[front->left]){ + flag = 1; + q.push(front->left); + visited[front->left] = 1; + } + if(front->right && !visited[front->right]){ + flag = 1; + q.push(front->right); + visited[front->right] = 1; + } + if(nodeToParent[front] && !visited[nodeToParent[front]]){ + flag = 1; + q.push(nodeToParent[front]); + visited[nodeToParent[front]] = 1; + } + } + if(flag){ + ans++; + } + } + return ans; + } + + int minTime(Node* root, int target){ + map nodeToParent; + Node* targetNode = createParentMapping(root, target, nodeToParent); + + int ans = burnTree(targetNode, nodeToParent); + return ans; + } +}; + +int main() { + int t; + cin; + while (t--) { + string s; + getline(cin, s); + Node *root = buildTree(s); + + int target; + cin >> target; + Solution ob; + cout << ob.minTime(root, target) << endl; + } + return 0; +} + + diff --git a/Trees/delete_nodes_BST.cpp b/Trees/delete_nodes_BST.cpp new file mode 100644 index 00000000..bf41e1d0 --- /dev/null +++ b/Trees/delete_nodes_BST.cpp @@ -0,0 +1,139 @@ +#include +using namespace std; + +class Tree +{ +public: + + int val; + Tree *left; + Tree *right; + +public: + + //class constructor called when any object or pointer is created without any parameter. + Tree() + { + val=0; + left=nullptr; + right=nullptr; + } + + //class constructor called when an object or pointer is called while passing an argument (val). + Tree(int val) + { + this->val=val; + this->left=nullptr; + this->right=nullptr; + } + + //builds a Binary Tree taking (int) value as an argument and returns the root to the tree built. + Tree* buildTree(int val) + { + if(this==nullptr) + { + Tree *temp = new Tree(val); + return temp; + } + else + { + Tree *temp=nullptr; + if(this->val>val) + { + temp=this->left->buildTree(val); + this->left=temp; + } + else + { + temp=this->right->buildTree(val); + this->right=temp; + } + return this; + } + } + + //RECURSIVE DFS PREORDER + void preOrder() + { + if(this!=nullptr) + { + cout<val<<","; + this->left->preOrder(); + this->right->preOrder(); + } + } +}; + +Tree* deleteNode(Tree *root, int val) +{ + if(root==nullptr) + return nullptr; + else + { + if(root->val>val) + root->left=deleteNode(root->left,val); + else if(root->valright=deleteNode(root->right,val); + else + { + if(root->left!=nullptr) + { + Tree *temp=root->left; + Tree *trav=temp->right; + if(trav==nullptr) + { + temp->right=root->right; + root=temp; + } + else + { + while(trav->right!=nullptr) + { + temp=trav; + trav=trav->right; + } + temp->right=trav->left; + root->val=trav->val; + trav->left=NULL; + } + } + else if(root->right!=nullptr) + { + Tree *temp=root->right; + Tree *trav=temp->left; + if(trav==nullptr) + { + temp->left=root->left; + root=temp; + } + else + { + while(trav->left!=nullptr) + { + temp=trav; + trav=trav->left; + } + temp->left=trav->right; + root->val=trav->val; + trav->right=NULL; + } + } + else + root=nullptr; + } + return root; + } +} + +int main() +{ + vectortest={8,5,3,6,11,10,9,12}; + Tree *root=nullptr; + for(int i:test) + root=root->buildTree(i); + cout<<"The tree: "; + root->preOrder(); + root=deleteNode(root,6); + cout<<"\nThe tree after deletion: "; + root->preOrder(); +} diff --git a/Trees/flatten-binary-tree-to-linked-list.cpp b/Trees/flatten-binary-tree-to-linked-list.cpp new file mode 100644 index 00000000..a7e58a2c --- /dev/null +++ b/Trees/flatten-binary-tree-to-linked-list.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; + +/** + * Question Link:-https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ + * 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) {} + * }; + */ + +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* rightmost(TreeNode* root){ + if (root->right==NULL) return root; + return rightmost(root->right); + } + + void flatten(TreeNode* root) { + if (root==NULL) return; + TreeNode* nextright; + TreeNode* rightMOST; + + while (root){ + + if (root->left){ + rightMOST = rightmost(root->left); + nextright = root->right; + root->right = root->left; + root->left=NULL; + rightMOST->right=nextright; + } + root=root->right; + } + } +}; \ No newline at end of file diff --git a/Trees/pathSum.cpp b/Trees/pathSum.cpp new file mode 100644 index 00000000..44150f07 --- /dev/null +++ b/Trees/pathSum.cpp @@ -0,0 +1,15 @@ +#include +#include +using namespace std; +struct TreeNode{ + int val; + TreeNode *left,*right; +}; +bool hasPathSum(TreeNode* root, int sum) { + if(!root) + return 0; + + if(!root->left && !root->right) // checks if the sum at the root is equal to target sum + return sum-root->val == 0; + return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val); // Traverses the tree to find the solution at one of the leaf nodes +} diff --git a/ZigZag Conversion b/ZigZag Conversion new file mode 100644 index 00000000..5a222052 --- /dev/null +++ b/ZigZag Conversion @@ -0,0 +1,13 @@ +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows==1:return s + + res="" + for r in range(numRows): + increment=2*(numRows-1) + for i in range(r,len(s),increment): + res+=s[i] + if(r>0 and r findAnagrams(String s, String p) { + int sn = s.length(); + int pn = p.length(); + List res = new ArrayList<>(); + if (sn<=0 || pn<=0) return res; + + int[] pArr = new int[26]; + for (int i = 0; i < pn; i ++) + { + char c = p.charAt(i); + pArr[(int)(c-'a')] ++; + } + + for (int i = 0; i <= sn-pn; i ++) + { + char c = s.charAt(i); + if (pArr[(int)(c-'a')]==0) continue; + if (isAnagram(s, i, i+pn-1, pArr)) + { + res.add(i); + } + } + + return res; + } + + private boolean isAnagram(String s, int start, int end, int[] pArr) + { + int[] sArr = new int[26]; + for (int i = start; i <= end; i ++) + { + char c = s.charAt(i); + if (pArr[(int)(c-'a')]==0) return false; + sArr[(int)(c-'a')] ++; + if (pArr[(int)(c-'a')] findAnagrams(String s, String p) { + int sn = s.length(); + int pn = p.length(); + List res = new ArrayList<>(); + if (sn<=0 || pn<=0) return res; + + int[] pArr = new int[26]; + for (int i = 0; i < pn; i ++) + { + char c = p.charAt(i); + pArr[(int)(c-'a')] ++; + } + + for (int i = 0; i <= sn-pn; i ++) + { + char c = s.charAt(i); + if (pArr[(int)(c-'a')]==0) continue; + if (isAnagram(s, i, i+pn-1, pArr)) + { + res.add(i); + } + } + + return res; + } + + private boolean isAnagram(String s, int start, int end, int[] pArr) + { + int[] sArr = new int[26]; + for (int i = start; i <= end; i ++) + { + char c = s.charAt(i); + if (pArr[(int)(c-'a')]==0) return false; + sArr[(int)(c-'a')] ++; + if (pArr[(int)(c-'a')] +using namespace std; +int main(){ + int lastDigit,sum=0,n; + cin>>n; + int original_n =n; + + while(n>0){ + lastDigit=n%10; + sum = sum + lastDigit*lastDigit*lastDigit; + n=n/10; + } + if(sum==original_n){ + cout<<"Armstrong Number"; + }else{ + cout<<"Not an Armstrong Number"; + + } +} diff --git a/digit_dp.py b/digit_dp.py new file mode 100644 index 00000000..04f057ad --- /dev/null +++ b/digit_dp.py @@ -0,0 +1,21 @@ +# Problem Link -: https://leetcode.com/problems/numbers-at-most-n-given-digit-set/ +# Problem -: Numbers At Most N Given Digit Set +# Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. +# Return the number of positive integers that can be generated that are less than or equal to a given integer n. + + + +# Python Digit DP Solution +def atMostNGivenDigitSet(self, D: List[str], N: int) -> int: + D = list(map(int, D)) + N = list(map(int, str(N))) + + @functools.lru_cache(None) + def dp(i, isPrefix, isBigger): + if i == len(N): + return not isBigger + if not isPrefix and not isBigger: + return 1 + len(D) * dp(i + 1, False, False) + return 1 + sum(dp(i + 1, isPrefix and d == N[i], isBigger or (isPrefix and d > N[i])) for d in D) + + return dp(0, True, False) - 1 diff --git a/disjoint set - Copy/code.cpp b/disjoint set - Copy/code.cpp new file mode 100644 index 00000000..119a8b17 --- /dev/null +++ b/disjoint set - Copy/code.cpp @@ -0,0 +1,102 @@ +// This section is for Disjoint set data structure +// when we find parent of any number in worst case we go O(n) so if for all the numbers on the path we directly make their parent as root +// so when we make M number of operations and take thier average complexity that is alpha(n) which <= 4 for even biggest values +// their is no difference in code except the part where we find parent there we add one more line for changing parent of every node on +// the path + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +int find(vector &parent, int x) +{ + if (parent[x] == x) + { + return x; + } + parent[x] = find(parent, parent[x]); + return parent[x]; +} + +void union_num(vector &parent, vector &rank, int num1, int num2) +{ + int fparent = find(parent, num1); + int sparent = find(parent, num2); + if (fparent == sparent) + { + return; + } + if (rank[fparent] < rank[sparent]) + { + parent[fparent] = sparent; + } + else if (rank[fparent] > rank[sparent]) + { + parent[sparent] = fparent; + } + else + { + parent[fparent] = sparent; + rank[sparent]++; + } +} + +void solve() +{ + int n = 8; // 0 - 7 + vector parent(n), rank(n, 0); + for (int i = 0; i < n; i++) + { + parent[i] = i; + } + int total; + cin >> total; + while (total--) + { + int choice; + cin >> choice; + if (choice == 1) + { + // union + int num1, num2; + cin >> num1 >> num2; + union_num(parent, rank, num1, num2); + } + else + { + // find + int num1, num2; + cin >> num1 >> num2; + int fparent = find(parent, num1), sparent = find(parent, num2); + + if (fparent == sparent) + { + cout << "They are in same group!!" << endl; + } + else + { + cout << "They are not in same group!!" << endl; + } + } + + cout << "Check parent array: " << endl; + for (int i = 0; i < parent.size(); i++) + { + cout << parent[i] << " "; + } + cout << endl; + cout << "Check Rank array: " << endl; + for (int i = 0; i < rank.size(); i++) + { + cout << rank[i] << " "; + } + cout << endl; + } +} + +int main() +{ + solve(); + return 0; +} \ No newline at end of file diff --git a/disjoint set - Copy/readme.txt b/disjoint set - Copy/readme.txt new file mode 100644 index 00000000..d195e2ff --- /dev/null +++ b/disjoint set - Copy/readme.txt @@ -0,0 +1,8 @@ +This section is for Disjoint set data structure + + +First one is basic one which adds first over second whithout any optimisation + +second one sees height of tree and add according to that + +Third one makes average time complexity <= 4 because it makes parent of every node as root during any normal find function \ No newline at end of file diff --git a/fibonacci b/fibonacci new file mode 100644 index 00000000..78b7de6e --- /dev/null +++ b/fibonacci @@ -0,0 +1,14 @@ +#include +using namespace std; +int main(){ + int n; + cin >> n; + + int t1=0,t2=1; + for(int i=1;i<=n;i++){ + cout< +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +int main() +{ + int v; + v = 5; + int mat[v][v]; + memset(mat, 0, sizeof(mat)); + // adding edges + // 0-1 0-4 1-3 3-4 2-3 + + mat[0][1] = mat[1][0] = 1; + mat[0][4] = mat[4][0] = 1; + mat[1][3] = mat[3][1] = 1; + mat[3][4] = mat[4][3] = 1; + mat[2][3] = mat[3][2] = 1; + + // if graph is undirected then mat is symmetric otherwise it depends on edges + + cout << "CHECK MATRIX: " << endl; + for (int i = 0; i < v; i++) + { + for (int j = 0; j < v; j++) + { + cout << mat[i][j] << " "; + } + cout << endl; + } + return 0; +} \ No newline at end of file diff --git a/graph/code10.cpp b/graph/code10.cpp new file mode 100644 index 00000000..e47c4ce7 --- /dev/null +++ b/graph/code10.cpp @@ -0,0 +1,85 @@ +// Detect cycle in directed graph --> DFS +// here we find that if in stack call of recursion of dfs there is a back edge +// i.e. if a number finds that one if its adjacent is already visited and active in stack then that means that there is a cycle + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); +} + +bool dfs(vector vec[], vector &visited, vector &recst, int source) +{ + visited[source] = true; + recst[source] = true; + for (int i = 0; i < vec[source].size(); i++) + { + int adjacent = vec[source][i]; + if (visited[adjacent] == false) + { + if (dfs(vec, visited, recst, adjacent) == true) + { + return true; + } + } + else if (visited[adjacent] == true && recst[adjacent] == true) + { + return true; + } + } + recst[source] = false; + return false; +} + +bool dfs_rec(vector vec[], int v) +{ + vector visited(v, false); + vector recst(v, false); + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + if (dfs(vec, visited, recst, i)) + { + return true; + } + } + } + return false; +} + +int main() +{ + int v; + v = 6; + vector vec[v]; + + // adding edges from this point + + // add_edge(vec, 0, 1); + // add_edge(vec, 1, 2); + // add_edge(vec, 2, 3); + // add_edge(vec, 2, 4); + // add_edge(vec, 4, 5); + // add_edge(vec, 5, 1); + + add_edge(vec, 0, 1); + add_edge(vec, 2, 3); + add_edge(vec, 3, 4); + add_edge(vec, 4, 5); + add_edge(vec, 5, 1); + + if (dfs_rec(vec, v)) + { + cout << "There is a cycle in the graph!!" << endl; + } + else + { + cout << "There isnt a cycle in the graph!!" << endl; + } + return 0; +} \ No newline at end of file diff --git a/graph/code11.cpp b/graph/code11.cpp new file mode 100644 index 00000000..8aa67dca --- /dev/null +++ b/graph/code11.cpp @@ -0,0 +1,72 @@ +// Topological Sort -> Kahn's Based algorithm --> BFS +// Kahn algorithm is based on removing the vertex which do not depend on any other vertex i.e having 0 indegree +// and then keep on removing and finding the sequence. + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); +} + +void topo_sort(vector vec[], int v) +{ + vector indegree(v, 0); + for (int i = 0; i < v; i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + int adjacent = vec[i][j]; + indegree[adjacent]++; + } + } + queue q; + for (int i = 0; i < indegree.size(); i++) + { + if (indegree[i] == 0) + { + q.push(i); + } + } + cout << "TOPOLOGICAL SORT: " << endl; + while (q.empty() == false) + { + int curr = q.front(); + q.pop(); + + cout << curr << " "; + for (int i = 0; i < vec[curr].size(); i++) + { + int adjacent = vec[curr][i]; + + indegree[adjacent]--; + if (indegree[adjacent] == 0) + { + q.push(adjacent); + } + } + } + return; +} + +int main() +{ + int v; + v = 5; + vector vec[v]; + + // adding edges from this point + add_edge(vec, 0, 1); + add_edge(vec, 0, 3); + add_edge(vec, 1, 2); + add_edge(vec, 2, 4); + add_edge(vec, 3, 1); + add_edge(vec, 3, 4); + + topo_sort(vec, v); + + return 0; +} \ No newline at end of file diff --git a/graph/code12.cpp b/graph/code12.cpp new file mode 100644 index 00000000..cfa7f143 --- /dev/null +++ b/graph/code12.cpp @@ -0,0 +1,75 @@ +// Topological Sort -> DFS +// In DFS type approach we first go till end where there are no more adjacents left that means we can then push them +// and above that we will push vertex which are parents and we will do it with recursion. + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); +} + +void topo_sort(vector vec[], vector &visited, int source, stack &s) +{ + cout<<"source: "< vec[], int v) +{ + vector visited(v, false); + stack s; + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + topo_sort(vec, visited, i, s); + } + } + + while(s.size() > 0) { + int curr = s.top(); + s.pop(); + cout< vec[v]; + + // adding edges from this point + // add_edge(vec, 0, 1); + // add_edge(vec, 0, 3); + // add_edge(vec, 1, 2); + // add_edge(vec, 2, 4); + // add_edge(vec, 3, 1); + // add_edge(vec, 3, 4); + + add_edge(vec, 0, 1); + // add_edge(vec, 0, 3); + add_edge(vec, 1, 2); + add_edge(vec, 1, 3); + add_edge(vec, 3, 2); + // add_edge(vec, 3, 4); + + topo_rec(vec, v); + + return 0; +} \ No newline at end of file diff --git a/graph/code13.cpp b/graph/code13.cpp new file mode 100644 index 00000000..69c07b09 --- /dev/null +++ b/graph/code13.cpp @@ -0,0 +1,151 @@ +// Shortest Path in DAG (Weighted) +// shortest path in DAG is based on the fact that in DAG we can find topo sort +// and topo sort represents source to sink i.e we will start with a node which does not depend on any other node +// and keep on traversing until we find last node + +// here we will start with the most independent node and then find shortest path from this to all its adjacent nodes +// which means that when we reach any node we already covered all nodes which comes before it and we already explored all possible +// possibilities (i.e shortest path) + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector> vec[], int u, int v, int weight) +{ + vec[u].push_back({v, weight}); +} + +vector topo_sort(vector> vec[], int v) +{ + // here we will find topo sort by using bfs code for that + vector indegree(v, 0); + for (int i = 0; i < v; i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + indegree[vec[i][j].first]++; + } + } + + queue q; + for (int i = 0; i < indegree.size(); i++) + { + if (indegree[i] == 0) + { + q.push(i); + } + } + + vector ans; + while (q.empty() == false) + { + int curr = q.front(); + q.pop(); + + ans.push_back(curr); + for (int i = 0; i < vec[curr].size(); i++) + { + int adjacent = vec[curr][i].first; + indegree[adjacent]--; + + if (indegree[adjacent] == 0) + { + q.push(adjacent); + } + } + } + + return ans; +} + +void shortest_dist(vector> vec[], vector &sort_vec, int v, int source) +{ + vector dist(v, INT_MAX); + dist[source] = 0; + + int pos = -1; + + for (int i = 0; i < sort_vec.size(); i++) + { + + // cout << sort_vec[i] << " "; + if (sort_vec[i] == source) + { + pos = i; + break; + } + } + + // cout<<"pos: "< dist[curr] + vec[curr][j].second) + { + dist[adjacent] = dist[curr] + vec[curr][j].second; + } + } + } + + cout << "CHECK SHORTEST DISTANCE:" << endl; + for (int i = 0; i < dist.size(); i++) + { + cout << dist[i] << " "; + } + cout << endl; +} + +int main() +{ + clock_t start = clock(); + + // int v = 6; + // vector> adj[v]; + + // // adding edges now + // add_edge(adj, 0, 1, 4); + // add_edge(adj, 0, 2, 2); + // add_edge(adj, 1, 3, 10); + // add_edge(adj, 1, 2, 5); + // add_edge(adj, 2, 4, 3); + // add_edge(adj, 4, 3, 4); + // add_edge(adj, 3, 5, 11); + + // vector sort_vec = topo_sort(adj, v); + + // int source = 1; + + // shortest_dist(adj, sort_vec, v, source); + + int v = 4; + vector> adj[v]; + + // adding edges now + add_edge(adj, 0, 1, 15); + add_edge(adj, 0, 2, 2); + add_edge(adj, 2, 3, 3); + add_edge(adj, 3, 1, 4); + + vector sort_vec = topo_sort(adj, v); + + int source = 0; + + shortest_dist(adj, sort_vec, v, source); + + clock_t end = clock(); + double elapsed = double(end - start) / CLOCKS_PER_SEC; + // printf("Time measured: %.4f seconds.", elapsed); + return 0; +} \ No newline at end of file diff --git a/graph/code14.cpp b/graph/code14.cpp new file mode 100644 index 00000000..7c3cfe15 --- /dev/null +++ b/graph/code14.cpp @@ -0,0 +1,161 @@ +// Minimum Spanning tree +// Basically it is forming a tree kind of structure where there are v vertices and v-1 edges and every node is connected to other node +// directly or indirectly +// In prims algorithm, we make two sets of (included in MST) & (Not included in MST) +// then we take first node include in MST and then take weight of all edges connected to it and not included in MST and then find minimum +// of them and making this move again and again till we include (v-1) edges +// also graph should be connected weighted undirected + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector> vec[], int u, int v, int weight) +{ + vec[u].push_back({v, weight}); + vec[v].push_back({u, weight}); +} + +// this algo is without using priority queue +void prims_algo1(vector> vec[], int v) +{ + // one array for checking whether included in mst or not + // second array for distance computation + + vector mst(v, false); + vector dist(v, INT_MAX); + + // int ans = 0; + + int source = 0; + dist[source] = 0; + + for (int i = 0; i <= v - 1; i++) + { + // finding minimum edge which includes one non added node + int pos = -1; // index of node which is not yet included in MST and is minimum + + // cout << "dist: array: " << endl; + // for (int j = 0; j < dist.size(); j++) + // { + // cout << dist[j] << " "; + // } + // cout<<"mist array: "< vec[pos][j].second && mst[adjacent] == false) + { + dist[adjacent] = vec[pos][j].second; + } + } + } + + int ans = 0; + for (int i = 0; i < dist.size(); i++) + { + ans += dist[i]; + } + cout << "final answer from algo 1 is : " << ans << endl; +} + +struct mycmp +{ + bool operator()(const pair &a, const pair &b) + { + return a.second > b.second; + } +}; + +void prims_algo2(vector> vec[], int v) +{ + vector mst(v, false); + vector dist(v, INT_MAX); + + dist[0] = 0; + priority_queue, vector>, mycmp> pq; + pq.push({0, 0}); + + int ans = 0; + + int count = 0; + for (int i = 0; i < v; i++) + { + while (pq.empty() == false && mst[pq.top().first] == true) + { + pq.pop(); + } + pair curr = pq.top(); + pq.pop(); + + // cout << "curr.first() " << curr.first << " curr.second() " << curr.second << endl; + + mst[curr.first] = true; + ans += curr.second; + for (int j = 0; j < vec[curr.first].size(); j++) + { + int adjacent = vec[curr.first][j].first; + if (mst[adjacent] == false && dist[adjacent] > vec[curr.first][j].second) + { + pq.push({adjacent, vec[curr.first][j].second}); + } + } + } + cout << "Final answer from algo 2 is : " << ans << endl; +} + +int main() +{ + int v = 7; + vector> adj[v]; + + // adding all edges now + add_edge(adj, 0, 1, 7); + add_edge(adj, 0, 3, 5); + add_edge(adj, 1, 3, 9); + add_edge(adj, 1, 2, 8); + add_edge(adj, 1, 4, 7); + add_edge(adj, 2, 4, 5); + add_edge(adj, 3, 4, 15); + add_edge(adj, 3, 5, 6); + add_edge(adj, 4, 5, 8); + add_edge(adj, 4, 6, 9); + add_edge(adj, 5, 6, 11); + + // int v = 5; + // vector> adj[v]; + + // add_edge(adj, 0, 1, 5); + // add_edge(adj, 0, 2, 2); + // add_edge(adj, 1, 2, 4); + // add_edge(adj, 1, 4, 1); + // add_edge(adj, 2, 3, 6); + // add_edge(adj, 4, 3, 3); + + prims_algo1(adj, v); + + prims_algo2(adj, v); + + return 0; +} \ No newline at end of file diff --git a/graph/code15.cpp b/graph/code15.cpp new file mode 100644 index 00000000..2fdcf6e1 --- /dev/null +++ b/graph/code15.cpp @@ -0,0 +1,143 @@ +// minimum spanning tree with kruskal algorithm +// In this algorithm we take all the edges and sort them in increasing order of their weights +// them we take an edge and find if adding it leads to any cycle or not +// if it does not form a cycle then we keep it added otherwise we remove it and move on to next one + +// for cycle detection we can run a cycle detection algorithm or we can find it with the help of union add and find which will take less +// time complexity than normal cycle detection algorithm + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +struct node +{ + int u, v, weight; +}; + +bool mycomp(node n1, node n2) +{ + return n1.weight < n2.weight; +} + +void add_edge(vector> vec[], int u, int v, int weight) +{ + vec[u].push_back({v, weight}); + // vec[v].push_back({u, weight}); +} + +int find(vector &parent, int x) +{ + if (parent[x] == x) + { + return x; + } + parent[x] = find(parent, parent[x]); + return parent[x]; +} + +void make_union(vector &parent, vector &rank, int a, int b) +{ + int first_parent = find(parent, a); + int second_parent = find(parent, b); + + if (first_parent == second_parent) + { + return; + } + + if (rank[first_parent] < rank[second_parent]) + { + parent[first_parent] = second_parent; + } + else if (rank[first_parent] > rank[second_parent]) + { + parent[second_parent] = first_parent; + } + else + { + parent[first_parent] = second_parent; + rank[second_parent]++; + } +} + +void kruskal(vector> vec[], int v) +{ + vector arr(v), rank(v, 0); + for (int i = 0; i < v; i++) + { + arr[i] = i; + } + vector nodes; + for (int i = 0; i < v; i++) + { + int curr = i; + for (int j = 0; j < vec[curr].size(); j++) + { + int adj = vec[curr][j].first; + int adj_weight = vec[curr][j].second; + + nodes.push_back({curr, adj, adj_weight}); + } + } + sort(nodes.begin(), nodes.end(), mycomp); + + int mini_weight = 0; + + for (int i = 0; i < nodes.size(); i++) + { + node curr = nodes[i]; + int find_first = find(arr, curr.u); + int find_sec = find(arr, curr.v); + + if (find_first == find_sec) + { + continue; + } + else + { + make_union(arr, rank, curr.u, curr.v); + cout << "Connected Edge: " << curr.u << " " << curr.v << " " << curr.weight << endl; + mini_weight += curr.weight; + } + } + + cout << "Minimum Spanning Tree weight: " << mini_weight << endl; +} + +int main() +{ + // int v = 6; + // vector> adj[v]; + + // // adding edges now + // add_edge(adj, 0, 2, 6); + // add_edge(adj, 1, 5, 1); + // add_edge(adj, 2, 5, 2); + // add_edge(adj, 2, 3, 5); + // add_edge(adj, 3, 4, 3); + // add_edge(adj, 4, 5, 4); + + int v = 9; + vector> adj[v]; + + // adding edges now + add_edge(adj, 0, 1, 4); + add_edge(adj, 1, 2, 8); + add_edge(adj, 2, 3, 7); + add_edge(adj, 3, 4, 9); + add_edge(adj, 4, 5, 10); + add_edge(adj, 5, 6, 2); + add_edge(adj, 6, 7, 1); + add_edge(adj, 7, 0, 8); + add_edge(adj, 1, 7, 11); + add_edge(adj, 3, 5, 14); + add_edge(adj, 2, 8, 2); + add_edge(adj, 6, 8, 6); + add_edge(adj, 7, 8, 7); + + kruskal(adj, v); + + return 0; +} \ No newline at end of file diff --git a/graph/code16.cpp b/graph/code16.cpp new file mode 100644 index 00000000..4ec32674 --- /dev/null +++ b/graph/code16.cpp @@ -0,0 +1,139 @@ +// In this code we will implement Dijstra's algorithm +// Dijstra's works same way as Prim's algorithm with only difference +// (in prims we consider only edges) (in dijstra we consider dist upto some node with its adjacent) + +// here we take one node check all adjacents of it and chec if we can get any shorter distance from our current point +// if we get shorter we consider it.. otherwise ignore it + +// here we will use priority queue to get that node which is at minimum distance currently so we can get minimum distance for its adjacent + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector> vec[], int u, int v, int weight) +{ + vec[u].push_back({v, weight}); + vec[v].push_back({u, weight}); +} + +// without priority queue +void dijstra1(vector> vec[], int v, int source) +{ + vector mst(v, false); + vector dist(v, INT_MAX); + dist[source] = 0; + + for (int i = 0; i < v; i++) + { + int u = -1; + for (int j = 0; j < dist.size(); j++) + { + if (mst[j] == false && (u == -1 || dist[j] < dist[u])) + { + u = j; + } + } + mst[u] = true; + for (int j = 0; j < vec[u].size(); j++) + { + int adjacent = vec[u][j].first; + int adj_weight = vec[u][j].second; + + if (mst[adjacent] == false && dist[adjacent] > dist[u] + adj_weight) + { + dist[adjacent] = dist[u] + adj_weight; + } + } + } + + cout << "Minimum distances(without priority queue) are: " << endl; + for (int i = 0; i < dist.size(); i++) + { + cout << dist[i] << " "; + } + cout << endl; +} + +struct mycmp +{ + bool operator()(const pair &p1, const pair &p2) + { + return p1.second > p2.second; + } +}; + +// with priority queue +void dijstra2(vector> vec[], int v, int source) +{ + vector dist(v, INT_MAX); + vector mst(v, false); + + dist[source] = 0; + priority_queue, vector>, mycmp> pq; + pq.push({source, 0}); + + for (int i = 0; i < v; i++) + { + while (pq.empty() == false && mst[pq.top().first] == true) + { + pq.pop(); + } + + pair curr = pq.top(); + pq.pop(); + + for (int j = 0; j < vec[curr.first].size(); j++) + { + int adjacent = vec[curr.first][j].first; + int adj_weight = vec[curr.first][j].second; + + if (mst[adjacent] == false && dist[adjacent] > dist[curr.first] + adj_weight) + { + dist[adjacent] = dist[curr.first] + adj_weight; + pq.push({adjacent, dist[adjacent]}); + } + } + } + cout << "Minimum distances(priority queue) are: " << endl; + for (int i = 0; i < dist.size(); i++) + { + cout << dist[i] << " "; + } + cout << endl; +} + +int main() +{ + // int v = 5; + // vector> adj[v]; + + // add_edge(adj, 0, 1, 6); + // add_edge(adj, 0, 3, 1); + // add_edge(adj, 1, 3, 2); + // add_edge(adj, 3, 4, 1); + // add_edge(adj, 1, 4, 2); + // add_edge(adj, 1, 2, 5); + // add_edge(adj, 2, 4, 5); + + // int source = 0; + + int v = 5; + vector> adj[v]; + + add_edge(adj, 0, 1, 3); + add_edge(adj, 0, 2, 1); + add_edge(adj, 1, 2, 7); + add_edge(adj, 2, 3, 2); + add_edge(adj, 1, 3, 5); + add_edge(adj, 1, 4, 1); + add_edge(adj, 3, 4, 7); + + int source = 2; + + + dijstra1(adj, v, source); + dijstra2(adj, v, source); + return 0; +} \ No newline at end of file diff --git a/graph/code17.cpp b/graph/code17.cpp new file mode 100644 index 00000000..6513f863 --- /dev/null +++ b/graph/code17.cpp @@ -0,0 +1,72 @@ +// In this code we will do shortest path code by bellman ford algorithm +// This code is dp implementation where we store result for (x-1)th edge and use it for xth edge +// we run one loop for v-1 cause in worst case we can go to last node in v-1 time +// and inside that loop we do relaxation of all edges + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector> vec[], int u, int v, int weight) +{ + vec[u].push_back({v, weight}); +} + +struct node +{ + int u, v, weight; +}; + +void bellman_ford(vector> vec[], int v, int source) +{ + vector edges; + vector dist(v, inf); + dist[source] = 0; + for (int i = 0; i < v; i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + edges.push_back({i, vec[i][j].first, vec[i][j].second}); + } + } + + for (int i = 0; i < v - 1; i++) + { + for (int j = 0; j < edges.size(); j++) + { + node curr = edges[j]; + + int curr_u = curr.u, curr_v = curr.v, curr_weight = curr.weight; + if (dist[curr_v] > dist[curr_u] + curr_weight) + { + dist[curr_v] = dist[curr_u] + curr_weight; + } + } + } + + cout << "FINAL SHORTEST DISTANCES VIA BELLMAN FORD ALGORITHM: " << endl; + for (int i = 0; i < dist.size(); i++) + { + cout << dist[i] << " "; + } + cout << endl; +} + +int main() +{ + int v = 4; + vector> adj[v]; + + // adding edges now + add_edge(adj, 0, 1, 1); + add_edge(adj, 0, 2, 4); + add_edge(adj, 1, 2, -3); + add_edge(adj, 1, 3, 2); + add_edge(adj, 2, 3, 3); + + int source = 0; + bellman_ford(adj, v, source); + + return 0; +} \ No newline at end of file diff --git a/graph/code18.cpp b/graph/code18.cpp new file mode 100644 index 00000000..1a3f2367 --- /dev/null +++ b/graph/code18.cpp @@ -0,0 +1,123 @@ +// Strongly connected components (Kosaraju's algorithm) +// In this code we will be finding strongly connected components in directed connected graphs +// Here when we do observation we find that if we start from sink side of nodes and try to find connected components then we get them right +// but if we start from source side we can never get it cause source side will also include sink as well and not strongly components as well + +// So the algo has three steps +// 1. find source to sink side thorugh topological sort +// 2. reverse all the edges +// 3. check from topo sort and print all connected components in one go! + +// so when we find source to sink and reverse edges then source actually becomes sink now and we are traversing from sink side .. also +// connected components stay connected when reversed so we reverse edges + +// one doubt can be why cant we just start from sink side without reversing edges .. here there are chances that we will include those which are not +// part of connected components + +// example: 0->1 , 1->2 , 1->3, 3->1 .. here topo sort will be 0, 1, 2, 3... when we start from 3 .. connected components will be : 3 0 1 2... +// which is wrong + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); +} + +void topo_sort(vector vec[], int source, vector &visited, stack &st) +{ + visited[source] = true; + for (int i = 0; i < vec[source].size(); i++) + { + int adjacent = vec[source][i]; + if (visited[adjacent] == false) + { + topo_sort(vec, adjacent, visited, st); + } + } + st.push(source); +} + +void find_transpose(vector vec[], int v, vector transpose[]) +{ + for (int i = 0; i < v; i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + int first = i; + int second = vec[i][j]; + add_edge(transpose, second, first); + } + } +} + +void dfs(vector transpose[], int source, vector &visited) +{ + cout << source << " "; + visited[source] = true; + for (int i = 0; i < transpose[source].size(); i++) + { + int adjacent = transpose[source][i]; + if (visited[adjacent] == false) + { + dfs(transpose, adjacent, visited); + } + } +} + +void kosaraju(vector vec[], int v, vector transpose[]) +{ + vector visited(v, false); + int source = 0; + stack st; + // finding topo sort first + topo_sort(vec, source, visited, st); + + // finding transpose + find_transpose(vec, v, transpose); + + // final step of printing connected components .. we wll do it via dfs + for (int i = 0; i < visited.size(); i++) + { + // making visited vector again false as it is used in topo_sort and it is all true + visited[i] = false; + } + cout << "Printing connected components: " << endl; + for (int i = 0; i < visited.size(); i++) + { + if (visited[i] == false) + { + dfs(transpose, i, visited); + cout << endl; + } + } +} + +int main() +{ + // int v = 5; + // vector adj[v], transpose[v]; + // // adding edges now + // add_edge(adj, 0, 1); + // add_edge(adj, 1, 2); + // add_edge(adj, 2, 0); + // add_edge(adj, 1, 3); + // add_edge(adj, 3, 4); + + int v = 6; + vector adj[v], transpose[v]; + // adding edges now + add_edge(adj, 0, 1); + add_edge(adj, 1, 2); + add_edge(adj, 2, 3); + add_edge(adj, 3, 0); + add_edge(adj, 3, 4); + add_edge(adj, 4, 5); + add_edge(adj, 5, 4); + + kosaraju(adj, v, transpose); + return 0; +} \ No newline at end of file diff --git a/graph/code19.cpp b/graph/code19.cpp new file mode 100644 index 00000000..ba9ce85e --- /dev/null +++ b/graph/code19.cpp @@ -0,0 +1,129 @@ +// Articulation Point + +// In this code, we will see articulation point .. articulation point is point .. removal of which makes 2 or more components +// one easiest way to handle this would be removing each vertex and count connected components for it.. it takes O(E * (v+E)) time + +// now our approach is discovery time and min time .. discovery time refers to time when it was discovered and min time refers to time +// min discovery time it can reach or more to say which min ancestor it can reach in discovery tree.. + +// now for any child v of any node u if min[v] >= dis[u] then that node is articulation point .. that is cause if min[v] is greater +// than discovery time of that node means any child of this node cant reach ancestor and removing this node will definitely convert tree into +// two parts .. but if any child can reach ancestor means even if we remove this node child will still be attached to ancestor and removing +// this node wont do any good so it is not an articulation point + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +// dist_minm function gives discovery time and low time for any node... +// here we firstly give (discovery time and low time) to each node according to their finding time +// then whenever we found a node which is already visited before we give its discovery time to all nodes from which this can be reached +// we do it by firsty applying condition where we find a visited node and then we reduce (low time) by calling this min func after recursion +// so when we call min function in recursion we already have minimum for adjacent which we got from elseif condition and we wil further use it now + +// note: line 48 will execute recursively then at the end line 60 will update it then line 50 will make further updations +void dist_minm(vector vec[], int source, vector &visited, vector &disc, vector &low, int &time, int parent, + vector &isap) +{ + visited[source] = true; + disc[source] = low[source] = time; + time++; + + int children = 0; + + for (int i = 0; i < vec[source].size(); i++) + { + int adjacent = vec[source][i]; + if (visited[adjacent] == false) + { + children++; + // calling recursion function + dist_minm(vec, adjacent, visited, disc, low, time, source, isap); + // after we make low value less for adjacent we call this fucntion so that this can further update it + low[source] = min(low[source], low[adjacent]); + + if (low[adjacent] >= disc[source] && parent != -1) + { + isap[source] = true; + } + } + // when we get visited adjacent we call min function to make low value less... + else if (visited[adjacent] == true && adjacent != parent) + { + low[source] = min(disc[adjacent], low[source]); + } + } + // we separately check for root node as even if nodes ends at node there is no prior node from which we can say that it made two parts + // so we check for children of this node and by children we means that children which are not reachable from each other directly .. they + // firstly have to go through root itself.. + if (parent == -1 && children > 1) + { + isap[source] = true; + } +} + +void arti_point(vector vec[], int v) +{ + vector visited(v, false), isap(v, false); + vector disc(v), low(v); + + int time = 1; + + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + dist_minm(vec, i, visited, disc, low, time, -1, isap); + } + } + + cout << "All articulation points: " << endl; + for (int i = 0; i < isap.size(); i++) + { + if (isap[i] == true) + { + cout << i << " "; + } + } + cout << endl; + + // cout << "disc time: " << endl; + // for (int i = 0; i < disc.size(); i++) + // { + // cout << disc[i] << " "; + // } + + // cout << endl; + // cout << "low time: " << endl; + // for (int i = 0; i < low.size(); i++) + // { + // cout << low[i] << " "; + // } + // cout << endl; +} + +int main() +{ + int v = 7; + vector vec[v]; + + // adding edges now + add_edge(vec, 0, 1); + add_edge(vec, 1, 2); + add_edge(vec, 2, 3); + add_edge(vec, 0, 3); + add_edge(vec, 1, 4); + add_edge(vec, 4, 5); + add_edge(vec, 5, 6); + add_edge(vec, 4, 6); + + arti_point(vec, v); + return 0; +} \ No newline at end of file diff --git a/graph/code2.cpp b/graph/code2.cpp new file mode 100644 index 00000000..698a1ce9 --- /dev/null +++ b/graph/code2.cpp @@ -0,0 +1,42 @@ +// adjacency List show +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +void show_list(vector vec[], int list_size) +{ + for (int i = 0; i < list_size; i++) + { + cout << i << " --> "; + for (int j = 0; j < vec[i].size(); j++) + { + cout << vec[i][j] << " "; + } + cout << endl; + } +} + +int main() +{ + int v; + v = 5; + vector adj[v]; + + // adding all edges + add_edge(adj, 0, 1); + add_edge(adj, 0, 4); + add_edge(adj, 1, 3); + add_edge(adj, 3, 4); + add_edge(adj, 2, 3); + + cout << "Check Matrix: " << endl; + show_list(adj, v); + return 0; +} \ No newline at end of file diff --git a/graph/code20.cpp b/graph/code20.cpp new file mode 100644 index 00000000..7b698b5c --- /dev/null +++ b/graph/code20.cpp @@ -0,0 +1,109 @@ +// In this code we will do bridges in graph... + +// by bridges we mean any edge .. removal of which creates extra number of graphs components .. +// one simple approach can be we remove each edge and and then check for count of connected components +// this approach will take O(E * (V+E)) (E for count of edges as we have to remove each edge and (V+E) for the function to check count of +// connected components + +// second approach is doing this with the concept of discovery time and low time (same as articulation point) +// but in that condition was min[adjacent] >= disc[source] but here it will be min[adjacent] > disc[source] +// as we need to check if some nodes are completely on one side and others on one side .. and if we keep equal conditon then +// that means there is other edge connected to other half and we can't say its a bridge.. + +// also there is no concept of root condition(there was one in articulation point) cause there we were checking for nodes +// but here it is edge + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +// dfs_func function gives discovery time and low time for any node... +// here we firstly give (discovery time and low time) to each node according to their finding time +// then whenever we found a node which is already visited before we give its discovery time to all nodes from which this can be reached +// we do it by firsty applying condition where we find a visited node and then we reduce (low time) by calling this min func after recursion +// so when we call min function in recursion we already have minimum for adjacent which we got from elseif condition and we wil further use it now + +// note: line 49 will execute recursively then at the end line 61 will update it then line 51 will make further updations + +void dfs_func(vector vec[], int source, vector &visited, vector &disc, vector &low, int &time, int parent) +{ + visited[source] = true; + disc[source] = low[source] = time; + + time++; + + for (int i = 0; i < vec[source].size(); i++) + { + int adjacent = vec[source][i]; + if (visited[adjacent] == false) + { + + // calling recursion function + dfs_func(vec, adjacent, visited, disc, low, time, source); + // after we make low value less for adjacent we call this fucntion so that this can further update it + low[source] = min(low[source], low[adjacent]); + + if (low[adjacent] > disc[source]) + { + cout << source << " " << adjacent << endl; + } + } + // when we get visited adjacent we call min function to make low value less... + else if (visited[adjacent] == true && adjacent != parent) + { + low[source] = min(low[source], disc[adjacent]); + } + } +} + +void bridges(vector vec[], int v) +{ + vector disc(v), low(v); + vector visited(v, false); + + int time = 1; + + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + dfs_func(vec, i, visited, disc, low, time, -1); + } + } +} + +int main() +{ + // int v = 7; + // vector vec[v]; + + // // adding edges now + // add_edge(vec, 0, 1); + // add_edge(vec, 0, 3); + // add_edge(vec, 1, 2); + // add_edge(vec, 1, 4); + // add_edge(vec, 2, 3); + // add_edge(vec, 4, 5); + // add_edge(vec, 4, 6); + // add_edge(vec, 5, 6); + + // bridges(vec, v); + + int v = 5; + vector vec[v]; + + add_edge(vec, 1, 0); + add_edge(vec, 0, 2); + add_edge(vec, 2, 1); + add_edge(vec, 0, 3); + add_edge(vec, 3, 4); + bridges(vec, v); + return 0; +} \ No newline at end of file diff --git a/graph/code3.cpp b/graph/code3.cpp new file mode 100644 index 00000000..a8854dd9 --- /dev/null +++ b/graph/code3.cpp @@ -0,0 +1,25 @@ +/* +Comparison in adjaceny List or matrix + +Adjacency List +1. this takes size upto O(v+E)/O(V+2*E) for directed and undirected graph respectively. +2. Finding if there is a edge between two vertices is O(degree(node)) or O(v) as it can be connected to all other nodes. +3. finding degree of any vertex is O(E) / O(V) because maximum it can be connected with all other vertices + but in maximum cases it is sparse matrix so it would be really less compared to matrix. +4. Adding an edge: O(1) as we have to do one pushback operation +5. Removing an Edge: O(V)/O(E) because a number can be connected with all other nodes other than itself +6. Adding a vertex: we just have to pushback a new node to the vector so O(1). +7. Removing a vertex: So here first of all we need all the edges of that vertex to be removed so that would be + O(E) then we need to remove that vertex from the main vector and it would be O(V) so total would be O(V+E); + +Adjacency Matrix +1. This takes upto v^2 size. +2. Finding if there is a edge between two vertices is O(1). +3. Finding degree would be O(V). +4. Adding an edge: O(1) as we have to make mat[i][j] = 1. +5. Removing an Edge: O(1) as we have to make mat[i][j] = 0. +6. Adding a vertex: It will take O(v^2); +7. Removing a vertex: It will take O(v^2); + + +*/ \ No newline at end of file diff --git a/graph/code4.cpp b/graph/code4.cpp new file mode 100644 index 00000000..992da32e --- /dev/null +++ b/graph/code4.cpp @@ -0,0 +1,68 @@ +// Breadth first search +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +void bfs(vector vec[], int v, int source, vector &visited) +{ + queue q; + q.push(source); + visited[source] = true; + + while (q.empty() == false) + { + int curr = q.front(); + q.pop(); + + cout << curr << " "; + for (int i = 0; i < vec[curr].size(); i++) + { + int adjacent = vec[curr][i]; + if (visited[adjacent] == false) + { + q.push(adjacent); + visited[adjacent] = true; + } + } + } +} + +void bfs_recursive(vector vec[], int v) +{ + vector visited(v, false); + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + bfs(vec, v, i, visited); + } + } +} + +int main() +{ + int v; + v = 6; + vector adj[v]; + + // Adding edges from this point + add_edge(adj, 0, 1); + add_edge(adj, 0, 2); + add_edge(adj, 0, 3); + add_edge(adj, 1, 5); + add_edge(adj, 2, 5); + add_edge(adj, 1, 4); + + cout << "Breadth First Search is: " << endl; + + bfs_recursive(adj, v); + + return 0; +} \ No newline at end of file diff --git a/graph/code5.cpp b/graph/code5.cpp new file mode 100644 index 00000000..ab87c13b --- /dev/null +++ b/graph/code5.cpp @@ -0,0 +1,57 @@ +// Depth First search +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +void dfs(vector vec[], int source, vector &visited) +{ + visited[source] = true; + cout << source << " "; + for (int i = 0; i < vec[source].size(); i++) + { + int adjacent = vec[source][i]; + if (visited[adjacent] == false) + { + dfs(vec, adjacent, visited); + } + } +} + +void dfs_rec(vector vec[], int v) +{ + vector visited(v, false); + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + dfs(vec, i, visited); + } + } +} + +int main() +{ + int v; + v = 6; + vector adj[v]; + + // adding edges now + add_edge(adj, 0, 1); + add_edge(adj, 0, 2); + add_edge(adj, 0, 3); + add_edge(adj, 1, 4); + add_edge(adj, 1, 5); + add_edge(adj, 2, 5); + + cout << "DEPTH FIRST SEARCH: " << endl; + + dfs_rec(adj, v); + return 0; +} \ No newline at end of file diff --git a/graph/code6.cpp b/graph/code6.cpp new file mode 100644 index 00000000..76fc92be --- /dev/null +++ b/graph/code6.cpp @@ -0,0 +1,67 @@ +// Shortest Path in Unweighted Graph +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +void find_sd(vector vec[], int v, int source) +{ + vector visited(v, false); + vector dist(v, INT_MAX); + + queue q; + q.push(source); + dist[source] = 0; + visited[source] = true; + + while (q.empty() == false) + { + int curr = q.front(); + q.pop(); + // cout<<"curr: "< adj[v]; + + // adding edge to graph + add_edge(adj, 0, 1); + add_edge(adj, 0, 2); + add_edge(adj, 0, 3); + add_edge(adj, 1, 4); + add_edge(adj, 1, 5); + add_edge(adj, 2, 5); + + // finding shortes distance + int source = 0; + find_sd(adj, v, source); + return 0; +} \ No newline at end of file diff --git a/graph/code7.cpp b/graph/code7.cpp new file mode 100644 index 00000000..81470a19 --- /dev/null +++ b/graph/code7.cpp @@ -0,0 +1,84 @@ +// Detect cycle in undirected graph with BFS +// so in undirected graphs mainly we find who is the parent and if found some adjacent whose adjacent +// is visited and also is not is not its parent the we can surely say that we have a cycle. +// In case of BFS we make parent array and thats how we check parent.. +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +bool bfs_find(vector vec[], vector &visited, vector &parent, int source) +{ + queue q; + q.push(source); + visited[source] = true; + while (q.empty() == false) + { + int curr = q.front(); + q.pop(); + for (int i = 0; i < vec[curr].size(); i++) + { + int adjacent = vec[curr][i]; + if (visited[adjacent] == false) + { + visited[adjacent] = true; + q.push(adjacent); + parent[adjacent] = curr; + } + else if (visited[adjacent] == true && parent[curr] != adjacent) + { + return true; + } + } + } + return false; +} + +bool bfs_rec(vector vec[], int v) +{ + vector visited(v, false); + vector parent(v, -1); + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + if (bfs_find(vec, visited, parent, i) == true) + { + return true; + } + } + } + return false; +} + +int main() +{ + int v; + v = 6; + vector adj[v]; + + // adding edges now + add_edge(adj, 0, 1); + add_edge(adj, 0, 2); + add_edge(adj, 0, 3); + add_edge(adj, 1, 4); + add_edge(adj, 1, 5); + add_edge(adj, 2, 5); + + // find if it has a loop or not + if (bfs_rec(adj, v)) + { + cout << "It has a loop !!" << endl; + } + else + { + cout << "It doesnt have a loop!!" << endl; + } + return 0; +} \ No newline at end of file diff --git a/graph/code8.cpp b/graph/code8.cpp new file mode 100644 index 00000000..7178fb4c --- /dev/null +++ b/graph/code8.cpp @@ -0,0 +1,79 @@ +// Detect cycle in undirected graph --> DFS +// when we want to detect cycle in a undirected graph then should check what will be its parent and if one of its adjacent is +// already and not its parent then we conclude that there exists a cycle in the graph... +// in DfS the parent will se stored in recursion itself unlike BFS where we store it in array/vector and check it.. + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); + vec[v].push_back(u); +} + +bool dfs(vector vec[], vector &visited, int parent, int source) +{ + visited[source] = true; + for (int i = 0; i < vec[source].size(); i++) + { + int adjacent = vec[source][i]; + if (visited[adjacent] == false) + { + if (dfs(vec, visited, source, adjacent) == true) + { + return true; + } + } + else if (visited[adjacent] == true && parent != adjacent) + { + return true; + } + } + return false; +} + +bool dfs_rec(vector vec[], int v) +{ + vector visited(v, false); + int parent = -1; + for (int i = 0; i < v; i++) + { + if (visited[i] == false) + { + if (dfs(vec, visited, parent, i) == true) + { + return true; + } + } + } + return false; +} + +int main() +{ + int v; + v = 6; + vector adj[v]; + + // adding edges now + add_edge(adj, 0, 1); + add_edge(adj, 0, 2); + add_edge(adj, 0, 3); + add_edge(adj, 1, 4); + add_edge(adj, 1, 5); + add_edge(adj, 2, 5); + + if (dfs_rec(adj, v)) + { + cout << "It contains an cycle!!" << endl; + } + else + { + cout << "It doesnt contain an cycle!!" << endl; + } + + return 0; +} \ No newline at end of file diff --git a/graph/code9.cpp b/graph/code9.cpp new file mode 100644 index 00000000..b38c1a59 --- /dev/null +++ b/graph/code9.cpp @@ -0,0 +1,79 @@ +// Detect cycle in a directed graph using BFS +// here we will use topo_sort in topo sort we reduce indegrees but in cycle.. for all the vertex in +// the cycle the indegree will never be zero ... we can find out from there + +#include +using namespace std; +#define ll long long +const int inf = 1e9 + 7; + +void add_edge(vector vec[], int u, int v) +{ + vec[u].push_back(v); +} + +bool topo_sort(vector vec[], int v) +{ + vector indegree(v, 0); + for (int i = 0; i < v; i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + int adjacent = vec[i][j]; + indegree[adjacent]++; + } + } + queue q; + for (int i = 0; i < indegree.size(); i++) + { + if (indegree[i] == 0) + { + q.push(i); + } + } + int count = 0; + while (q.empty() == false) + { + int curr = q.front(); + q.pop(); + + count++; + for (int i = 0; i < vec[curr].size(); i++) + { + int adjacent = vec[curr][i]; + + indegree[adjacent]--; + if (indegree[adjacent] == 0) + { + q.push(adjacent); + } + } + } + return count == v; +} + +int main() +{ + int v; + v = 5; + vector vec[v]; + + // adding edges from this point + add_edge(vec, 0, 1); + add_edge(vec, 0, 3); + add_edge(vec, 1, 2); + add_edge(vec, 2, 4); + add_edge(vec, 3, 1); + add_edge(vec, 4, 3); + + if (topo_sort(vec, v)) + { + cout << "No cycle " << endl; + } + else + { + cout << "there is a cycle" << endl; + } + + return 0; +} \ No newline at end of file diff --git a/graph/cycleDetectionInDirectedGraph.java b/graph/cycleDetectionInDirectedGraph.java new file mode 100644 index 00000000..1b97335f --- /dev/null +++ b/graph/cycleDetectionInDirectedGraph.java @@ -0,0 +1,31 @@ +import java.util.ArrayList; + + +// check whether the graph is DAG, directed acyclic(without cycles) graph +public class cycleDetectionInDirectedGraph { + private boolean checkCycle(int node, ArrayList> adj, int[] visited, int dfsVisited[]) { + visited[node] = 1; + dfsVisited[node] = 1; + for (Integer child : adj.get(node)) { + if (visited[child] == 0) { + if (checkCycle(child, adj, visited, dfsVisited)) + return true; + } else if (dfsVisited[child] == 1) + return true; + } + return false; + } + + public boolean isCyclic(int N, ArrayList> adjlist, int n) { + int visited[] = new int[N]; + int dfsVisited[] = new int[N]; + for (int i = 0; i < n; i++) { + if (visited[i] == 0) { + if (checkCycle(i, adjlist, visited, dfsVisited) == true) { + return true; + } + } + } + return false; + } +} diff --git a/graph/cycledetectionInUndirectedGraph.java b/graph/cycledetectionInUndirectedGraph.java new file mode 100644 index 00000000..eb25613a --- /dev/null +++ b/graph/cycledetectionInUndirectedGraph.java @@ -0,0 +1,66 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; + +// CORE: if children is already visited and +// is not the parent of the node then there isa cycle +public class cycledetectionInUndirectedGraph { + private boolean isCycle(int V, ArrayList> adj) { + boolean[] visited = new boolean[V + 1]; + Arrays.fill(visited, false); + for (int i = 1; i <= V; i++) { + if (!visited[i]) { + if (checkForCycle(adj, i, visited)) + return true; + } + } + return false; + } + + static boolean checkForCycle(ArrayList> adj, int s, boolean visited[]) { + Queue q = new LinkedList<>(); // bfs queue + q.add(new Node(s, -1)); // add source node parent of start Node is -1 <-- 0 + visited[s] = true; + while (!q.isEmpty()) { + int node = q.peek().self; + int parent = q.peek().Parent; + q.remove(); + for (Integer child : adj.get(node)) { + if (!visited[child]) { + q.add(new Node(child, node)); + visited[child] = true; + } else if (child != parent) { // child is visited and is not parent, then cycle + return true; + } + } + } + return false; + + } + + // driver code + public static void main(String[] args) { + ArrayList> adj = new ArrayList<>(); + adj.add(new ArrayList<>(Arrays.asList(1, 2))); + adj.add(new ArrayList<>(Arrays.asList(2, 3))); + adj.add(new ArrayList<>(Arrays.asList(3, 4))); + // adj.add(new ArrayList<>(Arrays.asList(4, 5))); + cycledetectionInUndirectedGraph obj = new cycledetectionInUndirectedGraph(); + System.out.println(obj.isCycle(4, adj)); + } +} + +class Node { + int self; + int Parent; + + public Node(int self, int Parent) { + this.self = self; + this.Parent = Parent; + } +} + +class cycleDetectionUsingDSU{ + +} \ No newline at end of file diff --git a/graph/readme.txt b/graph/readme.txt new file mode 100644 index 00000000..7024d0b0 --- /dev/null +++ b/graph/readme.txt @@ -0,0 +1,20 @@ +1. Adjacency Matrix +2. Adjacency List +3. Comparison in adjaceny matrix and adaceny list +4. Breadth First Search +5. Depth First Search +6. Shortest Path in Unweighted Graph +7. Detect Cycle in Undirected Graph --- BFS +8. Detect Cycle in Undirected Graph --- DFS +9. Detect Cycle in Directed Graph --- BFS +10. Detect Cycle in Directed Graph --- DFS +11. Topological Sort --- BFS Kahn's Based Algorithm +12. Topological Sort --- DFS +13. Shortest Path in DAG (Weighted) +14. Minimum spanning tree (Prims algorithm) +15. Minimum spanning tree (Kruskal algorithm) +16. Shortest path algorithm (Dijstra's algorithm) +17. shortest path algorithm (Bellman Ford algorithm) (works with negative weights) +18. Strongly connected components (Kosaraju's algorithm) +20. Articulation Point +21. Bridges in graph \ No newline at end of file diff --git a/knapsack.class b/knapsack.class new file mode 100644 index 00000000..774891ea Binary files /dev/null and b/knapsack.class differ diff --git a/knapsack.java b/knapsack.java new file mode 100644 index 00000000..6dc157ee --- /dev/null +++ b/knapsack.java @@ -0,0 +1,37 @@ +//Ankita Patil + +class knapsack { + int knap(int[] wt, int[] val, int W, int n) { + int[][] M = new int[n + 1][W + 1]; + for (int i = 0; i <= n; i++) { + for (int w = 0; w <= W; w++) { + if (w == 0 || i == 0) + M[i][w] = 0; + else if (wt[i - 1] > w) + M[i][w] = M[i - 1][w]; + else + M[i][w] = Math.max(M[i - 1][w], val[i - 1] + M[i - 1][w - wt[i - 1]]); + } + } + int i = n, k = W; + while (i > 0 && k > 0) { + if (M[i][k] != M[i - 1][k]) { + System.out.println(i); + i = i - 1; + k = k - wt[i]; + } else + i = i - 1; + } + return M[n][W]; + } + + public static void main(String[] args) { + int[] val = new int[] { 10, 4, 9, 11 }; + int[] wt = new int[] { 3, 5, 6, 2 }; + int W = 7; + int n = val.length; + knapsack ob = new knapsack(); + System.out.println("Maximum value in Knapsack: " + ob.knap(wt, val, W, n)); + } + +} \ No newline at end of file diff --git a/left view of tree.cpp b/left view of tree.cpp new file mode 100644 index 00000000..8d5d889e --- /dev/null +++ b/left view of tree.cpp @@ -0,0 +1,61 @@ +// C++ program to print left view of Binary Tree +#include +using namespace std; + +struct Node +{ + int data; + struct Node *left, *right; +}; + + +struct Node *newNode(int item) +{ + struct Node *temp = (struct Node *)malloc( + sizeof(struct Node)); + temp->data = item; + temp->left = temp->right = NULL; + return temp; +} + +// left view of a binary tree. +void leftViewUtil(struct Node *root, + int level, int *max_level) +{ + + if (root == NULL) return; + + + if (*max_level < level) + { + cout << root->data << " "; + *max_level = level; + } + + leftViewUtil(root->left, level + 1, max_level); + leftViewUtil(root->right, level + 1, max_level); + +} + + +void leftView(struct Node *root) +{ + int max_level = 0; + leftViewUtil(root, 1, &max_level); +} + +int main() +{ + Node* root = newNode(10); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(7); + root->left->right = newNode(8); + root->right->right = newNode(15); + root->right->left = newNode(12); + root->right->right->left = newNode(14); + + leftView(root); + + return 0; +} diff --git a/linked_list/.java b/linked_list/.java new file mode 100644 index 00000000..a9416002 --- /dev/null +++ b/linked_list/.java @@ -0,0 +1,71 @@ +// CREATION AND INSERTION + +import java.io.*; +public class LinkedList { + Node head; + + static class Node { + + int data; + Node next; + + // Constructor + Node(int d) + { + data = d; + next = null; + } + } + + public static LinkedList insert(LinkedList list, int data) + { + Node new_node = new Node(data); + + if (list.head == null) { + list.head = new_node; + } + else { + + Node last = list.head; + while (last.next != null) { + last = last.next; + } + + last.next = new_node; + } + + return list; + } + + public static void printList(LinkedList list) + { + Node currNode = list.head; + + System.out.print("LinkedList: "); + + while (currNode != null) { + + System.out.print(currNode.data + " "); + + currNode = currNode.next; + } + } + + public static void main(String[] args) + { + + LinkedList list = new LinkedList(); + + + list = insert(list, 0); + list = insert(list, 9); + list = insert(list, 8); + list = insert(list, 7); + list = insert(list, 6); + list = insert(list, 5); + list = insert(list, 4); + list = insert(list, 3); + + printList(list); + } +}