> vec2d) {
+ if (vec2d == null) {
+ return;
+ }
+ this.x = 0;
+ this.y = 0;
+ this.list = vec2d;
+ }
+
+ public int next() {
+ int rst = list.get(x).get(y);
+ // when y(column) reaches end increment row(x) and reset y
+ if (y + 1 >= list.get(x).size()) {
+ y = 0;
+ x++;
+ } else {
+ y++;
+ }
+ return rst;
+ }
+
+ public boolean hasNext() {
+ if (list == null) {
+ return false;
+ }
+ // this condition is to check for empty rows
+ while (x < list.size() && list.get(x).size() == 0) {
+ x++;
+ y = 0;
+ }
+ if (x >= list.size()) {
+ return false;
+ }
+ if (y >= list.get(x).size()) {
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/src/geeksforgeeks/FlattenLinkedList.java b/src/geeksforgeeks/FlattenLinkedList.java
index 1e2e95c..9fbbcbe 100644
--- a/src/geeksforgeeks/FlattenLinkedList.java
+++ b/src/geeksforgeeks/FlattenLinkedList.java
@@ -1,5 +1,8 @@
package geeksforgeeks;
+/**
+ * https://www.techiedelight.com/flatten-linked-list/
+ */
class FlattenLinkedList {
Node head;
@@ -19,7 +22,6 @@ public String toString() {
}
}
-
Node mergeIterative(Node a, Node b) {
Node dummy = new Node(0);
Node result = dummy;
@@ -49,8 +51,9 @@ Node mergeIterative(Node a, Node b) {
}
Node flatten(Node root) {
- if (root == null || root.right == null)
+ if (root == null || root.right == null) {
return root;
+ }
root.right = flatten(root.right);
@@ -59,7 +62,6 @@ Node flatten(Node root) {
return root;
}
-
public static void main(String args[]) {
flattenList();
}
@@ -120,9 +122,13 @@ void printList() {
}
Node merge(Node a, Node b) {
- if (a == null) return b;
+ if (a == null) {
+ return b;
+ }
- if (b == null) return a;
+ if (b == null) {
+ return a;
+ }
Node result;
diff --git a/src/geeksforgeeks/FlattenMultiLevelLinkedList.java b/src/geeksforgeeks/FlattenMultiLevelLinkedList.java
index f054faa..f1db59b 100644
--- a/src/geeksforgeeks/FlattenMultiLevelLinkedList.java
+++ b/src/geeksforgeeks/FlattenMultiLevelLinkedList.java
@@ -4,7 +4,9 @@
class FlattenMultiLevelLinkedList {
public Node flatten(Node head) {
- if (head == null) return head;
+ if (head == null) {
+ return head;
+ }
// Pointer
Node p = head;
while (p != null) {
@@ -19,7 +21,9 @@ public Node flatten(Node head) {
temp = temp.next;
// Connect tail with p.next, if it is not null
temp.next = p.next;
- if (p.next != null) p.next.prev = temp;
+ if (p.next != null) {
+ p.next.prev = temp;
+ }
// Connect p with p.child, and remove p.child
p.next = p.child;
p.child.prev = p;
diff --git a/src/geeksforgeeks/FlipMaximizeZeroesSubarrayKadane.java b/src/geeksforgeeks/FlipMaximizeZeroesSubarrayKadane.java
index 1f10903..115d9b2 100644
--- a/src/geeksforgeeks/FlipMaximizeZeroesSubarrayKadane.java
+++ b/src/geeksforgeeks/FlipMaximizeZeroesSubarrayKadane.java
@@ -2,23 +2,30 @@
/**
* https://www.geeksforgeeks.org/maximize-number-0s-flipping-subarray/
+ *
+ * Problem : flip 1's to 0's so that total no.of 0's in array is maximized
*/
class FlipMaximizeZeroesSubarrayKadane {
public static int findMaxZeroCount(int arr[], int n) {
int zeroCount = 0;
- int maxSoFar = 0;
- int maxEndingHere = 0;
+ int maxSoFar = Integer.MIN_VALUE;
+ int sum = 0;
for (int i = 0; i < n; i++) {
- if (arr[i] == 0)
+ if (arr[i] == 0) {
zeroCount++;
+ }
int val = (arr[i] == 1) ? 1 : -1;
- maxEndingHere = Math.max(val, maxEndingHere + val);
- maxSoFar = Math.max(maxSoFar, maxEndingHere);
+ sum = sum + val;
+
+ if (sum < 0) {
+ sum = 0;
+ }
+ maxSoFar = Math.max(maxSoFar, sum);
}
maxSoFar = Math.max(0, maxSoFar);
@@ -26,7 +33,7 @@ public static int findMaxZeroCount(int arr[], int n) {
}
public static void main(String[] args) {
- int arr[] = {0, 1, 0, 0, 1, 1, 0};
+ int arr[] = { 0, 1, 0, 0, 1, 1, 0 };
System.out.println(findMaxZeroCount(arr, arr.length));
}
diff --git a/src/geeksforgeeks/FlipZeroesToFormConsecutiveMaximumOnes.java b/src/geeksforgeeks/FlipZeroesToFormConsecutiveMaximumOnes.java
index 535afdb..66590b7 100644
--- a/src/geeksforgeeks/FlipZeroesToFormConsecutiveMaximumOnes.java
+++ b/src/geeksforgeeks/FlipZeroesToFormConsecutiveMaximumOnes.java
@@ -30,7 +30,6 @@ public static void longestSeq(int[] A, int k) {
if (A[left] == 0) {
count--;
}
-
left++;
}
@@ -43,13 +42,14 @@ public static void longestSeq(int[] A, int k) {
}
}
- System.out.println("The longest sequence has length " + window + " from index " + leftIndex + " to "
- + (leftIndex + window - 1));
+ System.out.println(
+ "The longest sequence has length " + window + " from index " + leftIndex + " to " + (leftIndex + window
+ - 1));
}
// main function
public static void main(String[] args) {
- int[] A = {1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0};
+ int[] A = { 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0 };
int k = 1;
longestSeq(A, k);
diff --git a/src/geeksforgeeks/FourSum.java b/src/geeksforgeeks/FourSum.java
new file mode 100644
index 0000000..96a925c
--- /dev/null
+++ b/src/geeksforgeeks/FourSum.java
@@ -0,0 +1,41 @@
+package geeksforgeeks;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * https://leetcode.com/problems/4sum-ii/
+ */
+public class FourSum {
+
+ public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
+ Map sums = new HashMap<>();
+ int count = 0;
+ for (int i = 0; i < A.length; i++) {
+ for (int j = 0; j < B.length; j++) {
+ int sum = A[i] + B[j];
+ sums.put(sum, sums.getOrDefault(sum, 0) + 1);
+
+ }
+ }
+ for (int k = 0; k < A.length; k++) {
+ for (int z = 0; z < C.length; z++) {
+ int sum = -(C[k] + D[z]);
+ if (sums.containsKey(sum)) {
+ count += sums.get(sum);
+ }
+ }
+ }
+ return count;
+ }
+
+ public static void main(String[] args) {
+ int[] A = { 1, 2 };
+ int[] B = { -2, -1 };
+ int[] C = { -1, 2 };
+ int[] D = { 0, 2 };
+
+ FourSum fs = new FourSum();
+ fs.fourSumCount(A, B, C, D);
+ }
+}
diff --git a/src/geeksforgeeks/FrequencySort.java b/src/geeksforgeeks/FrequencySort.java
new file mode 100644
index 0000000..a01d6cc
--- /dev/null
+++ b/src/geeksforgeeks/FrequencySort.java
@@ -0,0 +1,34 @@
+package geeksforgeeks;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+// sort the string by character frequency from high to low
+public class FrequencySort {
+ // this could be easily done with priority queue but this is ref for bucket sort
+ public String frequencySort(String s) {
+ Map map = new HashMap<>();
+ for (char c : s.toCharArray())
+ map.put(c, map.getOrDefault(c, 0) + 1);
+
+ List[] bucket = new List[s.length() + 1];
+
+ for (char key : map.keySet()) {
+ int frequency = map.get(key);
+ if (bucket[frequency] == null) bucket[frequency] = new ArrayList<>();
+ bucket[frequency].add(key);
+ }
+
+ StringBuilder sb = new StringBuilder();
+ // since this is max frequency are iterating from last else we'd go from start
+ for (int pos = bucket.length - 1; pos >= 0; pos--)
+ if (bucket[pos] != null)
+ for (char c : bucket[pos])
+ for (int i = 0; i < map.get(c); i++)
+ sb.append(c);
+
+ return sb.toString();
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/GameOfLife.java b/src/geeksforgeeks/GameOfLife.java
new file mode 100644
index 0000000..d2b6069
--- /dev/null
+++ b/src/geeksforgeeks/GameOfLife.java
@@ -0,0 +1,61 @@
+package geeksforgeeks;
+
+/**
+ * https://forum.letstalkalgorithms.com/t/game-of-life/516/2
+ *
+ * https://leetcode.com/problems/game-of-life/
+ * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
+ *
+ * Any live cell with fewer than two live neighbors dies, as if caused by under-population.
+ * Any live cell with two or three live neighbors lives on to the next generation.
+ * Any live cell with more than three live neighbors dies, as if by over-population..
+ * Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
+ *
+ * Input:
+ * [
+ * [0,1,0],
+ * [0,0,1],
+ * [1,1,1],
+ * [0,0,0]
+ * ]
+ * Output:
+ * [
+ * [0,0,0],
+ * [1,0,1],
+ * [0,1,1],
+ * [0,1,0]
+ * ]
+ */
+public class GameOfLife {
+
+ public void gameOfLife(int[][] board) {
+
+ int[][] dir ={{1,-1},{1,0},{1,1},{0,-1},{0,1},{-1,-1},{-1,0},{-1,1}};
+ int row=board.length;
+ int col=board[0].length;
+
+ for(int i=0; i=row || j1>=col || i1<0 || j1<0) continue; // border conditions
+
+ if(board[i1][j1]==1 || board[i1][j1]==2) liveCells++;
+ }
+
+ if(board[i][j]==0 && liveCells==3) board[i][j]=3; //Any dead cell with exactly three live neighbors becomes a live cell
+
+ if(board[i][j]==1 && (liveCells<2 || liveCells>3)) board[i][j]=2; //live cell with fewer than two live neighbors dies || Any live cell with more than three live neighbors dies
+ }
+ }
+
+ for(int i=0; i generateParenthesis(int n) {
+ List result = new ArrayList<>();
+ if (n == 0)
+ return result;
+ // initially we send empty string and target number of pairs needed
+ generateUtil(n, new StringBuilder(), 0, 0, result);
+
+ return result;
+ }
+
+ public void generateUtil(int n, StringBuilder paran, int open, int close, List result) {
+ if (close == n) { // when close reaches n, we know n pairs have been created
+ result.add(paran.toString());
+ return;
+ }
+
+ if (close < open) { // when close is less than open we add a close and proceed
+ paran.append(")");
+ generateUtil(n, paran, open, close + 1, result);
+ paran.deleteCharAt(paran.length() - 1); // backtracking to remove the last seen
+ }
+ if (open < n) {
+ paran.append("(");
+ generateUtil(n, paran, open + 1, close, result);
+ paran.deleteCharAt(paran.length() - 1);
+
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/GrammarMistake.java b/src/geeksforgeeks/GrammarMistake.java
new file mode 100644
index 0000000..134fb1f
--- /dev/null
+++ b/src/geeksforgeeks/GrammarMistake.java
@@ -0,0 +1,83 @@
+package geeksforgeeks;
+
+/**
+ * https://www.geeksforgeeks.org/check-given-sentence-given-set-simple-grammer-rules/
+ * A simple sentence if syntactically correct if it fulfills given rules. The following are given rules.
+ *
+ * 1. Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.)
+ * 2. Then lowercase character follows.
+ * 3. There must be spaces between words.
+ * 4. Then the sentence must end with a full stop(.) after a word.
+ * 5. Two continuous spaces are not allowed.
+ * 6. Two continuous upper case characters are not allowed.
+ * 7. However, the sentence can end after an upper case character.
+ *
+ *
+ */
+import java.util.Arrays;
+import java.util.List;
+
+class Main
+{
+ public static boolean validateSentence(char[] chars)
+ {
+ int index = 0;
+ if (Character.isLowerCase(chars[index])) { // 1st condition
+ return false;
+ }
+
+ while (index < chars.length)
+ {
+ if (Character.isUpperCase(chars[index]))
+ {
+ if (Character.isUpperCase(chars[index + 1])) { // 5th condition
+ return false;
+ }
+
+ if (index - 1 >= 0 && chars[index - 1] != ' ') { // 2nd condition
+ return false;
+ }
+ }
+
+ if (chars[index] == ' ' && chars[index + 1] == ' ') { // 4th condition
+ return false;
+ }
+
+ index++;
+ }
+
+ if (chars[index - 2] == ' ' || chars[index - 1] != '.') { // 3th condition
+ return false;
+ }
+
+ return true;
+ }
+
+ public static void main(String[] args)
+ {
+ List list = Arrays.asList(
+ "This sentence is syntactically correct.",
+
+ "This sentence is syntactically incorrect as two " +
+ "continuous spaces are not allowed.",
+
+ "This sentence is syntactically correct Y.",
+
+ "This sentence is syntactically incorRect as uppercase " +
+ "character is not allowed midway of the String.",
+
+ "THis sentence is syntactically incorrect as lowercase " +
+ "character don't follow the first uppercase character.",
+
+ "This sentence is syntactically incorrect as it doesn't " +
+ "end with a full stop"
+ );
+
+ System.out.println("Valid sentences are -");
+ for (String sentence: list) {
+ if (validateSentence(sentence.toCharArray())) {
+ System.out.println(sentence);
+ }
+ }
+ }
+}
diff --git a/src/geeksforgeeks/GraphBiPartite.java b/src/geeksforgeeks/GraphBiPartite.java
new file mode 100644
index 0000000..27da2f5
--- /dev/null
+++ b/src/geeksforgeeks/GraphBiPartite.java
@@ -0,0 +1,53 @@
+package geeksforgeeks;
+
+/**
+ * Recall that a graph is bipartite if we can split it's set of nodes into
+ * two independent subsets A and B such that every edge in the graph has one node in A and
+ * another node in B.
+ * Input: [[1,3], [0,2], [1,3], [0,2]] => 0th node connects to 1,3 ..
+Output: true
+Explanation:
+The graph looks like this:
+0----1
+| |
+| |
+3----2
+We can divide the vertices into two groups: {0, 2} and {1, 3}.
+Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
+Output: false
+Explanation:
+The graph looks like this:
+0----1
+| \ |
+| \ |
+3----2
+We cannot find a way to divide the set of nodes into two independent subsets.
+ */
+public class GraphBiPartite {
+ public boolean isBipartite(int[][] graph) {
+ int[] color= new int[graph.length];
+
+ for(int i=0;i> groupAnagrams(String[] strs) {
+ List> result= new ArrayList<>();
+
+ if(strs==null || strs.length==0) return result;
+ Map> map= new HashMap<>();
+
+ for(String s: strs){
+ // int[] cache= new int[26];
+ // for(char ch: s.toCharArray()){
+ // cache[ch-'a']++;
+ // }
+ // String hash=Arrays.toString(cache);
+ char[] te=s.toCharArray();
+ Arrays.sort(te);
+ String hash=new String(te);
+
+ List list= map.getOrDefault(hash, new LinkedList<>());
+ list.add(s);
+ map.put(hash,list);
+ }
+
+ return new ArrayList(map.values());
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/HappyNumber.java b/src/geeksforgeeks/HappyNumber.java
new file mode 100644
index 0000000..a8ff875
--- /dev/null
+++ b/src/geeksforgeeks/HappyNumber.java
@@ -0,0 +1,56 @@
+package geeksforgeeks;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * https://leetcode.com/problems/happy-number/
+ */
+class HappyNumber {
+ public boolean isHappy(int n) {
+
+ Set visited = new HashSet<>();
+ int sum = String.valueOf(n).chars().map(Character::getNumericValue).map(val -> val * val).sum() == 1 ? 1 : n;
+ while (true) {
+ if (sum == 1) {
+ return true;
+ }
+ sum = String.valueOf(sum).chars().map(Character::getNumericValue).map(val -> val * val).sum();
+ if (visited.contains(sum)) {
+ return false;
+ }
+
+ visited.add(sum);
+ }
+ }
+
+ public int next(int n)
+ {
+ int res=0;
+ while (n>0)
+ {
+ int t = n % 10;
+ res += t*t;
+ n/=10;
+ }
+ return res;
+ }
+
+ public boolean isHappyOpt(int n)
+ {
+ int i1=n, i2=next(n);
+
+ while ( i2 != i1)
+ {
+ i1 = next(i1);
+ i2 = next(next(i2));
+ }
+
+ return i1==1;
+ }
+
+ public static void main(String[] args) {
+ HappyNumber hn = new HappyNumber();
+ System.out.println(hn.isHappy(19));
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/HitCounter.java b/src/geeksforgeeks/HitCounter.java
new file mode 100644
index 0000000..77d6368
--- /dev/null
+++ b/src/geeksforgeeks/HitCounter.java
@@ -0,0 +1,24 @@
+package geeksforgeeks;
+public class HitCounter {
+ ArrayDeque trac;
+ /** Initialize your data structure here. */
+ private final int FIVE_MINUTES = 300;
+ public HitCounter() {
+ trac = new ArrayDeque();
+ }
+
+ /** Record a hit.
+ @param timestamp - The current timestamp (in seconds granularity). */
+ public void hit(int timestamp) {
+ trac.addLast(timestamp);
+ }
+
+ /** Return the number of hits in the past 5 minutes.
+ @param timestamp - The current timestamp (in seconds granularity). */
+ public int getHits(int timestamp) {
+ while(trac.size() > 0 && ( int) trac.getFirst() + FIVE_MINUTES <= timestamp) {
+ trac.removeFirst();
+ } return trac.size();
+ }
+
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/HouseRobber.java b/src/geeksforgeeks/HouseRobber.java
new file mode 100644
index 0000000..b860ad0
--- /dev/null
+++ b/src/geeksforgeeks/HouseRobber.java
@@ -0,0 +1,46 @@
+package geeksforgeeks;
+
+/**
+ * https://leetcode.com/problems/house-robber/
+ */
+public class HouseRobber {
+
+ public int rob(int[] nums) {
+ if (nums.length == 0) {
+ return 0;
+ }
+ int incl = nums[0];
+ int excl = 0;
+ for (int i = 1; i < nums.length; i++) {
+ int temp = incl;
+ incl = Math.max(incl, excl + nums[i]);
+ excl = temp;
+ }
+ return incl;
+ }
+
+ public int robCircular(int[] nums) {
+
+ if(nums.length==0) return 0;
+ if(nums.length==1) return nums[0];
+ return Math.max(helperFn(nums,0,nums.length-2), helperFn(nums,1,nums.length-1));
+
+ }
+
+ public int helperFn(int[] nums, int start, int end){
+ int pre=0; int cur=0;
+ for(int i=start;i<=end;i++){
+ int temp=Math.max(pre+nums[i],cur);
+ pre=cur;
+ cur=temp;
+
+ }
+ return cur;
+ }
+
+ public static void main(String[] args) {
+ int[] arr = { 2, 7, 9, 3, 1 };
+ HouseRobber houseRobber = new HouseRobber();
+ System.out.println(houseRobber.rob(arr));
+ }
+}
diff --git a/src/geeksforgeeks/IPOMaxProfit.java b/src/geeksforgeeks/IPOMaxProfit.java
new file mode 100644
index 0000000..5338d09
--- /dev/null
+++ b/src/geeksforgeeks/IPOMaxProfit.java
@@ -0,0 +1,46 @@
+package geeksforgeeks;
+
+
+
+import java.util.PriorityQueue;
+//https://leetcode.com/problems/ipo/
+
+// Input: distinctProjToFind=2, capital=0, Profits=[1,2,3], Capital=[0,1,1].
+// Output: 4
+
+// Explanation: Since your initial capital is 0, you can only start the project indexed 0.
+// After finishing it you will obtain profit 1 and your capital becomes 1.
+// With capital 1, you can either start the project indexed 1 or the project indexed 2.
+// Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
+// Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
+public class IPOMaxProfit {
+
+ // Create (capital, profit) pairs and put them into PriorityQueue pqCap.
+ // This PriorityQueue sort by capital increasingly.
+ // Keep polling pairs from pqCap until the project out of current capital capability. Put them into
+ // PriorityQueue pqPro which sort by profit decreasingly.
+ // Poll one from pqPro, it's guaranteed to be the project with max profit and within current capital capability.
+ //Add the profit to capital W.
+ //Repeat step 2 and 3 till finish k steps or no suitable project (pqPro.isEmpty()).
+ public int findMaximizedCapital(int steps, int initialCapital, int[] Profits, int[] Capital) {
+
+ PriorityQueue minQueue= new PriorityQueue<>((a, b)->Integer.compare(a[0],b[0]));
+ PriorityQueue maxQueue= new PriorityQueue<>((a,b)->Integer.compare(b[1],a[1]));
+
+ for(int i=0;i dirs = new HashMap < > ();
+ HashMap < String, String > files = new HashMap < > ();
+ }
+ Dir root;
+ public FileSystem() {
+ root = new Dir();
+ }
+ public List < String > ls(String path) {
+ Dir t = root;
+ List < String > files = new ArrayList < > ();
+ if (!path.equals("/")) {
+ String[] d = path.split("/");
+ for (int i = 1; i < d.length - 1; i++) {
+ t = t.dirs.get(d[i]);
+ }
+ if (t.files.containsKey(d[d.length - 1])) {
+ files.add(d[d.length - 1]);
+ return files;
+ } else {
+ t = t.dirs.get(d[d.length - 1]);
+ }
+ }
+ files.addAll(new ArrayList < > (t.dirs.keySet()));
+ files.addAll(new ArrayList < > (t.files.keySet()));
+ Collections.sort(files);
+ return files;
+ }
+
+ public void mkdir(String path) {
+ Dir t = root;
+ String[] d = path.split("/");
+ for (int i = 1; i < d.length; i++) {
+ if (!t.dirs.containsKey(d[i]))
+ t.dirs.put(d[i], new Dir());
+ t = t.dirs.get(d[i]);
+ }
+ }
+
+ public void addContentToFile(String filePath, String content) {
+ Dir t = root;
+ String[] d = filePath.split("/");
+ for (int i = 1; i < d.length - 1; i++) {
+ t = t.dirs.get(d[i]);
+ }
+ t.files.put(d[d.length - 1], t.files.getOrDefault(d[d.length - 1], "") + content);
+ }
+
+ public String readContentFromFile(String filePath) {
+ Dir t = root;
+ String[] d = filePath.split("/");
+ for (int i = 1; i < d.length - 1; i++) {
+ t = t.dirs.get(d[i]);
+ }
+ return t.files.get(d[d.length - 1]);
+ }
+}
+
+class FileSystem1 {
+ class File {
+ boolean isfile = false;
+ HashMap < String, File > files = new HashMap < > ();
+ String content = "";
+ }
+ File root;
+ public FileSystem() {
+ root = new File();
+ }
+
+ public List < String > ls(String path) {
+ File t = root;
+ List < String > files = new ArrayList < > ();
+ if (!path.equals("/")) {
+ String[] d = path.split("/");
+ for (int i = 1; i < d.length; i++) {
+ t = t.files.get(d[i]);
+ }
+ if (t.isfile) {
+ files.add(d[d.length - 1]);
+ return files;
+ }
+ }
+ List < String > res_files = new ArrayList < > (t.files.keySet());
+ Collections.sort(res_files);
+ return res_files;
+ }
+
+ public void mkdir(String path) {
+ File t = root;
+ String[] d = path.split("/");
+ for (int i = 1; i < d.length; i++) {
+ if (!t.files.containsKey(d[i]))
+ t.files.put(d[i], new File());
+ t = t.files.get(d[i]);
+ }
+ }
+
+ public void addContentToFile(String filePath, String content) {
+ File t = root;
+ String[] d = filePath.split("/");
+ for (int i = 1; i < d.length - 1; i++) {
+ t = t.files.get(d[i]);
+ }
+ if (!t.files.containsKey(d[d.length - 1]))
+ t.files.put(d[d.length - 1], new File());
+ t = t.files.get(d[d.length - 1]);
+ t.isfile = true;
+ t.content = t.content + content;
+ }
+
+ public String readContentFromFile(String filePath) {
+ File t = root;
+ String[] d = filePath.split("/");
+ for (int i = 1; i < d.length - 1; i++) {
+ t = t.files.get(d[i]);
+ }
+ return t.files.get(d[d.length - 1]).content;
+ }
+}
+
+/**
+ * Your FileSystem object will be instantiated and called as such:
+ * FileSystem obj = new FileSystem();
+ * List param_1 = obj.ls(path);
+ * obj.mkdir(path);
+ * obj.addContentToFile(filePath,content);
+ * String param_4 = obj.readContentFromFile(filePath);
+ */
\ No newline at end of file
diff --git a/src/geeksforgeeks/InOrderSuccessor.java b/src/geeksforgeeks/InOrderSuccessor.java
new file mode 100644
index 0000000..d71489e
--- /dev/null
+++ b/src/geeksforgeeks/InOrderSuccessor.java
@@ -0,0 +1,29 @@
+package geeksforgeeks;
+public class InOrderSuccessor {
+ /*
+ * @param root: The root of the BST.
+ * @param p: You need find the successor node of p.
+ * @return: Successor of p.
+ */
+ TreeNode result=null;
+ public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
+ helperFn(root,p);
+ return result;
+ }
+ // Inorder traversal is obtained by going right first and follow the left path till end
+ // while traversing right we record the right before taking left turn, incase the left path is null
+
+ public void helperFn(TreeNode root, TreeNode p){
+ if(root==null) return;
+
+ if(root.val>p.val){
+
+ result=root;
+ helperFn(root.left,p);
+ }else{
+
+ helperFn(root.right,p);
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/InorderSuccessorPredecessor.java b/src/geeksforgeeks/InorderSuccessorPredecessor.java
new file mode 100644
index 0000000..3c46754
--- /dev/null
+++ b/src/geeksforgeeks/InorderSuccessorPredecessor.java
@@ -0,0 +1,149 @@
+package geeksforgeeks;
+
+/**
+ * https://algorithms.tutorialhorizon.com/inorder-predecessor-and-successor-in-binary-search-tree/
+ */
+public class InorderSuccessorPredecessor {
+ static int successor, predecessor;
+
+ public void successorPredecessor(TNode root, int val) {
+ // if (root.data == val) {
+ // // go to the right most element in the left subtree, it will be the
+ // // predecessor.
+ // if (root.left != null) {
+ // TNode t = root.left;
+ // while (t.right != null) {
+ // t = t.right;
+ // }
+ // predecessor = t.data;
+ // }
+ // if (root.right != null) {
+ // // go to the left most element in the right subtree, it will be
+ // // the successor.
+ // TNode t = root.right;
+ // while (t.left != null) {
+ // t = t.left;
+ // }
+ // successor = t.data;
+ // }
+ // } else
+ if (root != null) {
+ if (root.data > val) {
+ // we make the root as successor because we might have a
+ // situation when value matches with the root, it wont have
+ // right subtree to find the successor, in that case we need
+ // parent to be the successor
+ successor = root.data;
+ successorPredecessor(root.left, val);
+ } else if (root.data < val) {
+ // we make the root as predecessor because we might have a
+ // situation when value matches with the root, it wont have
+ // left subtree to find the predecessor, in that case we need
+ // parent to be the predecessor.
+ predecessor = root.data;
+ successorPredecessor(root.right, val);
+ }
+ }
+ }
+
+ public void shortSolution(TNode root, int val) {
+ if (root != null) {
+ if (root.data > val) {
+ // we make the root as successor because we might have a
+ // situation when value matches with the root, it wont have
+ // right subtree to find the successor, in that case we need
+ // parent to be the successor
+ successor = root.data;
+ successorPredecessor(root.left, val);
+ } else if (root.data < val) {
+ // we make the root as predecessor because we might have a
+ // situation when value matches with the root, it wont have
+ // left subtree to find the predecessor, in that case we need
+ // parent to be the predecessor.
+ predecessor = root.data;
+ successorPredecessor(root.right, val);
+ }
+ }
+ }
+
+ public static void main(String args[]) {
+ TNode root = new TNode(25);
+ root.left = new TNode(15);
+ root.right = new TNode(40);
+ root.left.left = new TNode(10);
+ root.left.left.left = new TNode(5);
+ root.left.right = new TNode(18);
+ root.right.left = new TNode(35);
+ root.right.right = new TNode(45);
+ root.left.right.left = new TNode(19);
+ root.left.right.right = new TNode(20);
+ InorderSuccessorPredecessor i = new InorderSuccessorPredecessor();
+
+ // i.successorPredecessor(root, 20);
+/* TNode tempSuccessor = root.right;
+ TNode successor = i.findSuccessor(tempSuccessor);
+ successor = successor==null?tempSuccessor:successor;*/
+
+ System.out.println("Inorder Successor of 10 is : " + successor + " and predecessor is : " + predecessor);
+
+ }
+
+ TreeNode result=null;
+ public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
+ helperFn(root,p);
+ return result;
+ }
+
+ public void helperFn(TreeNode root, TreeNode p){
+ if(root==null) return;
+
+ if(root.val>p.val){
+ // System.out.println("greatre root"+root.val);
+ result=root;
+ helperFn(root.left,p);
+ }else{
+ //System.out.println("smaller root"+root.val);
+ helperFn(root.right,p);
+ }
+
+ }
+}
+
+private TreeNode findPredecessor(TreeNode root, TreeNode node) {
+ TreeNode pre = null;
+ TreeNode cur = root;
+ while (cur != null) {
+ if (cur.val < node.val) {
+ pre = cur;
+ cur = cur.right;
+ } else {
+ cur = cur.left;
+ }
+ }
+ return pre;
+}
+private TreeNode findSuccessor(TreeNode root, TreeNode node) {
+ TreeNode succ = null;
+ TreeNode cur = root;
+ while (cur != null) {
+ if (cur.val > node.val) {
+ succ = cur;
+ cur = cur.left;
+ } else {
+ cur = cur.right;
+ }
+ }
+ return succ;
+}
+
+class TNode {
+ int data;
+ TNode left;
+ TNode right;
+
+ public TNode(int data) {
+ this.data = data;
+ left = null;
+ right = null;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/InserstionSortList.java b/src/geeksforgeeks/InserstionSortList.java
new file mode 100644
index 0000000..8ed6bf7
--- /dev/null
+++ b/src/geeksforgeeks/InserstionSortList.java
@@ -0,0 +1,29 @@
+package geeksforgeeks;
+
+public class InserstionSortList {
+ public ListNode insertionSortList(ListNode head) {
+ ListNode dummy = new ListNode(0);
+ ListNode prev = dummy;
+
+ // take 1->2->3->4
+ while (head != null) {
+ ListNode temp = head.next; // at first run temp=2, second run temp=3
+
+ /* Before insert, the prev is at the last node of the sorted list.
+ Only the last node's value is larger than the current inserting node
+ should we move the temp back to the head*/
+ if (prev.val >= head.val) prev = dummy;
+
+ // during second run prev= 0->1->null
+ while (prev.next != null && prev.next.val < head.val) {
+ prev = prev.next;
+ } // after this loop, at first run prev=0 (0->null), second run prev=1
+
+ head.next = prev.next; // we set 1->null // second run 2->null
+ prev.next = head; // 0->1 // 0->1->2
+
+ head = temp; // head= 2->3->4 // head= 3->4
+ }
+ return dummy.next;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/IntegerToBinary.java b/src/geeksforgeeks/IntegerToBinary.java
new file mode 100644
index 0000000..c16ffc3
--- /dev/null
+++ b/src/geeksforgeeks/IntegerToBinary.java
@@ -0,0 +1,38 @@
+package geeksforgeeks;
+
+class IntegerToBinary {
+ // function to convert decimal to binary
+ static void decToBinary(int n) {
+ // array to store binary number
+ int[] binaryNum = new int[1000];
+
+ // counter for binary array
+ int i = 0;
+ while (n > 0) {
+ // storing remainder in binary array
+ binaryNum[i] = n % 2;
+ n = n / 2;
+ i++;
+ }
+
+ // printing binary array in reverse order
+ for (int j = i - 1; j >= 0; j--)
+ System.out.print(binaryNum[j]);
+ }
+
+ public static void main(String[] args) {
+ int n = 4;
+ // decToBinary(n);
+ // System.out.println("Default method :" + Integer.toBinaryString(4));
+ System.out.println(intToBinary(4));
+ }
+
+ public static String intToBinary(int n) {
+ String s = "";
+ while (n > 0) {
+ s = ((n % 2) == 0 ? "0" : "1") + s;
+ n = n / 2;
+ }
+ return s;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/IntersectionOfArrays.java b/src/geeksforgeeks/IntersectionOfArrays.java
new file mode 100644
index 0000000..f104dd9
--- /dev/null
+++ b/src/geeksforgeeks/IntersectionOfArrays.java
@@ -0,0 +1,79 @@
+package geeksforgeeks;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82241/AC-solution-using-Java-HashMap
+ *
+ * Example 1:
+ *
+ * Input: nums1 = [1,2,2,1], nums2 = [2,2]
+ * Output: [2,2]
+ * Example 2:
+ *
+ * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+ * Output: [4,9]
+ */
+public class IntersectionOfArrays {
+ public static void main(String[] args) {
+ IntersectionOfArrays intersectionOfArrays = new IntersectionOfArrays();
+ int[] nums1 = { 4, 4, 9, 5 };
+ int[] nums2 = { 9, 4, 9, 4, 2, 3 };
+ System.out.println(Arrays.toString(intersectionOfArrays.intersect(nums1, nums2)));
+ }
+
+ public int[] intersect(int[] nums1, int[] nums2) {
+ //The first question is relatively easy, create a hashmap base on number frequency of nums1(whichever one is longer).
+
+ // Then for every element of nums2, look upon the hashmap. If we found an intersection, deduct by 1 to avoid duplicate.
+ HashMap map = new HashMap<>();
+ ArrayList result = new ArrayList<>();
+ for (int i = 0; i < nums1.length; i++) {
+ map.put(nums1[i], map.getOrDefault(nums1[i], 1));
+ }
+
+ for (int i = 0; i < nums2.length; i++) {
+ if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) {
+ result.add(nums2[i]);
+ map.put(nums2[i], map.get(nums2[i]) - 1);
+ }
+ }
+
+ int[] r = new int[result.size()];
+ for (int i = 0; i < result.size(); i++) {
+ r[i] = result.get(i);
+ }
+
+ return r;
+ }
+
+ //What if the given array is already sorted? How would you optimize your algorithm?
+ // Classic two pointer iteration, i points to nums1 and j points to nums2.
+ // Because a sorted array is in ascending order, so if nums1[i] > nums[j], we need to increment j, and vice versa.
+ // Only when nums1[i] == nums[j], we add it to the result array. Time Complexity O(max(N, M))
+ public int[] intersectSorted(int[] nums1, int[] nums2) {
+ Arrays.sort(nums1);
+ Arrays.sort(nums2);
+ int n = nums1.length, m = nums2.length;
+ int i = 0, j = 0;
+ List list = new ArrayList<>();
+ while(i < n && j < m){
+ int a = nums1[i], b= nums2[j];
+ if(a == b){
+ list.add(a);
+ i++;
+ j++;
+ }else if(a < b){
+ i++;
+ }else{
+ j++;
+ }
+ }
+ int[] ret = new int[list.size()];
+ for(int k = 0; k < list.size();k++) ret[k] = list.get(k);
+ return ret;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/IsEditOneDistanceAway.java b/src/geeksforgeeks/IsEditOneDistanceAway.java
new file mode 100644
index 0000000..ad443e8
--- /dev/null
+++ b/src/geeksforgeeks/IsEditOneDistanceAway.java
@@ -0,0 +1,44 @@
+package geeksforgeeks;
+
+class IsEditOneDistanceAway {
+ static boolean isOneEdit(String first, String second) {
+ // if the input string are same
+ if (first.equals(second))
+ return false;
+
+ int len1 = first.length();
+ int len2 = second.length();
+ // If the length difference of the stings is more than 1, return false.
+ if ((len1 - len2) > 1 || (len2 - len1) > 1) {
+ return false;
+ }
+ int i = 0, j = 0;
+ int diff = 0;
+ while (i < len1 && j < len2) {
+ char f = first.charAt(i);
+ char s = second.charAt(j);
+ if (f != s) {
+ diff++;
+ if (len1 > len2)
+ i++;
+ if (len2 > len1)
+ j++;
+ if (len1 == len2)
+ i++;
+ j++;
+ } else {
+ i++;
+ j++;
+ }
+ if (diff > 1) {
+ return false;
+ }
+ }
+ // If the length of the string is not same. ex. "abc" and "abde" are not one
+ // edit distance.
+ if (diff == 1 && len1 != len2 && (i != len1 || j != len2)) {
+ return false;
+ }
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/IsSubsequence.java b/src/geeksforgeeks/IsSubsequence.java
new file mode 100644
index 0000000..53df8e0
--- /dev/null
+++ b/src/geeksforgeeks/IsSubsequence.java
@@ -0,0 +1,22 @@
+package geeksforgeeks;
+
+public class IsSubsequence {
+ // Input: s = "abc", t = "ahbgdc"
+ // Output: true
+ // Input: s = "axc", t = "ahbgdc"
+ // Output: false
+ public boolean isSubsequence(String s, String t) {
+ if(s==null || t==null) return false;
+ int i=0; int j=0;
+
+ while(i queue = new ArrayDeque<>();
+ queue.offer(root);
+ while (!queue.isEmpty()) {
+ Pair temp = queue.poll();
+ for (int[] dir : directions) {
+
+ int x = temp.x + dir[0];
+ int y = temp.y + dir[1];
+ if (isvalid(grid, x, y)) {
+ grid[x][y] = '0';
+ queue.offer(new Pair(x, y));
+ }
+ }
+ }
+ }
+
+ public boolean isvalid(char[][] grid, int x, int y) {
+ if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == '0') {
+ return false;
+ }
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/Islands.java b/src/geeksforgeeks/Islands.java
index 948f3bb..49a8bad 100644
--- a/src/geeksforgeeks/Islands.java
+++ b/src/geeksforgeeks/Islands.java
@@ -11,8 +11,9 @@ class Islands {
public int numIslands(int[][] grid) {
int count = 0;
n = grid.length;
- if (n == 0)
+ if (n == 0) {
return 0;
+ }
m = grid[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
@@ -25,8 +26,9 @@ public int numIslands(int[][] grid) {
}
private void DFSMarking(int[][] grid, int i, int j) {
- if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != 1)
+ if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != 1) {
return;
+ }
grid[i][j] = 0;
DFSMarking(grid, i + 1, j);
DFSMarking(grid, i - 1, j);
@@ -35,7 +37,7 @@ private void DFSMarking(int[][] grid, int i, int j) {
}
public static void main(String[] args) {
- int M[][] = new int[][]{{1, 1, 1, 1, 0}, {1, 1, 0, 1, 0}, {1, 1, 0, 0, 0}, {0, 0, 0, 0, 0}};
+ int M[][] = new int[][] { { 1, 1, 1, 1, 0 }, { 1, 1, 0, 1, 0 }, { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 } };
Islands I = new Islands();
System.out.println("Number of islands is: " + I.numIslands(M));
}
diff --git a/src/geeksforgeeks/IsomorphicArray.java b/src/geeksforgeeks/IsomorphicArray.java
index f0ded5e..8eacfe8 100644
--- a/src/geeksforgeeks/IsomorphicArray.java
+++ b/src/geeksforgeeks/IsomorphicArray.java
@@ -1,33 +1,36 @@
package geeksforgeeks;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
public class IsomorphicArray {
public Collection> groupIsomorphicStrings(List strings) {
- if (strings == null || strings.isEmpty())
+ if (strings == null || strings.isEmpty()) {
return Collections.EMPTY_LIST;
+ }
Map> hashToList = new HashMap<>();
for (String string : strings) {
String hash = hash(string);
- if (!hashToList.containsKey(hash))
+ if (!hashToList.containsKey(hash)) {
hashToList.put(hash, new ArrayList<>());
+ }
hashToList.get(hash).add(string);
}
return hashToList.values();
}
-
+ // this method returns a hash value for every string passed in
+ // apple = 12234
+ // apply = 12234
+ // dog = 123
+ // cog = 123
+ // romi = 1234
private String hash(String s) {
- if (s.isEmpty())
+ if (s.isEmpty()) {
return "";
+ }
int count = 1;
StringBuilder hash = new StringBuilder();
@@ -36,13 +39,18 @@ private String hash(String s) {
for (char c : s.toCharArray()) {
- if (map.containsKey(c))
- hash.append(map.get(c));
- else {
+ if (!map.containsKey(c)) {
map.put(c, count++);
- hash.append(map.get(c));
}
+ hash.append(map.get(c));
}
+ System.out.println(s +" = "+hash.toString() );
return hash.toString();
}
+
+ public static void main(String[] args) {
+ Collection> result = new IsomorphicArray()
+ .groupIsomorphicStrings(Arrays.asList("apple", "apply", "dog", "cog", "romi"));
+ result.stream().forEach(System.out::println);
+ }
}
diff --git a/src/geeksforgeeks/IsomorphicString.java b/src/geeksforgeeks/IsomorphicString.java
index 3fae7d5..1f41f1e 100644
--- a/src/geeksforgeeks/IsomorphicString.java
+++ b/src/geeksforgeeks/IsomorphicString.java
@@ -7,14 +7,16 @@
*/
class IsomorphicString {
static boolean isIsomorphic(String s, String t) {
- int m1[] = new int[256];
- int m2[] = new int[256];
+ char m1[] = new int[256];
+ char m2[] = new int[256];
int n = s.length();
for (int i = 0; i < n; ++i) {
// it checks the count of the character in the array ;
// for 'g' -> a[103] is 2 and 'd' -> a[100] is 2
- if (m1[s.charAt(i)] != m2[t.charAt(i)])
+ // if both are same both gets incremented together else return false
+ if (m1[s.charAt(i)] != m2[t.charAt(i)]) {
return false;
+ }
m1[s.charAt(i)] = i + 1;
m2[t.charAt(i)] = i + 1;
}
diff --git a/src/geeksforgeeks/JumpsToReachEnd.java b/src/geeksforgeeks/JumpsToReachEnd.java
new file mode 100644
index 0000000..7f305c1
--- /dev/null
+++ b/src/geeksforgeeks/JumpsToReachEnd.java
@@ -0,0 +1,62 @@
+package geeksforgeeks;
+
+import java.util.*;
+
+public class JumpsToReachEnd {
+
+ public static boolean canReachEnd(List maxAdvanceSteps) {
+ int furthestReachSoFar = 0, lastlndex = maxAdvanceSteps.size() - 1;
+
+ //i <= furthestReachSoFar && furthestReachSoFar < lastlndex this is the imp part of the solution
+ for (int i = 0; i <= furthestReachSoFar && furthestReachSoFar < lastlndex; ++i) {
+ // for every index store max-steps it can take and i should be
+ // less than maxSteps to check if it can move further
+ // e.x (3, 2, 0, 0, 2, 0,1) when index i is 3 maxStpes is also 3, it cannot move further
+ furthestReachSoFar = Math.max(furthestReachSoFar, i + maxAdvanceSteps.get(i));
+ }
+ return furthestReachSoFar >= lastlndex;
+ }
+
+
+ // Given an array of non-negative integers arr, you are initially positioned at start index of the array.
+ // When you are at index i, you can jump to i + arr[i] or i - arr[i],
+ // check if you can reach to any index with value 0.
+ public boolean canReach(int[] arr, int start) {
+ // visited check included
+ if(start>=arr.length || start<0 || arr[start]>arr.length || arr[start]<0) return false;
+ if(arr[start]==0 ) return true;
+ arr[start]=-arr[start]; // visited marking
+ return canReach(arr, start+arr[start]) || canReach(arr, start-arr[start]);
+
+ }
+
+ public int minJump(int[] nums) {
+ if(nums==null || nums.length==0) return 0;
+ int currentMax=0;
+ int currentEnd=0;
+ int jumps=0;
+
+ for(int i=0;i=nums.length-1){ // if the current pick solves the issue
+ jumps++;
+ break;
+ }
+ //Once the current point reaches curEnd,
+ //then trigger another jump, and set the new curEnd with curFarthest,
+ //then keep the above steps, as the following:
+ if(currentEnd==i){ // when the current pick of ladder reached last step
+ jumps++;
+ currentEnd=currentMax;
+ }
+ }
+ return jumps;
+ }
+
+ public static void main(String[] args) {
+
+ List list= Arrays.asList(new Integer[]{3,3,1,0, 2,0,1});
+ System.out.println(canReachEnd(list));
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/KClosestElements.java b/src/geeksforgeeks/KClosestElements.java
new file mode 100644
index 0000000..6ea0cd5
--- /dev/null
+++ b/src/geeksforgeeks/KClosestElements.java
@@ -0,0 +1,66 @@
+package geeksforgeeks;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.PriorityQueue;
+
+/**
+ * Given a sorted array arr, two integers k and x, find the k closest elements to x in the array.
+ * Input: arr = [1,2,3,4,5], k = 4, x = 3
+Output: [1,2,3,4]
+ */
+public class KClosestElements {
+ public List findClosestElements(int[] arr, int k, int x) {
+ // since this is sorted array we are making use of binary search to get index of X and
+ // fix the range between index-K to index+K and doing normal PQ solution
+ int index= binarySearch(arr,x);
+ //if(index==-1) return Collections.emptyList();
+
+ int low= Math.max(0,index-k);
+ int high= Math.min(index+k,arr.length-1);
+
+ PriorityQueue queue= new PriorityQueue<>((a, b)->Integer.compare(a.key,b.key));
+
+ for(int i=low;i<=high;i++){
+ // taking abs value because question is askin closest in both signs
+ queue.offer(new Entry(Math.abs(arr[i]-x),i));
+ }
+ List result= new ArrayList<>();
+ int i=0;
+ while(i0){
+ start--;
+ }
+ return start;
+ }
+}
+
+class Entry{
+ int key;
+ int value;
+ public Entry(int key, int value){
+ this.key=key;
+ this.value=value;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/KmostFrequentLetters.java b/src/geeksforgeeks/KmostFrequentLetters.java
new file mode 100644
index 0000000..a5d1022
--- /dev/null
+++ b/src/geeksforgeeks/KmostFrequentLetters.java
@@ -0,0 +1,42 @@
+package geeksforgeeks;
+
+import java.util.*;
+
+public class KmostFrequentLetters {
+ public static void main(String[] args) {
+ int k1 = 2;
+ String[] keywords1 = { "anacell", "cetracular", "betacellular" };
+ String[] reviews1 = { "Anacell provides the best services in the city", "betacellular has awesome services",
+ "Best services provided by anacell, everyone should use anacell", };
+ int k2 = 2;
+ String[] keywords2 = { "anacell", "betacellular", "cetracular", "deltacellular", "eurocell" };
+ String[] reviews2 = { "I love anacell Best services; Best services provided by anacell",
+ "betacellular has great services", "deltacellular provides much better services than betacellular",
+ "cetracular is worse than anacell", "Betacellular is better than deltacellular.", };
+ System.out.println(solve(k1, keywords1, reviews1));
+ System.out.println(solve(k2, keywords2, reviews2));
+ }
+
+ private static List solve(int k, String[] keywords, String[] reviews) {
+ List res = new ArrayList<>();
+ Set set = new HashSet<>(Arrays.asList(keywords));
+ Map map = new HashMap<>();
+ for(String r : reviews) {
+ String[] strs = r.split("\\W");
+ Set added = new HashSet<>(); // creating a set per review to vaoid duplicate within a review
+ for(String s : strs) {
+ s = s.toLowerCase();
+ if(set.contains(s) && !added.contains(s)) {
+ map.put(s, map.getOrDefault(s, 0) + 1);
+ added.add(s);
+ }
+ }
+ }
+ PriorityQueue> maxHeap = new PriorityQueue<>((a, b)->a.getValue() == b.getValue() ? a.getKey().compareTo(b.getKey()) : b.getValue() - a.getValue());
+ maxHeap.addAll(map.entrySet());
+ while(!maxHeap.isEmpty() && k-- > 0) {
+ res.add(maxHeap.poll().getKey());
+ }
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/KthClosestOrigin.java b/src/geeksforgeeks/KthClosestOrigin.java
index 323ebef..fb4967c 100644
--- a/src/geeksforgeeks/KthClosestOrigin.java
+++ b/src/geeksforgeeks/KthClosestOrigin.java
@@ -5,95 +5,98 @@
/**
* https://leetcode.com/problems/k-closest-points-to-origin/solution/
- *
*/
class KthClosestOrigin {
- static int[][] points = new int[3][2];
-
- // quick select
- public int[][] kClosest(int[][] points, int K) {
- sort(0, points.length - 1, K);
- return Arrays.copyOfRange(points, 0, K);
- }
-
- public void sort(int i, int j, int K) {
- if (i >= j)
- return;
- int k = new Random().nextInt(j - i + 1) + i;
- swap(i, k);
-
- int mid = partition(i, j);
- int leftLength = mid - i + 1;
- if (K < leftLength)
- sort(i, mid - 1, K);
- else if (K > leftLength)
- sort(mid + 1, j, K - leftLength);
- }
-
- public int partition(int i, int j) {
- int oi = i;
- int pivot = dist(i);
- i++;
-
- while (true) {
- while (i < j && dist(i) < pivot)
- i++;
- while (i <= j && dist(j) > pivot)
- j--;
- if (i >= j)
- break;
- swap(i, j);
- }
- swap(oi, j);
- return j;
- }
-
- public int dist(int i) {
- return points[i][0] * points[i][0] + points[i][1] * points[i][1];
- }
-
- public void swap(int i, int j) {
- int t0 = points[i][0], t1 = points[i][1];
- points[i][0] = points[j][0];
- points[i][1] = points[j][1];
- points[j][0] = t0;
- points[j][1] = t1;
- }
-
- public int[][] kClosestOLogN(int[][] points, int K) {
- int N = points.length;
- int[] dists = new int[N];
- for (int i = 0; i < N; ++i)
- dists[i] = distOLogN(points[i]);
-
- Arrays.sort(dists);
- int distK = dists[K - 1];
-
- int[][] ans = new int[K][2];
- int t = 0;
- for (int i = 0; i < N; ++i)
- if (distOLogN(points[i]) <= distK)
- ans[t++] = points[i];
- return ans;
- }
-
- public int distOLogN(int[] point) {
- return point[0] * point[0] + point[1] * point[1];
- }
-
- public static void main(String[] args) {
- KthClosestOrigin kth = new KthClosestOrigin();
- points[0][0] = 3;
- points[0][1] = 3;
-
- points[1][0] = 5;
- points[1][1] = -1;
-
- points[2][0] = 2;
- points[2][1] = 4;
-
- // System.out.println(Arrays.deepToString(kth.kClosestOLogN(points, 1)));
- System.out.println(Arrays.deepToString(kth.kClosest(points, 2)));
- }
+ static int[][] points = new int[3][2];
+
+ // quick select
+ public int[][] kClosest(int[][] points, int K) {
+ sort(0, points.length - 1, K);
+ return Arrays.copyOfRange(points, 0, K);
+ }
+
+ public void sort(int i, int j, int K) {
+ if (i >= j) {
+ return;
+ }
+ int k = new Random().nextInt(j - i + 1) + i;
+ swap(i, k);
+
+ int mid = partition(i, j);
+ int leftLength = mid - i + 1;
+ if (K < leftLength) {
+ sort(i, mid - 1, K);
+ } else if (K > leftLength) {
+ sort(mid + 1, j, K - leftLength);
+ }
+ }
+
+ public int partition(int i, int j) {
+ int oi = i;
+ int pivot = dist(i);
+ i++;
+
+ while (true) {
+ while (i < j && dist(i) < pivot)
+ i++;
+ while (i <= j && dist(j) > pivot)
+ j--;
+ if (i >= j) {
+ break;
+ }
+ swap(i, j);
+ }
+ swap(oi, j);
+ return j;
+ }
+
+ public int dist(int i) {
+ return points[i][0] * points[i][0] + points[i][1] * points[i][1];
+ }
+
+ public void swap(int i, int j) {
+ int t0 = points[i][0], t1 = points[i][1];
+ points[i][0] = points[j][0];
+ points[i][1] = points[j][1];
+ points[j][0] = t0;
+ points[j][1] = t1;
+ }
+
+ public int[][] kClosestOLogN(int[][] points, int K) {
+ int N = points.length;
+ int[] dists = new int[N];
+ for (int i = 0; i < N; ++i)
+ dists[i] = distOLogN(points[i]);
+
+ Arrays.sort(dists);
+ int distK = dists[K - 1];
+
+ int[][] ans = new int[K][2];
+ int t = 0;
+ for (int i = 0; i < N; ++i)
+ if (distOLogN(points[i]) <= distK) {
+ ans[t++] = points[i];
+ }
+ return ans;
+ }
+
+ public int distOLogN(int[] point) {
+ return point[0] * point[0] + point[1] * point[1];
+ }
+
+ public static void main(String[] args) {
+ KthClosestOrigin kth = new KthClosestOrigin();
+ points[0][0] = 3;
+ points[0][1] = 3;
+
+ points[1][0] = 5;
+ points[1][1] = -1;
+
+ points[2][0] = 2;
+ points[2][1] = 4;
+
+ // System.out.println(Arrays.deepToString(kth.kClosestOLogN(points, 1)));
+ System.out.println(Arrays.deepToString(kth.kClosest(points, 2)));
+ }
}
diff --git a/src/geeksforgeeks/KthSmallestFromTwoSortedArrays.java b/src/geeksforgeeks/KthSmallestFromTwoSortedArrays.java
index b27bf5d..d62166f 100644
--- a/src/geeksforgeeks/KthSmallestFromTwoSortedArrays.java
+++ b/src/geeksforgeeks/KthSmallestFromTwoSortedArrays.java
@@ -1,5 +1,8 @@
package geeksforgeeks;
+/**
+ * https://www.geeksforgeeks.org/k-th-element-two-sorted-arrays/
+ */
class KthSmallestFromTwoSortedArrays {
public static int findKth(int[] A, int i, int[] B, int j, int k) {
@@ -26,14 +29,15 @@ public static int findKth(int[] A, int i, int[] B, int j, int k) {
}
public static void main(String[] args) {
- int arr1[] = {1,6,8,9,15};
- int arr2[] = {3,5,10,14,20};
+ int arr1[] = { 1, 6, 8, 9, 15 };
+ int arr2[] = { 3, 5, 10, 14, 20 };
int k = 6;
int ans = findKth(arr1, 0, arr2, 0, k);
- if (ans == -1)
+ if (ans == -1) {
System.out.println("Invalid query");
- else
+ } else {
System.out.println(ans);
+ }
}
}
diff --git a/src/geeksforgeeks/KthSmallestMatrix.java b/src/geeksforgeeks/KthSmallestMatrix.java
index ac71a24..29bebcb 100644
--- a/src/geeksforgeeks/KthSmallestMatrix.java
+++ b/src/geeksforgeeks/KthSmallestMatrix.java
@@ -13,17 +13,16 @@ public static int kthSmallest(int[][] matrix, int k) {
for (int i = 0; i < k - 1; i++) {
Points t = pq.poll();
System.out.println(t.x);
- if (t.x == n - 1)
+ if (t.x == n - 1) {
continue;
+ }
pq.offer(new Points(t.x + 1, t.y, matrix[t.x + 1][t.y]));
}
return pq.poll().val;
}
public static void main(String[] args) {
- int[][] matrix = {{1, 2, 9},
- {3, 11, 13},
- {4, 13, 15}};
+ int[][] matrix = { { 1, 2, 9 }, { 3, 11, 13 }, { 4, 13, 15 } };
int k = 4;
System.out.println(kthSmallest(matrix, k));
diff --git a/src/geeksforgeeks/LIS2DMatrix.java b/src/geeksforgeeks/LIS2DMatrix.java
new file mode 100644
index 0000000..5ea3e62
--- /dev/null
+++ b/src/geeksforgeeks/LIS2DMatrix.java
@@ -0,0 +1,52 @@
+package geeksforgeeks;
+
+/**
+ * DFS + Memoization
+ *
+ * Traverse all points in matrix, use every point as starting point to do dfs traversal. DFS function returns max increasing
+ * path after comparing four max return distance from four directions.
+ */
+
+class LIS2DMatrix {
+ int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
+
+ public int longestIncreasingPath(int[][] matrix) {
+
+ if (matrix.length == 0) return 0;
+ // i+1,j, i-1,j i,j+1 i,j-1
+ Integer[][] cache = new Integer[matrix.length][matrix[0].length];
+ //Arrays.fill(cache,-1);
+ int result = 0;
+ for (int i = 0; i < matrix.length; i++) {
+ for (int j = 0; j < matrix[0].length; j++) {
+ result = Math.max(dfsUtil(matrix, i, j, cache, Integer.MIN_VALUE), result);
+ }
+ }
+
+ return result;
+ }
+
+ public int dfsUtil(int[][] matrix, int i, int j, Integer[][] cache, int data) {
+ if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length || data >= matrix[i][j]) return 0;
+
+
+ if (cache[i][j] != null) return cache[i][j];
+
+ int max = 1; // every element is an answer to itself
+
+ for (int[] dir : dirs) {
+
+ int x = i + dir[0];
+ int y = j + dir[1];
+
+ int count = 1 + dfsUtil(matrix, x, y, cache, matrix[i][j]);
+ max = Math.max(count, max);
+ }
+ cache[i][j] = max;
+
+ return cache[i][j];
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LRUCache.java b/src/geeksforgeeks/LRUCache.java
index a4acbc6..5c99caf 100644
--- a/src/geeksforgeeks/LRUCache.java
+++ b/src/geeksforgeeks/LRUCache.java
@@ -1,132 +1,118 @@
package geeksforgeeks;
-/*
- https://leetcode.com/problems/lru-cache/
- An adaption of the answer from user "liaison" on Leetcode.
- Link: https://leetcode.com/problems/lru-cache/discuss/45911/Java-Hashtable-%2B-Double-linked-list-(with-a-touch-of-pseudo-nodes)
- Revision by Benyam Ephrem (Dec. 31th 2018)
- > Making variable names more conventional
- > Adding more clarifying comments
- > Moving code around to be more conventional
- This code passes all Leetcode test cases as of Dec. 31st 2018
- Runtime: 77 ms, faster than 95.85% of Java online submissions for LRU Cache.
- The video to explain this code is here: https://www.youtube.com/watch?v=S6IfqDXWa10
-*/
-
-import java.util.HashMap;
-import java.util.Map;
-
class LRUCache {
-
- private class DNode {
+
+ class DLLNode{
+ DLLNode prev;
+ DLLNode next;
+ int val;
int key;
- int value;
- DNode prev;
- DNode next;
- }
-
- private Map hashtable = new HashMap<>();
- private DNode head, tail;
- private int totalItemsInCache;
- private int maxCapacity;
-
- public LRUCache(int maxCapacity) {
-
- totalItemsInCache = 0;
- this.maxCapacity = maxCapacity;
-
- head = new DNode();
- head.prev = null;
-
- tail = new DNode();
- tail.next = null;
-
- head.next = tail;
- tail.prev = head;
- }
-
- public int get(int key) {
-
- DNode node = hashtable.get(key);
- boolean itemFoundInCache = node != null;
-
- if (!itemFoundInCache) {
- return -1;
+ public DLLNode(int key, int val){
+ this.val=val;
+ this.key=key;
}
-
- moveToHead(node);
-
- return node.value;
}
-
- public void put(int key, int value) {
-
- DNode node = hashtable.get(key);
- boolean itemFoundInCache = node != null;
-
- if (!itemFoundInCache) {
-
- DNode newNode = new DNode();
- newNode.key = key;
- newNode.value = value;
-
- hashtable.put(key, newNode);
- addNode(newNode);
-
- totalItemsInCache++;
-
- if (totalItemsInCache > maxCapacity) {
- removeLRUEntryFromStructure();
+ Map map;
+ DLLNode head;
+ DLLNode tail;
+ int capacity=0;
+ public LRUCache(int capacity) {
+ map= new HashMap<>();
+ head= new DLLNode(-1,-1);
+ tail= new DLLNode(-1,-1);
+ head.next=tail;
+ tail.prev=head;
+ this.capacity=capacity;
+ }
+
+ public int get(int key) {
+ if(!map.containsKey(key)) return -1;
+ DLLNode node= map.get(key);
+ update(node);
+ return node.val;
+ }
+
+ public void put(int key, int value) {
+ if(map.containsKey(key)){
+ DLLNode node= map.get(key);
+ node.val=value;
+ update(node);
+ }else{
+ if(map.size()>=capacity){
+ removeTail();
+ }
+ DLLNode newNode= new DLLNode(key,value);
+ map.put(key, newNode);
+
+ updateHead(newNode);
}
-
- } else {
- node.value = value;
- moveToHead(node);
+ }
+
+ public void removeTail(){
+ DLLNode tailNode=tail.prev;
+ remove(tailNode);
+ map.remove(tailNode.key);
+ }
+
+ public void updateHead(DLLNode node){
+ node.prev = head;
+ node.next = head.next;
+ head.next.prev = node;
+ head.next = node;
+ }
+
+ public void remove(DLLNode node){
+ DLLNode next= node.next;
+ DLLNode prev= node.prev;
+ prev.next=next;
+ next.prev=prev;
+ }
+ public void update(DLLNode node){
+ remove(node);
+ updateHead(node);
}
}
-
- private void removeLRUEntryFromStructure() {
- DNode tail = popTail();
- hashtable.remove(tail.key);
- --totalItemsInCache;
- }
-
- private void addNode(DNode node) {
-
- node.prev = head;
- node.next = head.next;
-
- head.next.prev = node;
- head.next = node;
- }
-
- private void removeNode(DNode node) {
-
- DNode savedPrev = node.prev;
- DNode savedNext = node.next;
-
- savedPrev.next = savedNext;
- savedNext.prev = savedPrev;
- }
-
- private void moveToHead(DNode node) {
- removeNode(node);
- addNode(node);
- }
-
- private DNode popTail() {
- DNode itemBeingRemoved = tail.prev;
- removeNode(itemBeingRemoved);
- return itemBeingRemoved;
- }
-
- public static void main(String[] args) {
- LRUCache lru = new LRUCache(3);
- lru.put(1, 1);
- lru.put(2, 2);
- lru.put(3, 3);
- lru.put(2, 2);
- lru.put(4, 4);
- lru.put(2, 2);
- lru.put(3, 3);
+
+
+ class LRUCache1 {
+ LinkedHashMap isbnToPrice;
+
+ LRUCache(final int capacity) {
+ this.isbnToPrice
+ = new LinkedHashMap(capacity, 1f, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry e) {
+ return this.size() > capacity;
+ }
+ };
+ }
+
+ public Integer lookup(Integer key) {
+ if (!isbnToPrice.containsKey(key)) {
+ return null;
+ }
+ return isbnToPrice.get(key);
+ }
+
+ public Integer insert(Integer key, Integer value) {
+ // We add the value for key only if key is not present - we don’t update
+ // existing values.
+ Integer currentValue = isbnToPrice.get(key);
+ if (!isbnToPrice.containsKey(key)) {
+ isbnToPrice.put(key, value);
+ return currentValue;
+ } else {
+ return null;
+ }
+ }
+
+ public Integer erase(Object key) {
+ return isbnToPrice.remove(key);
+ }
+
}
-}
+ /**
+ * Your LRUCache object will be instantiated and called as such:
+ * LRUCache obj = new LRUCache(capacity);
+ * int param_1 = obj.get(key);
+ * obj.put(key,value);
+ */
\ No newline at end of file
diff --git a/src/geeksforgeeks/LargestDivisibleSubset.java b/src/geeksforgeeks/LargestDivisibleSubset.java
new file mode 100644
index 0000000..e52f5d2
--- /dev/null
+++ b/src/geeksforgeeks/LargestDivisibleSubset.java
@@ -0,0 +1,64 @@
+package geeksforgeeks;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
+ Si % Sj = 0 or Sj % Si = 0.
+ If there are multiple solutions, return any subset is fine.
+ Input: [2,3,4,6,10,8,24]
+ Output: [2,4,8,24] each pair's modulo is 0
+ */
+public class LargestDivisibleSubset {
+
+ /**
+ * if a%b==0 means a>b, if b>a then the ans is b itself
+ *inorder to have that we need to sort the array in increasing order
+ at first each val is ans to itself, then we come from last so a is higher in a%b
+ [2, 3, 4, 6, 8, 10, 24]
+ {2} {3} {4} {6} {8} {10} {24}
+ {8,24}
+
+ {6,24}
+
+ {4,8,24}
+
+ {3,6,24}
+
+ {2,4,8,24}
+ *
+ */
+ public List largestDivisibleSubset(int[] nums) {
+ if(nums==null || nums.length==0) return Collections.emptyList();
+
+ Arrays.sort(nums);
+ List[] result= new ArrayList[nums.length];
+
+ int maxLength=0;
+ int resIndex=-1;
+ List re;
+
+ for(int i=nums.length-1;i>=0;i--){
+ result[i]=new ArrayList<>(); // every element is an answer itself
+ re= new ArrayList<>();
+ result[i].add(nums[i]);
+ for(int j=i+1;j re.size()){ // this is to take even if 1 element is at j position
+ re=result[j]; // the reason we take list is consider 4,8,24 when i is at 4 and j is 8 mod is 0 means 4%24 is also zero
+ }
+ }
+ }
+ result[i].addAll(re);
+ if(result[i].size()>maxLength){
+ maxLength=result[i].size();
+ resIndex=i;
+ }
+ }
+ Collections.sort(result[resIndex]);
+ return result[resIndex];
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LargestPossibleNumber.java b/src/geeksforgeeks/LargestPossibleNumber.java
index 9f349c3..398815f 100644
--- a/src/geeksforgeeks/LargestPossibleNumber.java
+++ b/src/geeksforgeeks/LargestPossibleNumber.java
@@ -5,9 +5,13 @@
import java.util.Comparator;
import java.util.List;
+/**
+ * https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/
+ */
class LargestPossibleNumber {
+
public static void main(String[] args) {
- int nums[] = {10, 68, 97, 9, 21, 12};
+ int nums[] = { 10, 68, 97, 9, 21, 12 };
List numbers = Arrays.asList("10", "68", "97", "9", "21", "12");
Collections.sort(numbers, (a, b) -> (b + a).compareTo(a + b));
@@ -21,10 +25,9 @@ public String largestNumber(int[] nums) {
arr[i] = String.valueOf(nums[i]);
}
- Arrays.sort(arr,
- (a, b) -> {
- return (b + a).compareTo(a + b);
- });
+ Arrays.sort(arr, (a, b) -> {
+ return (b + a).compareTo(a + b);
+ });
StringBuilder sb = new StringBuilder();
for (String s : arr) {
@@ -36,4 +39,17 @@ public String largestNumber(int[] nums) {
return sb.toString();
}
+
+ public String largestNumber1(int[] nums) {
+ if(nums==null || nums.length==0) return null;
+ List list= new LinkedList<>();
+ for(int i: nums){
+ list.add(String.valueOf(i));
+ }
+
+ Collections.sort(list, (a,b)->(int)(Long.parseLong(b+a)-Long.parseLong(a+b)));
+
+ return String.join("",list).replaceFirst("^0+(?!$)", "");
+
+ }
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LargestSubArray.java b/src/geeksforgeeks/LargestSubArray.java
deleted file mode 100644
index 6abddb7..0000000
--- a/src/geeksforgeeks/LargestSubArray.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package geeksforgeeks;
-
-import java.util.HashMap;
-
-/*https://www.geeksforgeeks.org/largest-subarray-with-equal-number-of-0s-and-1s/*/
-class LargestSubArray {
-
- int maxLen(int arr[], int n) {
-
- HashMap map = new HashMap<>();
-
- int sum = 0;
- int maxLength = 0;
- int endingIndex = -1;
-
- for (int i = 0; i < n; i++) {
- arr[i] = (arr[i] == 0) ? -1 : 1;
- }
-
- for (int i = 0; i < n; i++) {
- sum += arr[i];
- if (sum == 0) {
- maxLength = i + 1;
- endingIndex = i;
- }
-
- if (map.containsKey(sum)) {
- if (maxLength < i - map.get(sum)) {
- maxLength = i - map.get(sum);
- endingIndex = i;
- }
- } else
- map.put(sum, i);
- }
-
- for (int i = 0; i < n; i++) {
- arr[i] = (arr[i] == -1) ? 0 : 1;
- }
-
- int start = endingIndex - maxLength + 1;
- System.out.println(start + " to " + endingIndex);
-
- return maxLength;
- }
-
- public static void main(String[] args) {
- LargestSubArray sub = new LargestSubArray();
- int arr[] = {0, 0, 0, 1, 0, 1, 1};
- int n = arr.length;
-
- sub.maxLen(arr, n);
- }
-}
diff --git a/src/geeksforgeeks/LargestSubArrayWithZeroesAndOnes.java b/src/geeksforgeeks/LargestSubArrayWithZeroesAndOnes.java
new file mode 100644
index 0000000..2d5e893
--- /dev/null
+++ b/src/geeksforgeeks/LargestSubArrayWithZeroesAndOnes.java
@@ -0,0 +1,68 @@
+package geeksforgeeks;
+
+import java.util.HashMap;
+
+/*https://www.geeksforgeeks.org/largest-subarray-with-equal-number-of-0s-and-1s/
+ Given an array containing only 0s and 1s, find the largest subarray which contains equal no of 0s and 1s.
+ Expected time complexity is O(n).
+*/
+class LargestSubArrayWithZeroesAndOnes {
+ /**
+ * The concept of taking cumulative sum, taking 0’s as -1 will help us in optimising the approach.
+ * While taking the cumulative sum, there are two cases when there can be a sub-array with equal number of 0’s and 1’s
+ * When cumulative sum=0, which signifies that sub-array from index (0) till present index has equal number of 0’s and 1’s.
+ *
+ * When we encounter a cumulative sum value which we have already encountered before,
+ * which means that sub-array from the previous index+1 till the present index has equal number of 0’s and 1’s as they give a cumulative sum of 0 .
+ * @param arr
+ * @param n
+ * @return
+ */
+ int maxLen(int arr[], int n) {
+
+ HashMap map = new HashMap<>();
+
+ int sum = 0;
+ int maxLength = 0;
+ int endingIndex = -1;
+
+ for (int i = 0; i < n; i++) {
+ arr[i] = (arr[i] == 0) ? -1 : 1;
+ }
+
+ for (int i = 0; i < n; i++) {
+ sum += arr[i];
+
+ if (sum == 0) { // To handle sum=0 at last index
+ maxLength = i + 1;
+ endingIndex = i;
+ }
+ // If this sum is seen before,
+ // then update max_len if required
+ if (map.containsKey(sum)) {
+ if (maxLength < i - map.get(sum)) {
+ maxLength = i - map.get(sum);
+ endingIndex = i;
+ }
+ } else
+ map.put(sum, i);
+ }
+
+ for (int i = 0; i < n; i++) {
+ arr[i] = (arr[i] == -1) ? 0 : 1;
+ }
+
+ int start = endingIndex - maxLength + 1;
+ System.out.println(start + " to " + endingIndex);
+
+ return maxLength;
+ }
+
+ public static void main(String[] args) {
+ LargestSubArrayWithZeroesAndOnes sub = new LargestSubArrayWithZeroesAndOnes();
+ int arr[] = {0, 0, 0, 1, 0, 1, 1};
+ int n = arr.length;
+
+ sub.maxLen(arr, n);
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LengthOfLongestSubstringKDistinct.java b/src/geeksforgeeks/LengthOfLongestSubstringKDistinct.java
new file mode 100644
index 0000000..f832355
--- /dev/null
+++ b/src/geeksforgeeks/LengthOfLongestSubstringKDistinct.java
@@ -0,0 +1,40 @@
+package geeksforgeeks;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class LengthOfLongestSubstringKDistinct {
+ /**
+ * @param s: A string
+ * @param k: An integer
+ *
+ * @return: An integer
+ */
+ public int lengthOfLongestSubstringKDistinct(String s, int k) {
+ if (s == null || k == 0) {
+ return 0;
+ }
+ Map map = new HashMap<>();
+
+ int result = 0;
+ int left = 0;
+ int right = 0;
+
+ while (left < s.length()) {
+ char ch = s.charAt(left);
+ map.put(ch, map.getOrDefault(ch, 0) + 1);
+ while (map.size() > k) {
+ char chright = s.charAt(right);
+ map.put(chright, map.get(chright) - 1);
+ if (map.get(chright) <= 0) {
+ map.remove(chright);
+ }
+ right++;
+ }
+ left++;
+ result = Math.max(result, left - right);
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LinkedListRemoveDuplicates.java b/src/geeksforgeeks/LinkedListRemoveDuplicates.java
new file mode 100644
index 0000000..029e418
--- /dev/null
+++ b/src/geeksforgeeks/LinkedListRemoveDuplicates.java
@@ -0,0 +1,36 @@
+package geeksforgeeks;
+
+class LinkedListRemoveDuplicate{
+ /**
+ * Method to remove duplicates from Linked list
+ * when no additional buffer is allowed.
+ *
+ * Time Complexity : O(n^2)
+ * Space Complexity : O(1)
+ *
+ * @param head
+ */
+ public static void removeDuplicatesWithoutBuffer(LinkedListNode head) {
+ /* If head is null, stop processing */
+ if (head == null) {
+ return;
+ }
+ /* We will need two pointers here i.e current and runner.
+ * When current is pointing to a node, move runner through
+ * rest of the list, checking for duplicates */
+ LinkedListNode current = head;
+ while (current != null) {
+ /* Have runner point to current node */
+ LinkedListNode runner = current;
+ while (runner.next != null) {
+ /* If it is duplicate, jump runner over the node */
+ if (runner.next.data == current.data) {
+ runner.next = runner.next.next;
+ } else {
+ runner = runner.next;
+ }
+ }
+ current = current.next;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LiveCellDeadCellGame.java b/src/geeksforgeeks/LiveCellDeadCellGame.java
new file mode 100644
index 0000000..9ec83b4
--- /dev/null
+++ b/src/geeksforgeeks/LiveCellDeadCellGame.java
@@ -0,0 +1,37 @@
+package geeksforgeeks;
+
+//https://leetcode.com/problems/game-of-life/discuss/73366/Clean-O(1)-space-O(mn)-time-Java-Solution
+public class LiveCellDeadCellGame {
+ public void gameOfLife(int[][] board) {
+ int[][] dir = { { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, -1 }, { 0, 1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } };
+ int row = board.length;
+ int col = board[0].length;
+ for (int i = 0; i < board.length; i++) {
+ for (int j = 0; j < board[0].length; j++) {
+ int liveCells = 0;
+ for (int k = 0; k < dir.length; k++) {
+ if (i + dir[k][0] >= row || j + dir[k][1] >= col || i + dir[k][0] < 0 || j + dir[k][1] < 0) {
+ continue;
+ }
+ if (board[i + dir[k][0]][j + dir[k][1]] == 1 || board[i + dir[k][0]][j + dir[k][1]] == 2) {
+ liveCells++;
+ }
+ }
+
+ if (board[i][j] == 0 && liveCells == 3) {
+ board[i][j] = 3;
+ }
+ if (board[i][j] == 1 && (liveCells < 2 || liveCells > 3)) {
+ board[i][j] = 2;
+ }
+ }
+ }
+
+ for (int i = 0; i < board.length; i++) {
+ for (int j = 0; j < board[0].length; j++) {
+ board[i][j] %= 2;
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LongestConsequtiveSequence.java b/src/geeksforgeeks/LongestConsequtiveSequence.java
new file mode 100644
index 0000000..1eea844
--- /dev/null
+++ b/src/geeksforgeeks/LongestConsequtiveSequence.java
@@ -0,0 +1,71 @@
+package geeksforgeeks;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
+ *
+ * Your algorithm should run in O(n) complexity.
+ * Input: [100, 4, 200, 1, 3, 2]
+ * Output: 4
+ * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
+ */
+class LongestConsequtiveSequence {
+
+ public int longestConsecutive(int[] nums) {
+ if (nums.length == 0) {
+ return 0;
+ }
+ int max = 1;
+ Set set = new HashSet<>();
+ for (int i : nums) {
+ set.add(i);
+ }
+ // have a set, go backwards and remove entries, go forward remove entries and calculate Max
+ // without removing entries, runtime would be too much
+ for (Integer i : nums) {
+ int num = i;
+ int count = 1;
+ // looking left;
+ while (set.contains(--num)) {
+ count++;
+ set.remove(num);
+ }
+ num = i;
+ while (set.contains(++num)) {
+ count++;
+ set.remove(num);
+ }
+
+ max = Math.max(max, count);
+ }
+
+ return max;
+ }
+
+ public int longestConsecutiveSorting(int[] nums) {
+ if (nums == null || nums.length == 0)
+ return 0;
+
+ Arrays.sort(nums);
+
+ int longestStreak = 1;
+ int currentStreak = 1;
+
+ for (int i = 0; i < nums.length - 1; i++) {
+ if (nums[i] != nums[i+1]) { // avoid duplicate
+ if (nums[i] + 1 == nums[i+1]) { // if increasing increase streak count else reset
+ currentStreak += 1;
+ }
+ else {
+ longestStreak = Math.max(longestStreak, currentStreak);
+ currentStreak = 1;
+ }
+ }
+ }
+
+ return Math.max(longestStreak, currentStreak);
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LongestRepeatCharReplace.java b/src/geeksforgeeks/LongestRepeatCharReplace.java
new file mode 100644
index 0000000..4cf5039
--- /dev/null
+++ b/src/geeksforgeeks/LongestRepeatCharReplace.java
@@ -0,0 +1,47 @@
+package geeksforgeeks;
+
+// you can perform at most k operations on that string.
+// In one operation, you can choose any character of the string and change it to any other uppercase English character.
+// Find the length of the longest sub-string containing all repeating letters
+// s = "ABAB", k = 2
+// Output:
+// 4
+// Explanation:
+// Replace the two 'A's with two 'B's or vice versa.
+public class LongestRepeatCharReplace {
+ public int characterReplacement(String s, int k) {
+ if(s==null || s.length()==0) return 0;
+
+ int[] cache= new int[26];
+ int left=0;
+ int right=0;
+ int result=0;
+ int maxOccured=0;
+ while(right 0, then we have characters in the window that are NOT the character that occurs the most.
+ // end-start+1-maxCount is equal to exactly the # of characters that are NOT the character that occurs the most in that window.
+ //Example: For a window "xxxyz", end-start+1-maxCount would equal 2. (maxCount is 3 and there are 2 characters here, "y" and "z" that are not "x" in the window.)
+ // We are allowed to have at most k replacements in the window, so when end-start+1-maxCount > k,
+ //then there are more characters in the window than we can replace, and we need to shrink the window.
+ // If we have window with "xxxy" and k = 1, that's fine because end-start+1-maxCount = 1, which is not > k. maxLength gets updated to 4.
+ // But if we then find a "z" after, like "xxxyz", then we need to shrink the window because now end-start+1-maxCount = 2, and 2 > 1. The window becomes "xxyz".
+ if(right-left+1-maxOccured > k){
+ char leftchr= s.charAt(left);
+ --cache[leftchr-'A'];
+ left++;
+ }
+ result=Math.max(result, right-left+1);
+ right++;
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/LongestSpanWithSameSumArray.java b/src/geeksforgeeks/LongestSpanWithSameSumArray.java
index 71fe75b..dee75cb 100644
--- a/src/geeksforgeeks/LongestSpanWithSameSumArray.java
+++ b/src/geeksforgeeks/LongestSpanWithSameSumArray.java
@@ -1,42 +1,69 @@
package geeksforgeeks;
-import java.util.HashMap;
-
/*https://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/*/
class LongestSpanWithSameSumArray {
static int longestCommonSum(int[] arr1, int[] arr2, int n) {
- int[] arr = new int[n];
- for (int i = 0; i < n; i++)
- arr[i] = arr1[i] - arr2[i];
+ int maxLen = 0;
+
+ // Initialize prefix sums of two arrays
+ int preSum1 = 0, preSum2 = 0;
- HashMap map = new HashMap<>();
+ // Create an array to store staring and ending
+ // indexes of all possible diff values. diff[i]
+ // would store starting and ending points for
+ // difference "i-n"
- int sum = 0;
- int maxLength = 0;
+ int diff[] = new int[2*n+1];
- for (int i = 0; i < n; i++) {
+ // Initialize all starting and ending values as -1.
+ for (int i = 0; i < diff.length; i++) {
+ diff[i] = -1;
+ }
- sum += arr[i];
+ // Traverse both arrays
+ for (int i=0; i maxLen)
+ maxLen = len;
+ }
}
- return maxLength;
+ return maxLen;
}
public static void main(String args[]) {
/* int[] arr1 = {0, 1, 0, 1, 1, 1, 1};
int[] arr2 = {1, 1, 1, 1, 1, 0, 1};*/
- int arr1[] = {0, 1, 0, 0, 1, 1, 1, 0};
- int arr2[] = {1, 1, 1, 1, 1, 1, 0, 1};
+ int arr1[] = { 0, 1, 0, 0, 1, 1, 1, 0 };
+ int arr2[] = { 1, 1, 1, 1, 1, 1, 0, 1 };
//{-1,0,-1,0,0,1,0}
int n = arr1.length;
System.out.println(longestCommonSum(arr1, arr2, n));
diff --git a/src/geeksforgeeks/LongestSubArraySumUtmostK.java b/src/geeksforgeeks/LongestSubArraySumUtmostK.java
index 43e306e..093bb04 100644
--- a/src/geeksforgeeks/LongestSubArraySumUtmostK.java
+++ b/src/geeksforgeeks/LongestSubArraySumUtmostK.java
@@ -6,31 +6,28 @@
// array is non-negative
class LongestSubArraySumUtmostK {
- public static int atMostSum(int arr[], int n, int target) {
+ public static int utMostSum(int arr[], int n, int target) {
int sum = 0;
int count = 0;
int maxCount = 0;
for (int i = 0; i < n; i++) {
- //7
if ((sum + arr[i]) <= target) {
sum += arr[i];
count++;
} else if (sum != 0) {
sum = sum - arr[i - count] + arr[i];
}
-
maxCount = Math.max(count, maxCount);
}
return maxCount;
}
public static void main(String[] args) {
- int arr[] = {1, 2, 1, 0, 1, 1, 0};
+ int arr[] = { 1, 2, 1, 0, 1, 1, 0 };
int n = arr.length;
int k = 4;
- System.out.print(atMostSum(arr, n, k));
-
+ System.out.print(utMostSum(arr, n, k));
}
}
diff --git a/src/geeksforgeeks/LongestUniqueSubstring.java b/src/geeksforgeeks/LongestUniqueSubstring.java
index 289e2b0..21b6f58 100644
--- a/src/geeksforgeeks/LongestUniqueSubstring.java
+++ b/src/geeksforgeeks/LongestUniqueSubstring.java
@@ -5,6 +5,7 @@
/*https://leetcode.com/problems/longest-substring-without-repeating-characters/*/
public class LongestUniqueSubstring {
+
public static int lengthOfLongestSubstring(String s) {
Map map = new HashMap<>();
int begin = 0;
@@ -15,12 +16,16 @@ public static int lengthOfLongestSubstring(String s) {
while (end < s.length()) {
char c = s.charAt(end);
map.put(c, map.getOrDefault(c, 0) + 1);
- if (map.get(c) > 1) counter++;
+ if (map.get(c) > 1) {
+ counter++;
+ }
end++;
while (counter > 0) {
char charTemp = s.charAt(begin);
- if (map.get(charTemp) > 1) counter--;
+ if (map.get(charTemp) > 1) {
+ counter--;
+ }
map.put(charTemp, map.get(charTemp) - 1);
begin++;
}
@@ -28,8 +33,21 @@ public static int lengthOfLongestSubstring(String s) {
}
return result;
}
+ public static int lengthOfLongestSubstringOpt(String s) {
+ int res = 0, n = s.length();
+ int[] arr = new int[256];
+ int startIndex=0;
+ for(int curr=0;curr next index, so that we can start from here
+ arr[s.charAt(curr)] = curr+1;
+ }
+ return res;
+ }
public static void main(String[] args) {
- System.out.println(lengthOfLongestSubstring("abccbcbb"));
+ System.out.println(lengthOfLongestSubstringOpt("pwwkew"));
}
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MajorityVoting.java b/src/geeksforgeeks/MajorityVoting.java
index d857bdb..291132a 100644
--- a/src/geeksforgeeks/MajorityVoting.java
+++ b/src/geeksforgeeks/MajorityVoting.java
@@ -7,24 +7,25 @@
public class MajorityVoting {
public static List majorityElementII(int[] nums) {
- if (nums == null || nums.length == 0)
+ if (nums == null || nums.length == 0) {
return new ArrayList<>();
+ }
List result = new ArrayList<>();
- int number1 = nums[0];
- int number2 = nums[0];
+ int candidate1 = nums[0];
+ int candidate2 = nums[0];
int count1 = 0;
int count2 = 0;
int len = nums.length;
for (int i = 0; i < len; i++) {
- if (nums[i] == number1)
+ if (nums[i] == candidate1) {
count1++;
- else if (nums[i] == number2)
+ } else if (nums[i] == candidate2) {
count2++;
- else if (count1 == 0) {
- number1 = nums[i];
+ } else if (count1 == 0) {
+ candidate1 = nums[i];
count1 = 1;
} else if (count2 == 0) {
- number2 = nums[i];
+ candidate2 = nums[i];
count2 = 1;
} else {
count1--;
@@ -34,29 +35,37 @@ else if (count1 == 0) {
count1 = 0;
count2 = 0;
for (int i = 0; i < len; i++) {
- if (nums[i] == number1)
+ if (nums[i] == candidate1) {
count1++;
- else if (nums[i] == number2)
+ } else if (nums[i] == candidate2) {
count2++;
+ }
+ }
+ if (count1 > len / 3) {
+ result.add(candidate1);
+ }
+ if (count2 > len / 3) {
+ result.add(candidate2);
}
- if (count1 > len / 3)
- result.add(number1);
- if (count2 > len / 3)
- result.add(number2);
return result;
}
public static int majorityElementI(int[] nums) {
- int count = 0;
- int candidate = 0;
+ int count = 1;
+ int candidate = nums[0];
int majority = nums.length / 2;
- for (int num : nums) {
- if (count == 0) {
- candidate = num;
+ for (int i = 1; i < nums.length; i++) {
+ if (candidate == nums[i]) {
+ count++;
+ } else if (count == 0) {
+ count++;
+ candidate = nums[i];
+ } else {
+ count--;
}
- count += (num == candidate) ? 1 : -1;
}
+ //what if array is even and it has many elements
count = 0;
for (int num : nums) {
if (num == candidate) {
@@ -68,9 +77,10 @@ public static int majorityElementI(int[] nums) {
}
public static void main(String[] args) {
- int[] arr = {1, 1, 1, 1, 1, 2, 2, 4, 4, 4, 4, 4, 2, 2};
+ int[] arr = { 1, 1, 1, 1, 1, 2, 2, 4, 4, 4, 4, 4, 2, 2 };
System.out.println(majorityElementI(arr));
System.out.println(majorityElementII(arr));
+
}
}
diff --git a/src/geeksforgeeks/MakeAnArrayPalindrome.java b/src/geeksforgeeks/MakeAnArrayPalindrome.java
index 775cb12..8234a81 100644
--- a/src/geeksforgeeks/MakeAnArrayPalindrome.java
+++ b/src/geeksforgeeks/MakeAnArrayPalindrome.java
@@ -34,7 +34,7 @@ else if (arr[i] > arr[j]) {
}
public static void main(String[] args) {
- int arr[] = new int[]{1, 4, 5, 9, 1};
+ int arr[] = new int[] { 1, 4, 5, 9, 1 };
System.out.println("Count of minimum operations is " + findMinOps(arr, arr.length));
}
diff --git a/src/geeksforgeeks/MatrixRowWithMax1.java b/src/geeksforgeeks/MatrixRowWithMax1.java
index c71f828..0a278e9 100644
--- a/src/geeksforgeeks/MatrixRowWithMax1.java
+++ b/src/geeksforgeeks/MatrixRowWithMax1.java
@@ -6,7 +6,7 @@
public class MatrixRowWithMax1 {
public static void main(String[] args) {
- int[][] mat = {{0, 0, 0, 1}, {0, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0, 0}};
+ int[][] mat = { { 0, 0, 0, 1 }, { 0, 1, 1, 1 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 } };
System.out.println(rowWithMax1s(mat));
}
@@ -17,8 +17,9 @@ static int rowWithMax1s(int mat[][]) {
int max_row_index = 0;
int j = findFirstIndex(mat[0], 0, C - 1);
- if (j == -1)
+ if (j == -1) {
j = C - 1;
+ }
for (int i = 1; i < R; i++) {
while (j >= 0 && mat[i][j] == 1) {
@@ -33,14 +34,13 @@ static int findFirstIndex(int arr[], int low, int high) {
if (high >= low) {
int mid = low + (high - low) / 2;
- if ((mid == 0 || (arr[mid - 1] == 0)) && arr[mid] == 1)
+ if ((mid == 0 || (arr[mid - 1] == 0)) && arr[mid] == 1) {
return mid;
-
- else if (arr[mid] == 0)
+ } else if (arr[mid] == 0) {
return findFirstIndex(arr, (mid + 1), high);
-
- else
+ } else {
return findFirstIndex(arr, low, (mid - 1));
+ }
}
return -1;
}
diff --git a/src/geeksforgeeks/MaxDistinctElementAfterKRemoval.java b/src/geeksforgeeks/MaxDistinctElementAfterKRemoval.java
new file mode 100644
index 0000000..97589ed
--- /dev/null
+++ b/src/geeksforgeeks/MaxDistinctElementAfterKRemoval.java
@@ -0,0 +1,117 @@
+package geeksforgeeks;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.PriorityQueue;
+
+/**
+ * Given an array arr[] containing n elements. The problem is to find maximum number of distinct elements (non-repeating) after removing k elements from the array.
+ * Input : arr[] = {5, 7, 5, 5, 1, 2, 2}, k = 3
+ * Output : 4
+ *
+ * Remove 2 occurrences of element 5 and
+ * 1 occurrence of element 2.
+ *
+ * Input : arr[] = {1, 2, 3, 4, 5, 6, 7}, k = 5
+ * Output : 2
+ */
+public class MaxDistinctElementAfterKRemoval {
+ // after removing k elements
+
+ /**
+ * Create a hash table to store the frequency of each element.
+ * Insert frequency of each element in a max heap.
+ * Now, perform the following operation k times.
+ * Remove an element from the max heap. Decrement its value by 1. After this if element is not equal to 0, then again push the element in the max heap.
+ * @param arr
+ * @param n
+ * @param k
+ * @return
+ */
+ static int maxDistinctNum(int[] arr, int n, int k)
+ {
+ // hash map to store
+ // frequency of each element
+ HashMap map = new HashMap<>();
+
+ // priority_queue 'pq' implemented as
+ // max heap
+ PriorityQueue pq =
+ new PriorityQueue<>(Collections.reverseOrder());
+
+ // storing frequency of each element in map
+ for (int i = 0; i < n; i++) {
+ map.put(arr[i], map.getOrDefault(arr[i],0)+1);
+ }
+
+ // inserting frequency of each element in 'pq'
+ for (Map.Entry entry : map.entrySet()) {
+ pq.add(entry.getValue());
+ }
+
+ while (k > 0) {
+ // get the top element of 'pq'
+ int temp = pq.poll();
+
+ // decrement the popped element by 1
+ temp--;
+
+ // if true, then push the element in 'pq'
+ if (temp > 0)
+ pq.add(temp);
+ k--;
+ }
+
+ // Count all those elements that appear
+ // once after above operations.
+ int res = 0;
+ while (pq.size() != 0) {
+ pq.poll();
+ res++;
+ }
+
+ return res;
+ }
+
+ /**
+ * Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
+ * Input: arr = [5,5,4], k = 1
+ * Output: 1
+ * Explanation: Remove the single 4, only 5 is left.
+ *
+ * Input: arr = [4,3,1,1,3,3,2], k = 3
+ * Output: 2
+ * Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
+ * @param arr
+ * @param k
+ * @return
+ */
+ public int findLeastNumOfUniqueInts(int[] arr, int k) {
+ if(arr.length==0) return 0;
+ Map frequencyMap= new HashMap<>();
+
+ for(int i: arr){
+ frequencyMap.put(i,frequencyMap.getOrDefault(i,0)+1);
+ }
+
+ PriorityQueue maxQueue= new PriorityQueue<>();
+
+ for(Map.Entry entry: frequencyMap.entrySet()){
+ maxQueue.offer(entry.getValue());
+ }
+
+ while(k-- >0){
+ int temp= maxQueue.poll();
+ temp-=1;
+ if(temp>0) maxQueue.offer(temp);
+
+ }
+
+ int result=0;
+ while(!maxQueue.isEmpty()){
+ result++;
+ }
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MaxFreqStack.java b/src/geeksforgeeks/MaxFreqStack.java
new file mode 100644
index 0000000..624051d
--- /dev/null
+++ b/src/geeksforgeeks/MaxFreqStack.java
@@ -0,0 +1,74 @@
+package geeksforgeeks;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.PriorityQueue;
+
+/**
+ * FreqStack has two functions:
+ *
+ * push(int x), which pushes an integer x onto the stack.
+ * pop(), which removes and returns the most frequent element in the stack.
+ * If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.
+ * ["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],
+ * [[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
+ * Output: [null,null,null,null,null,null,null,5,7,5,4]
+ * Explanation:
+ * After making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top. Then:
+ *
+ * pop() -> returns 5, as 5 is the most frequent.
+ * The stack becomes [5,7,5,7,4].
+ *
+ * pop() -> returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top.
+ * The stack becomes [5,7,5,4].
+ *
+ * pop() -> returns 5.
+ * The stack becomes [5,7,4].
+ *
+ * pop() -> returns 4.
+ * The stack becomes [5,7].
+ */
+public class MaxFreqStack {
+
+ PriorityQueue maxQueue;
+ Map hashMap;
+ int sequence = 0;
+
+ public MaxFreqStack() {
+
+ maxQueue= new PriorityQueue<>((a,b)->{
+ if(a.frequency==b.frequency){
+ return Integer.compare(b.sequence,a.sequence);
+ }
+ return Integer.compare(b.frequency,a.frequency);
+ });
+ hashMap= new HashMap<>();
+ }
+
+ public void push(int x) {
+ hashMap.put(x, hashMap.getOrDefault(x, 0) + 1);
+ maxQueue.offer(new EntryStack(x, hashMap.get(x), sequence++));
+ }
+
+ public int pop() {
+ EntryStack temp = maxQueue.poll();
+ hashMap.put(temp.val, temp.frequency - 1);
+
+ return temp.val;
+ }
+}
+
+// 1. val = value of the number
+// 2. frequency = current frequency of the number when it was pushed to the heap
+// 3. sequenceNumber = a sequence number, to know what number came first
+class EntryStack {
+ int val;
+ int frequency;
+ int sequence;
+
+ public EntryStack(int val, int frequency, int sequence) {
+ this.val = val;
+ this.frequency = frequency;
+ this.sequence = sequence;
+ }
+}
diff --git a/src/geeksforgeeks/MaxHistogram.java b/src/geeksforgeeks/MaxHistogram.java
new file mode 100644
index 0000000..a860ddd
--- /dev/null
+++ b/src/geeksforgeeks/MaxHistogram.java
@@ -0,0 +1,68 @@
+package geeksforgeeks;
+
+import java.util.Arrays;
+
+/**
+ * https://leetcode.com/problems/largest-rectangle-in-histogram/
+ */
+
+public class MaxHistogram {
+
+ //For any bar i the maximum rectangle is of width r - l - 1
+ // where r - is the last coordinate of the bar to the right with height h[r] >= h[i] and
+ // l - is the last coordinate of the bar to the left which height h[l] >= h[i]
+ //So if for any i coordinate we know his utmost higher (or of the same height) neighbors to the right and to the left,
+ // we can easily find the largest rectangle: maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
+
+ //The main trick is how to effectively calculate lessFromRight and lessFromLeft arrays.
+ // The trivial solution is to use O(n^2) solution and for each i element
+ // first find his left/right neighbour in the second inner loop just iterating back or forward:
+ public static int largestRectangleArea(int[] height) {
+ if (height == null || height.length == 0) {
+ return 0;
+ }
+ int[] lessFromLeft = new int[height.length]; // idx of the first bar the left that is lower than current
+ int[] lessFromRight = new int[height.length]; // idx of the first bar the right that is lower than current
+ lessFromRight[height.length - 1] = height.length;
+ lessFromLeft[0] = -1;
+
+ // for example in order to lessFromLeft[i]; if height[i - 1] < height[i] then left[i] = i - 1;
+ // other wise we do not need to start scan from i - 1; we can start the scan from lessFromLeft[i - 1],
+ // because since lessFromLeft[i - 1] is the first position to the left of i - 1 that have height less than height[i - 1],
+ // and we know height[i - 1] >= height[i]; so lessFromLeft[i] must be at the left or at lessFromLeft[i - 1]; similar for the right array;
+ for (int i = 1; i < height.length; i++) {
+ int p = i - 1;
+
+ while (p >= 0 && height[p] >= height[i]) {
+ p = lessFromLeft[p];
+ }
+ lessFromLeft[i] = p;
+ }
+
+ for (int i = height.length - 2; i >= 0; i--) {
+ int p = i + 1;
+
+ while (p < height.length && height[p] >= height[i]) {
+ p = lessFromRight[p];
+ }
+ lessFromRight[i] = p;
+ }
+ // after both the loop ends, this is the output of left and right
+ // input [2, 1, 5, 6, 2, 3]
+ // 0, 1, ,2 3, 4, 5
+ // left [-1, -1, 1, 2, 1, 4] => indexes of elements
+ // right [1, 6, 4, 4, 6, 6]
+ int maxArea = 0;
+ for (int i = 0; i < height.length; i++) {
+ maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
+ }
+ System.out.println(Arrays.toString(lessFromLeft));
+ System.out.println(Arrays.toString(lessFromRight));
+ return maxArea;
+ }
+
+ public static void main(String[] args) {
+ int[] arr = new int[] { 2, 1, 5, 6, 2, 3 };
+ System.out.println(largestRectangleArea(arr));
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MaxProductString.java b/src/geeksforgeeks/MaxProductString.java
new file mode 100644
index 0000000..54bb75d
--- /dev/null
+++ b/src/geeksforgeeks/MaxProductString.java
@@ -0,0 +1,57 @@
+package geeksforgeeks;
+
+/**
+ * Given a string array words, find the maximum value of length(word[i]) * length(word[j])
+ * where the two words do not share common letters.
+ * You may assume that each word will contain only lower case letters
+ * Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
+ * Output: 16
+ * Explanation: The two words can be "abcw", "xtfn".
+ *
+ * Input: ["a","aa","aaa","aaaa"]
+ * Output: 0
+ * Explanation: No such pair of words.
+ */
+public class MaxProductString {
+ public int maxProduct(String[] words) {
+ int[] checker = new int[words.length];
+ int max = 0;
+ // populating the checker array with their respective numbers
+ for (int i = 0; i < checker.length; i++) {
+ int num = 0;
+ for (int j = 0; j < words[i].length(); j++) {
+ // we are making char index in bit to be set
+ // a 1->1 making first bit marked
+ // b 2->10
+ // c 4->100
+ // ab 3->11 // making first and secind marked
+ // ac 5->101
+ // abc 7->111
+ // az 33554433->10000000000000000000000001
+
+ num |= 1 << (words[i].charAt(j) - 'a');
+ System.out.println(words[i].charAt(j)+"->"+num+ "->"+Integer.toBinaryString(num) );
+ }
+
+ checker[i] = num;
+ }
+
+ for (int i = 0; i < words.length; i++) {
+ for (int j = i + 1; j < words.length; j++) {
+ // abcd efgd
+ // 11110000 -> abcd
+ // 00011110 -> efgd
+ // and-ing these two might say if even a single char is present in other
+ if ((checker[i] & checker[j]) == 0) //checking if the two strings have common character
+ max = Math.max(max, words[i].length() * words[j].length());
+ }
+ }
+ System.out.println(max);
+ return max;
+ }
+
+
+ public static void main(String[] args) {
+ new MaxProductString().maxProduct(new String[]{"abcw", "baz", "foo", "bar", "xtfn", "abcdef"});
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MaxSoldiers.java b/src/geeksforgeeks/MaxSoldiers.java
new file mode 100644
index 0000000..0866e7a
--- /dev/null
+++ b/src/geeksforgeeks/MaxSoldiers.java
@@ -0,0 +1,46 @@
+package geeksforgeeks;
+
+public class MaxSoldiers {
+ class Pair{
+ int row;
+ int soldiers;
+ Pair(int row, int soldiers){
+ this.row=row;
+ this.soldiers=soldiers;
+ }
+ }
+
+ public int[] kWeakestRows(int[][] mat, int k) {
+ int[] result= new int[k];
+ PriorityQueue queue= new PriorityQueue<>((a,b)->a.soldiers==b.soldiers?Integer.compare(a.row,b.row):Integer.compare(a.soldiers,b.soldiers));
+ int i=0;
+ int soldiers=0;
+ for(int []rows: mat){
+ int temp= binarySearchUtil(rows, 0, rows.length);
+ queue.offer(new Pair(i,temp));
+ i++;
+ }
+ int ind=0;
+ while(ind map= new HashMap<>();
+ Queue stack=new LinkedList();
+ stack.offer(root);
+ map.put(root,1); // if we are assigning head as 0 then the fourmula is left=>2*n+1, right=> 2*n+2
+ while(!stack.isEmpty()){
+ int width= stack.size();
+ int start=0;
+ int end=0;
+ for(int i=0;i 0)
- previousSum += diff;
- else
- previousSum = diff;
-
- if (previousSum > maxSum)
- maxSum = previousSum;
+ static int maxDiff(int arr[], int arr_size) {
+ int maxDiff = 0;
+ int minElement = arr[0];
+ for (int i = 1; i < arr_size; i++) {
+ if (arr[i] - minElement > maxDiff) {
+ maxDiff = arr[i] - minElement;
+ }
+ if (arr[i] < minElement) {
+ minElement = arr[i];
+ }
}
- return maxSum;
+ return maxDiff;
+ }
+ static int maxDiff1(int arr[], int arr_size) {
+ int maxDiff = 0;
+ int minElement = arr[0];
+ for (int i = 1; i < arr_size; i++) {
+ if (arr[i] - minElement > maxDiff) {
+ maxDiff = arr[i] - minElement;
+ }
+ if (arr[i] < minElement) {
+ minElement = arr[i];
+ }
+ }
+ return maxDiff;
}
-
public static void main(String[] args) {
- int arr[] = {2, 4, 1, 3, 10, 8, 5};
- int n = arr.length;
-
- System.out.print("Maximum difference is " + maxDiff(arr, n));
+ int arr[] = { 2, 4, 1, 3, 10, 8, 5 };
+ System.out.println("Maximum difference is " + maxDiff(arr, arr.length));
}
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MaximumGap.java b/src/geeksforgeeks/MaximumGap.java
new file mode 100644
index 0000000..64342fd
--- /dev/null
+++ b/src/geeksforgeeks/MaximumGap.java
@@ -0,0 +1,70 @@
+package geeksforgeeks;
+
+/**
+ * Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
+Return 0 if the array contains less than 2 elements.
+Input: [3,6,9,1]
+Output: 3
+Explanation: The sorted form of the array is [1,3,6,9], either
+ (3,6) or (6,9) has the maximum difference 3.
+
+
+trick is to do in O(N)= > Radix sort
+ */
+public class MaximumGap {
+ // The first step is to find the maximum value in nums array, it will
+ // be the threshold to end while loop.
+ // Then use the radix sort algorithm to sort based on each digit from Least Significant Bit
+ // (LSB) to Most Significant Bit (MSB), that's exactly what's showing
+ // in the link.
+ // (nums[i] / exp) % 10 is used to get the digit, for each digit, basically the digit itself serves as the index to
+ // access the count array. Count array stores the index to access aux
+ // array which stores the numbers after sorting based on the current
+ // digit.
+ // Finally, find the maximum gap from sorted array.
+ // Time and space complexities are both O(n). (Actually time is O(10n) at worst case for Integer.MAX_VALUE 2147483647)
+ public int maximumGap(int[] nums) {
+ if (nums == null || nums.length < 2) {
+ return 0;
+ }
+
+ // m is the maximal number in nums
+ int m = nums[0];
+ for (int i = 1; i < nums.length; i++) {
+ m = Math.max(m, nums[i]);
+ }
+
+ int exp = 1; // 1, 10, 100, 1000 ...
+ int R = 10; // 10 digits
+
+ int[] aux = new int[nums.length];
+
+ while (m / exp > 0) { // Go through all digits from LSB to MSB
+ int[] count = new int[R];
+
+ for (int i = 0; i < nums.length; i++) {
+ count[(nums[i] / exp) % 10]++;
+ }
+
+ for (int i = 1; i < count.length; i++) {
+ count[i] += count[i - 1];
+ }
+
+ for (int i = nums.length - 1; i >= 0; i--) {
+ aux[--count[(nums[i] / exp) % 10]] = nums[i];
+ }
+
+ for (int i = 0; i < nums.length; i++) {
+ nums[i] = aux[i];
+ }
+ exp *= 10;
+ }
+
+ int max = 0;
+ for (int i = 1; i < aux.length; i++) {
+ max = Math.max(max, aux[i] - aux[i - 1]);
+ }
+
+ return max;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MaximumProductSubarray.java b/src/geeksforgeeks/MaximumProductSubarray.java
new file mode 100644
index 0000000..025e49e
--- /dev/null
+++ b/src/geeksforgeeks/MaximumProductSubarray.java
@@ -0,0 +1,63 @@
+package geeksforgeeks;
+
+/**
+ * https://www.geeksforgeeks.org/maximum-product-subarray/
+ */
+public class MaximumProductSubarray {
+
+ // 1, -2, -3, 0, 8, 7, -2
+ public static int maxProductSubArray(int[] A) {
+
+ if (A.length == 0) {
+ return 0;
+ }
+
+ int maxHerePre = A[0];
+ int minHerePre = A[0];
+ int maxsofar = A[0];
+
+ for (int i = 1; i < A.length; i++) {
+ int maxHere = Math.max(Math.max(maxHerePre * A[i], minHerePre * A[i]), A[i]);
+ int minHere = Math.min(Math.min(maxHerePre * A[i], minHerePre * A[i]), A[i]);
+ maxsofar = Math.max(maxHere, maxsofar);
+ maxHerePre = maxHere;
+ minHerePre = minHere;
+ }
+ return maxsofar;
+ }
+
+ public static int maxSumSubArray(int[] arr) {
+
+ int max = Integer.MIN_VALUE;
+ int sum = 0;
+
+ for (int i = 0; i < arr.length; i++) {
+ sum = sum + arr[i];
+ if (sum < 0) {
+ //get i if you want to get index of subarray
+ sum = 0;
+ }
+ max = Math.max(sum, max);
+ }
+ return sum;
+ }
+
+ public int maxSubArray(int[] nums) {
+ if(nums==null || nums.length==0) return 0;
+
+ int maxHere=0;
+ int max=Integer.MIN_VALUE;
+ for(int i:nums){
+ maxHere=Math.max(i,maxHere+i);
+ max= Math.max(maxHere, max);
+ }
+
+ return max;
+ }
+
+ public static void main(String[] args) {
+ int arr[] = { 1, -2, -3, 0, 8, 7, -2 };
+ System.out.println("Maximum Sub array sum is " + maxSumSubArray(arr));
+ System.out.println("Maximum Sub array product is " + maxProductSubArray(arr));
+ }
+}
diff --git a/src/geeksforgeeks/MaximumSubarray.java b/src/geeksforgeeks/MaximumSubarray.java
deleted file mode 100644
index 8d7a333..0000000
--- a/src/geeksforgeeks/MaximumSubarray.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package geeksforgeeks;
-
-/**
- * https://www.geeksforgeeks.org/maximum-product-subarray/
- */
-public class MaximumSubarray {
-
- public static int maxProductSubArray(int[] A) {
- if (A.length == 0) {
- return 0;
- }
-
- int maxHerePre = A[0];
- int minHerePre = A[0];
- int maxsofar = A[0];
-
- for (int i = 1; i < A.length; i++) {
- int maxHere = Math.max(Math.max(maxHerePre * A[i], minHerePre * A[i]), A[i]);
- int minHere = Math.min(Math.min(maxHerePre * A[i], minHerePre * A[i]), A[i]);
- maxsofar = Math.max(maxHere, maxsofar);
- maxHerePre = maxHere;
- minHerePre = minHere;
- }
- return maxsofar;
- }
-
- public static int maxSumSubArray(int[] nums) {
-
- int maxSoFar = nums[0];
- int maxEndingHere = nums[0];
-
- for (int i = 1; i < nums.length; i++) {
- maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]);
- maxSoFar = Math.max(maxSoFar, maxEndingHere);
- }
- return maxSoFar;
- }
-
-
- public static void main(String[] args) {
- int arr[] = {1, -2, -3, 0, 8, 7, -2};
- System.out.println("Maximum Sub array product is " + maxSumSubArray(arr));
- }
-
-}
diff --git a/src/geeksforgeeks/MaximumSubstringWithKDistinctChar.java b/src/geeksforgeeks/MaximumSubstringWithKDistinctChar.java
index 12f3007..65963f7 100644
--- a/src/geeksforgeeks/MaximumSubstringWithKDistinctChar.java
+++ b/src/geeksforgeeks/MaximumSubstringWithKDistinctChar.java
@@ -3,10 +3,16 @@
import java.util.HashMap;
import java.util.Map;
+/**
+ * https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
+ *
+ * https://www.lintcode.com/problem/longest-substring-with-at-most-two-distinct-characters/description
+ */
public class MaximumSubstringWithKDistinctChar {
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstringTwoDistinct("abaaaaacccddcc", 2));
+ //System.out.println(lengthOfLongestSubstringKDistinct("eqgkcwGFvjjmxutystqdfhuMblWbylgjxsxgnoh", 2));
}
public static int lengthOfLongestSubstringTwoDistinct(String s, int k) {
@@ -18,7 +24,9 @@ public static int lengthOfLongestSubstringTwoDistinct(String s, int k) {
while (end < s.length()) {
char c = s.charAt(end);
map.put(c, map.getOrDefault(c, 0) + 1);
- if (map.get(c) == 1) counter++;//new char
+ if (map.get(c) == 1) {
+ counter++;//new char
+ }
end++;
while (counter > k) {
char cTemp = s.charAt(start);
@@ -32,4 +40,36 @@ public static int lengthOfLongestSubstringTwoDistinct(String s, int k) {
}
return length;
}
+
+ // improvised solution
+ public static int lengthOfLongestSubstringKDistinct(String s, int k) {
+ if (s == null || s.isEmpty()) {
+ return 0;
+ }
+ if (k == 0) {
+ return 0;
+ }
+ int start = 0;
+ int maxCount = 0;
+ int[] arr = new int[26];
+ s = s.toLowerCase();
+ for (int i = 0; i < s.length(); i++) {
+
+ if (arr[s.charAt(i) - 'a'] == 0) {
+ k--;
+ }
+
+ arr[s.charAt(i) - 'a']++;
+ while (k == -1) {
+
+ arr[s.charAt(start) - 'a']--;
+ if (arr[s.charAt(start) - 'a'] == 0) {
+ k++;
+ }
+ start++;
+ }
+ maxCount = Math.max(maxCount, i - start);
+ }
+ return maxCount + 1;
+ }
}
diff --git a/src/geeksforgeeks/MaximumUnsortedSubarray.java b/src/geeksforgeeks/MaximumUnsortedSubarray.java
index 8cc830a..b9a436e 100644
--- a/src/geeksforgeeks/MaximumUnsortedSubarray.java
+++ b/src/geeksforgeeks/MaximumUnsortedSubarray.java
@@ -4,12 +4,22 @@
import java.util.Arrays;
import java.util.List;
-//https://www.interviewbit.com/problems/maximum-unsorted-subarray/#
+//https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
+/**
+ * Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
+ *
+ * You need to find the shortest such subarray and output its length.
+ *
+ * Example 1:
+ * Input: [2, 6, 4, 8, 10, 9, 15]
+ * Output: 5
+ * Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
+ */
public class MaximumUnsortedSubarray {
- public static ArrayList subarraySort(ArrayList A) {
+ public static ArrayList subarraySort(final ArrayList A) {
- ArrayList list = new ArrayList<>();
+ final ArrayList list = new ArrayList<>();
int start = -1;
int end = -1;
@@ -34,7 +44,13 @@ public static ArrayList subarraySort(ArrayList A) {
break;
}
}
-
+ // [1, 3, 2, 0, -1, 7, 10]
+ // the initial finding gives you 3 and -1 however the original sort array is
+ // [1, -1, 0, 2, 3, 7, 10],
+ //The problem here is that the smallest number of our subarray is ‘-1’
+ // which dictates that we need to include more numbers from the beginning of the array
+ // We will have a similar problem
+ //if the maximum of the subarray is bigger than some elements at the end of the array
// find min and max in the range [start, end]
int min = A.get(start);
int max = A.get(start);
@@ -63,11 +79,12 @@ public static ArrayList subarraySort(ArrayList A) {
return list;
}
- public static void main(String[] args) {
+ public static void main(final String[] args) {
//1, 1, 10, 10, 15, 10, 15, 10,10, 15, 10, 15
- //(1, 3, 2, 4, 5)));
+ //(1, 3, 2, 4, 5);
//4, 15, 4, 4, 15, 18, 20
- List result = subarraySort(new ArrayList<>(Arrays.asList(4, 15, 4, 4, 15, 18, 20)));
+ //2, 6, 1, 8, 10, 9, 15
+ final List result = subarraySort(new ArrayList<>(Arrays.asList(4, 15, 4, 4, 15, 18, 20)));
result.stream().forEach(System.out::println);
}
}
diff --git a/src/geeksforgeeks/MedianOfKWindow.java b/src/geeksforgeeks/MedianOfKWindow.java
new file mode 100644
index 0000000..2e3ad95
--- /dev/null
+++ b/src/geeksforgeeks/MedianOfKWindow.java
@@ -0,0 +1,46 @@
+package geeksforgeeks;
+
+public class MedianOfKWindow {
+ public double[] medianSlidingWindow(int[] nums, int k) {
+ MedianQueue medianHeap= new MedianQueue();
+
+ double[] result= new double[nums.length-k+1];
+
+ int resultIndex=0;
+
+ for( int i=0;i minQueue= new PriorityQueue<>();
+ PriorityQueue maxQueue= new PriorityQueue<>(Collections.reverseOrder());
+
+ public void offer(int x){
+ maxQueue.offer(x);
+ minQueue.offer(maxQueue.poll());
+ if(maxQueue.size() minQueue.size() ? maxQueue.peek() : ((long)maxQueue.peek() + minQueue.peek()) * 0.5;
+ }
+ public int size(){
+ return minQueue.size() + maxQueue.size();
+ }
+
+ public boolean remove(int x){
+ return minQueue.remove(x) || maxQueue.remove(x);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MedianOfRunningIntegers.java b/src/geeksforgeeks/MedianOfRunningIntegers.java
index cef851b..d9f05ca 100644
--- a/src/geeksforgeeks/MedianOfRunningIntegers.java
+++ b/src/geeksforgeeks/MedianOfRunningIntegers.java
@@ -3,11 +3,20 @@
import java.util.Collections;
import java.util.PriorityQueue;
+/**
+ * https://leetcode.com/problems/find-median-from-data-stream/
+ */
public class MedianOfRunningIntegers {
PriorityQueue min = new PriorityQueue<>();
PriorityQueue max = new PriorityQueue<>(Collections.reverseOrder());
+ // 6,8,1,4,9,2,3,5
+ // median is a middle element in sorted array
+ // in a sorted array if we choose a point the immediate left to that point is maxLeft (max of all left)
+ // the immediate right to that point is minRight (min of all right)
+ // to mimic that here the right(max) values are stored in min heap
+ // the left(min) values are stored in maxheap
public void addNum(int num) {
max.offer(num);
min.offer(max.poll());
@@ -17,15 +26,16 @@ public void addNum(int num) {
}
public double findMedian() {
- if (max.size() == min.size())
+ if (max.size() == min.size()) {
return (max.peek() + min.peek()) / 2.0;
- else
+ } else {
return max.peek();
+ }
}
public static void main(String[] args) {
MedianOfRunningIntegers median = new MedianOfRunningIntegers();
- int A[] = {5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4};
+ int A[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 };
for (int num : A) {
median.addNum(num);
System.out.println(median.findMedian());
diff --git a/src/geeksforgeeks/MedianOfTwoSortedArrays.java b/src/geeksforgeeks/MedianOfTwoSortedArrays.java
new file mode 100644
index 0000000..7eae057
--- /dev/null
+++ b/src/geeksforgeeks/MedianOfTwoSortedArrays.java
@@ -0,0 +1,57 @@
+package geeksforgeeks;
+
+/**
+ * https://github.com/mission-peace/interview/blob/master/src/com/interview/binarysearch/MedianOfTwoSortedArrayOfDifferentLength.java
+ */
+public class MedianOfTwoSortedArrays {
+
+ public double findMedianSortedArrays(int input1[], int input2[]) {
+ //if input1 length is greater than switch them so that input1 is smaller than input2.
+ if (input1.length > input2.length) {
+ return findMedianSortedArrays(input2, input1);
+ }
+ int x = input1.length;
+ int y = input2.length;
+
+ int low = 0;
+ int high = x;
+ while (low <= high) {
+ int partitionX = (low + high) / 2;
+ int partitionY = (x + y + 1) / 2 - partitionX;
+
+ //if partitionX is 0 it means nothing is there on left side. Use -INF for maxLeftX
+ //if partitionX is length of input then there is nothing on right side. Use +INF for minRightX
+ int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : input1[partitionX - 1];
+ int minRightX = (partitionX == x) ? Integer.MAX_VALUE : input1[partitionX];
+
+ int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : input2[partitionY - 1];
+ int minRightY = (partitionY == y) ? Integer.MAX_VALUE : input2[partitionY];
+
+ if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
+ //We have partitioned array at correct place
+ // Now get max of left elements and min of right elements to get the median in case of even length combined array size
+ // or get max of left for odd length combined array size.
+ if ((x + y) % 2 == 0) {
+ return ((double) Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2;
+ } else {
+ return Math.max(maxLeftX, maxLeftY);
+ }
+ } else if (maxLeftX > minRightY) { //we are too far on right side for partitionX. Go on left side.
+ high = partitionX - 1;
+ } else { //we are too far on left side for partitionX. Go on right side.
+ low = partitionX + 1;
+ }
+ }
+
+ //Only we we can come here is if input arrays were not sorted. Throw in that scenario.
+ throw new IllegalArgumentException();
+ }
+
+ public static void main(String[] args) {
+ int[] x = { 1, 3, 8, 9, 15, 17 };
+ int[] y = { 7, 11, 18, 19, 21, 25 };
+ // 1,3,7,8,9,11,15,18,19,21,25
+ MedianOfTwoSortedArrays mm = new MedianOfTwoSortedArrays();
+ System.out.println(mm.findMedianSortedArrays(x, y));
+ }
+}
diff --git a/src/geeksforgeeks/MeetingRoomsII.java b/src/geeksforgeeks/MeetingRoomsII.java
new file mode 100644
index 0000000..bdab7a8
--- /dev/null
+++ b/src/geeksforgeeks/MeetingRoomsII.java
@@ -0,0 +1,66 @@
+package geeksforgeeks;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.PriorityQueue;
+
+/**
+ * https://www.lintcode.com/problem/meeting-rooms-ii/
+ */
+
+public class MeetingRoomsII {
+ /**
+ * @param intervals: an array of meeting time intervals
+ *
+ * @return: the minimum number of conference rooms required
+ */
+ // [(0,30),(5,10),(15,20)]
+ public int minMeetingRooms(List intervals) {
+ if (intervals == null || intervals.size() == 0) {
+ return -1;
+ }
+
+ Collections.sort(intervals, Comparator.comparingInt(a -> a.start));
+
+ PriorityQueue queue = new PriorityQueue<>();
+ queue.offer(intervals.get(0).end);
+ for (int i = 1; i < intervals.size(); i++) {
+ Interval temp = intervals.get(i);
+ if (queue.peek() <= temp.start) {
+ queue.poll();
+ }
+ queue.offer(temp.end);
+ }
+
+ return queue.size();
+
+ }
+
+ // Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
+ // Output: [[3,4]]
+
+ public List employeeFreeTime(List> schedule) {
+ PriorityQueue que = new PriorityQueue<>((a, b) -> a.start - b.start);
+
+ for (List list : schedule) {
+ for (Interval i : list) {
+ que.add(i);
+ }
+ }
+
+ List rt = new ArrayList<>();
+ int max = -1;
+ while (!que.isEmpty()) {
+ Interval top = que.poll();
+ if (max != -1 && top.start > max) {
+ rt.add(new Interval(max, top.start));
+ }
+ max = Math.max(max, top.end);
+ }
+
+ return rt;
+ }
+
+
+}
diff --git a/src/geeksforgeeks/MergeIntervalIntersection.java b/src/geeksforgeeks/MergeIntervalIntersection.java
new file mode 100644
index 0000000..a17ee6f
--- /dev/null
+++ b/src/geeksforgeeks/MergeIntervalIntersection.java
@@ -0,0 +1,39 @@
+package geeksforgeeks;
+
+/**
+ *
+Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
+Return the intersection of these two interval lists.
+
+Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
+Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
+ */
+public class MergeIntervalIntersection {
+
+ // inorder to find a overlapping part alone between two intervals
+ // we take
+ // start = max(a.start, b.start)
+ // end = min(a.end, b.end)
+ // That is, the highest start time and the lowest end time will be the overlapping interval.
+ public int[][] intervalIntersection(int[][] A, int[][] B) {
+ int i=0;
+ int j=0;
+ List result= new ArrayList<>();
+ while(i=B[j][0] && A[i][0]<=B[j][1] ||
+ B[j][0]>=A[i][0] && B[j][0]<=A[i][1]){ // this condition checks if there'a ovelapping
+ //A=>[0,2], B=> [1,5]
+ result.add(new int[]{Math.max(A[i][0],B[j][0]), Math.min(A[i][1],B[j][1])});
+ }
+ // once added to result move the i or j based on lesser end time
+ if(A[i][1] result = new ArrayList<>();
- if (intervals.length == 0 || intervals == null) return result.toArray(new int[0][]);
-
- Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
+ if (intervals.length <= 1) {
+ return intervals;
+ }
- int start = intervals[0][0];
- int end = intervals[0][1];
+ /* Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
+ Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0]));*/
+ Arrays.sort(intervals, Comparator.comparingInt(i -> i[0]));
- for (int[] arr : intervals) {
- System.out.println(arr[0] + "" + arr[1]);
- if (arr[0] <= end) {
- end = Math.max(end, arr[1]);
- } else {
- result.add(new int[]{start, end});
- start = arr[0];
- end = arr[1];
+ List result = new ArrayList<>();
+ int[] prevInterval = intervals[0];
+ result.add(prevInterval);
+ for (int[] currInterval : intervals) {
+ if (currInterval[0] <= prevInterval[1]) // Overlapping intervals, move the end if needed
+ {
+ prevInterval[1] = Math.max(prevInterval[1], currInterval[1]);
+ } else { // Disjoint intervals, add the new interval to the list
+ prevInterval = currInterval;
+ result.add(prevInterval);
}
}
- result.add(new int[]{start, end});
- return result.toArray(new int[0][]);
-
+ return result.toArray(new int[result.size()][]);
}
public static void main(String[] args) {
- int[][] arr = {{1, 3}, {2, 4}, {5, 7}, {6, 8}};
+ // [[1,3],[2,6],[8,10],[15,18]]
+ int[][] arr = { { 1, 9 }, { 6, 8 }, { 2, 4 }, { 4, 7 } };
+ //{ { 1, 3 }, { 2, 4 }, { 5, 7 }, { 6, 8 } };
//{{1, 9}, {2, 4}, {4, 7}, {6, 8}};
System.out.println(Arrays.deepToString(merge(arr)));
}
diff --git a/src/geeksforgeeks/MergeSortLinkedList.java b/src/geeksforgeeks/MergeSortLinkedList.java
index 4e8fbb2..d9eaf1b 100644
--- a/src/geeksforgeeks/MergeSortLinkedList.java
+++ b/src/geeksforgeeks/MergeSortLinkedList.java
@@ -1,38 +1,35 @@
package geeksforgeeks;
+/**
+ * https://www.geeksforgeeks.org/merge-sort-for-linked-list/
+ */
public class MergeSortLinkedList {
public static ListNode sortList(ListNode head) {
- if (head == null || head.next == null)
+ if (head == null || head.next == null) {
return head;
-
+ }
// step 1. cut the list to two halves
ListNode prev = null;
ListNode slow = head;
ListNode fast = head;
-
// find the mid node
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
-
prev.next = null;
-
// step 2. sort each half
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
-
// step 3. merge l1 and l2
return merge(l1, l2);
}
static ListNode merge(ListNode l1, ListNode l2) {
-
ListNode node = new ListNode(0);
ListNode temp = node;
-
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
temp.next = l1;
@@ -43,13 +40,12 @@ static ListNode merge(ListNode l1, ListNode l2) {
}
temp = temp.next;
}
-
- if (l1 != null)
+ if (l1 != null) {
temp.next = l1;
-
- if (l2 != null)
+ }
+ if (l2 != null) {
temp.next = l2;
-
+ }
return node.next;
}
@@ -76,4 +72,9 @@ class ListNode {
public ListNode(int val) {
this.val = val;
}
+
+ @Override
+ public String toString() {
+ return "ListNode{val=" + val + '}';
+ }
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MergeTwoLinkedList.java b/src/geeksforgeeks/MergeTwoLinkedList.java
new file mode 100644
index 0000000..8e879ea
--- /dev/null
+++ b/src/geeksforgeeks/MergeTwoLinkedList.java
@@ -0,0 +1,46 @@
+package geeksforgeeks;
+
+/**
+ * https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/
+ */
+public class MergeTwoLinkedList {
+
+ public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
+ if (l1 == null) {
+ return l2;
+ } else if (l2 == null) {
+ return l1;
+ }
+ ListNode dummy = new ListNode(0);
+ ListNode curr = dummy;
+ while (l1 != null && l2 != null) {
+ if (l1.val <= l2.val) {
+ curr.next = l1;
+ l1 = l1.next;
+ } else {
+ curr.next = l2;
+ l2 = l2.next;
+ }
+ curr = curr.next;
+ }
+ curr.next = l1 == null ? l2 : l1;
+ return dummy.next;
+ }
+
+ public static void main(String[] args) {
+ ListNode l1 = new ListNode(1);
+ l1.next = new ListNode(2);
+ l1.next.next = new ListNode(3);
+ l1.next.next.next = new ListNode(4);
+
+ ListNode l2 = new ListNode(1);
+ // l2.next = new ListNode(7);
+
+ ListNode head = mergeTwoLists(l1, l2);
+
+ while (head != null) {
+ System.out.println(head.val);
+ head = head.next;
+ }
+ }
+}
diff --git a/src/geeksforgeeks/MinCostRopeConnect.java b/src/geeksforgeeks/MinCostRopeConnect.java
index 1297fff..cab85b9 100644
--- a/src/geeksforgeeks/MinCostRopeConnect.java
+++ b/src/geeksforgeeks/MinCostRopeConnect.java
@@ -2,26 +2,33 @@
import java.util.PriorityQueue;
+/**
+ * https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/
+ */
public class MinCostRopeConnect {
- public static void main(String[] args) {
- int arr[] = { 4, 3, 2, 6 };
+ // 6 + 4 = 10 .. 10 + 3 = 13 .. 13 +2 = 15
- MinCostRopeConnect rope = new MinCostRopeConnect();
- rope.connectRopes(arr);
- }
+ // 2+3 = 5 .. 5 + 4 = 9 .. 9 + 6 = 15 ..
- private void connectRopes(int[] arr) {
- PriorityQueue pq = new PriorityQueue<>();
- for (int i : arr)
- pq.add(i);
+ public static void main(String[] args) {
+ int arr[] = { 4, 3, 2, 6 };
- while (pq.size() > 1) {
- Integer remove = pq.remove();
- Integer remove2 = pq.remove();
+ MinCostRopeConnect rope = new MinCostRopeConnect();
+ rope.connectRopes(arr);
+ }
- System.out.println("cost" + (remove + remove2));
- pq.add(remove + remove2);
- }
- }
+ private void connectRopes(int[] arr) {
+ PriorityQueue pq = new PriorityQueue<>();
+ for (int i : arr)
+ pq.add(i);
+
+ while (pq.size() > 1) {
+ Integer remove = pq.remove();
+ Integer remove2 = pq.remove();
+
+ System.out.println("cost" + (remove + remove2));
+ pq.add(remove + remove2);
+ }
+ }
}
diff --git a/src/geeksforgeeks/MinStepsToConvertXtoY.java b/src/geeksforgeeks/MinStepsToConvertXtoY.java
new file mode 100644
index 0000000..44c0efa
--- /dev/null
+++ b/src/geeksforgeeks/MinStepsToConvertXtoY.java
@@ -0,0 +1,37 @@
+package geeksforgeeks;
+
+class MinStepsToConvertXtoY {
+ private static int minOperations(int src, int target) {
+
+ Set visited = new HashSet<>(1000);
+ LinkedList queue = new LinkedList();
+
+ GFG node = new GFG(src, 0);
+
+ queue.offer(node);
+ visited.add(node);
+
+ while (!queue.isEmpty()) {
+ GFG temp = queue.poll();
+ visited.add(temp);
+
+ if (temp.val == target) {
+ return temp.steps;
+ }
+
+ int mul = temp.val * 2;
+ int sub = temp.val - 1;
+
+ // given constraints
+ if (mul > 0 && mul < 1000) {
+ GFG nodeMul = new GFG(mul, temp.steps + 1);
+ queue.offer(nodeMul);
+ }
+ if (sub > 0 && sub < 1000) {
+ GFG nodeSub = new GFG(sub, temp.steps + 1);
+ queue.offer(nodeSub);
+ }
+ }
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MinTimeRotOranges.java b/src/geeksforgeeks/MinTimeRotOranges.java
index a020b8a..5b1dfac 100644
--- a/src/geeksforgeeks/MinTimeRotOranges.java
+++ b/src/geeksforgeeks/MinTimeRotOranges.java
@@ -30,8 +30,9 @@ public String toString() {
private boolean hasFreshOrange(int[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
- if (grid[i][j] == 1)
+ if (grid[i][j] == 1) {
return true;
+ }
}
}
return false;
@@ -48,8 +49,8 @@ private boolean isValidFresh(int row, int col, int[][] grid) {
}
private void rotOranges(Queue queue, Pair p, int[][] grid) {
- int[] xMoves = {1, -1, 0, 0};
- int[] yMoves = {0, 0, 1, -1};
+ int[] xMoves = { 1, -1, 0, 0 };
+ int[] yMoves = { 0, 0, 1, -1 };
for (int k = 0; k < xMoves.length; k++) {
int x = p.x + xMoves[k];
int y = p.y + yMoves[k];
@@ -65,33 +66,36 @@ public int findMinTime(int[][] grid) {
Queue queue = new LinkedList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
- if (grid[i][j] == 2)
+ if (grid[i][j] == 2) {
queue.add(new Pair(i, j));
+ }
}
}
- if (queue.isEmpty())
+ if (queue.isEmpty()) {
return -1;
+ }
queue.add(new Pair(-1, -1));
while (!queue.isEmpty()) {
Pair p = queue.poll();
- if (!isDelimiter(p))
+ if (!isDelimiter(p)) {
rotOranges(queue, p, grid);
- else if (!queue.isEmpty()) {
+ } else if (!queue.isEmpty()) {
queue.add(p); // add back delimiter
result += 1;
}
}
- if (hasFreshOrange(grid))
+ if (hasFreshOrange(grid)) {
return -1;
+ }
return result;
}
public static void main(String[] args) {
- int grid[][] = {{2, 1, 0, 1, 1}, {1, 0, 2, 1, 1}, {1, 1, 1, 1, 1}};
+ int grid[][] = { { 2, 1, 0, 1, 1 }, { 1, 0, 2, 1, 1 }, { 1, 1, 1, 1, 1 } };
System.out.println(new MinTimeRotOranges().findMinTime(grid));
}
diff --git a/src/geeksforgeeks/MinimumBribes.java b/src/geeksforgeeks/MinimumBribes.java
new file mode 100644
index 0000000..2107aa4
--- /dev/null
+++ b/src/geeksforgeeks/MinimumBribes.java
@@ -0,0 +1,50 @@
+package geeksforgeeks;
+/**
+ * https://www.hackerrank.com/challenges/new-year-chaos/problem
+ * https://www.youtube.com/watch?v=UpmVTEvaXPE
+ * Any person in the queue can bribe the person directly in front of them to swap positions.
+ * If two people swap positions, they still wear the same sticker denoting their original place in line.
+ * One person can bribe at most two other persons.
+ * That is to say, if n = 8, and Person 5 bribes Person 4, the queue will look like this: 1,2,3,5,4,6,7,8.
+ * Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state!
+ *
+ * No person can bribe more than 2 persons if yes then print chaotic
+ * Input: 2 1 5 3 4
+ * Output: 3
+ *
+ * Input: 2 5 1 3 4
+ * Output: Too chaotic
+ */
+public class MinimumBribes {
+ // input is 2 1 5 3 4,
+ // when index is at 2(val=>5) we see how many elements lesser than 5 is there
+ // if the value is greater that 2 we print too chaotic
+ // else we add it to result
+ void minimumBribes(int[] q) {
+ int bribes=0;
+ for(int i = q.length-1; i >= 0; i--) {
+
+ if(i-1>=0 && q[i-1]==i+1){
+ q[i-1]=q[i];
+ q[i]=i+1;
+ bribes+=1;
+ } else if(i-2>=0 && q[i-2]==i+2){
+ //2,1,5,3,4 we need to swap 2 elements to restore the array
+ q[i-2]=q[i-1];
+ q[i-1]=q[i];
+ q[i]=i+1;
+ bribes+=2;
+ }else{
+ System.out.println("Too Chaotic");
+ return;
+ }
+ }
+ System.out.println(bribes);
+ }
+
+ public static void main(String[] args) {
+ // inputs 5,1,2,3,7,8,6,4 => too chaotic
+ // 1,2,5,3,7,8,6,4 => 7
+ new MinimumBribes().minimumBribes(new int[]{2,1,5,3,4});
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MinimumDistanceBetweenTwoNumbers.java b/src/geeksforgeeks/MinimumDistanceBetweenTwoNumbers.java
index 38b0d2d..c4c888a 100644
--- a/src/geeksforgeeks/MinimumDistanceBetweenTwoNumbers.java
+++ b/src/geeksforgeeks/MinimumDistanceBetweenTwoNumbers.java
@@ -1,26 +1,42 @@
package geeksforgeeks;
-/*https://www.geeksforgeeks.org/find-the-minimum-distance-between-two-numbers/*/
+
+
+/*
+https://www.geeksforgeeks.org/find-the-minimum-distance-between-two-numbers/
+
+Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[].
+The array might also contain duplicates.
+You may assume that both x and y are different and present in arr[].
+
+Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3},
+x = 3, y = 2
+Output: Minimum distance between 3
+and 2 is 1.
+Explanation:3 is at index 7 and 2 is at
+index 6, so the distance is 1
+*/
+
class MinimumDistanceBetweenTwoNumbers {
+
int minDist(int arr[], int n, int x, int y) {
int i = 0;
int minDist = Integer.MAX_VALUE;
int prev = 0;
- // Find the first occurence of any of the two numbers (x or y)
- // and store the index of this occurence in prev
+ // Find the first occurrence of any of the two numbers (x or y)
+ // and store the index of this occurrence in prev
for (i = 0; i < n; i++) {
if (arr[i] == x || arr[i] == y) {
prev = i;
break;
}
}
-
- // Traverse after the first occurrence
+ // sort of like sliding window tracks the first occurence
+ // of the element and check if both are not same and calculates the distance
for (; i < n; i++) {
if (arr[i] == x || arr[i] == y) {
- // If the current element matches with any of the two then
// check if current element and prev element are different
// Also check if this value is smaller than minimum distance
// so far
@@ -30,18 +46,17 @@ int minDist(int arr[], int n, int x, int y) {
prev = i;
}
}
-
return minDist;
}
public static void main(String[] args) {
MinimumDistanceBetweenTwoNumbers min = new MinimumDistanceBetweenTwoNumbers();
- int arr[] = {2, 5, 3, 5, 4, 4, 2, 3};
+ int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
+ int arr1[] = { 3, 5, 4, 3, 1, 2, 4, 6, 5, 6, 6, 5, 4, 8, 3 };
int n = arr.length;
int x = 3;
- int y = 2;
+ int y = 6;
- System.out.println("Minimum distance between " + x + " and " + y
- + " is " + min.minDist(arr, n, x, y));
+ System.out.println("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y));
}
}
diff --git a/src/geeksforgeeks/MinimumIndexDistanceOfMaximumNumbers.java b/src/geeksforgeeks/MinimumIndexDistanceOfMaximumNumbers.java
index fd3ed21..f05449b 100644
--- a/src/geeksforgeeks/MinimumIndexDistanceOfMaximumNumbers.java
+++ b/src/geeksforgeeks/MinimumIndexDistanceOfMaximumNumbers.java
@@ -2,31 +2,30 @@
/**
* https://www.geeksforgeeks.org/minimum-distance-between-two-occurrences-of-maximum/
- *
*/
class MinimumIndexDistanceOfMaximumNumbers {
- static int minDistance(int arr[], int n) {
- int maximumElement = arr[0];
- int minDist = n;
- int index = 0;
+ static int minDistance(int arr[], int n) {
+ int maximumElement = arr[0];
+ int minDist = n;
+ int index = 0;
- for (int i = 1; i < n; i++) {
- if (maximumElement == arr[i]) {
- minDist = Math.min(minDist, (i - index));
- index = i;
- } else if (maximumElement < arr[i]) {
- maximumElement = arr[i];
- minDist = n;
- index = i;
- }
- }
- return minDist - 1;
- }
+ for (int i = 1; i < n; i++) {
+ if (maximumElement == arr[i]) {
+ minDist = Math.min(minDist, (i - index));
+ index = i;
+ } else if (maximumElement < arr[i]) {
+ maximumElement = arr[i];
+ minDist = n;
+ index = i;
+ }
+ }
+ return minDist - 1;
+ }
- public static void main(String[] args) {
- int arr[] = { 6, 3, 1, 3, 6, 5, 4, 1 };
- int n = arr.length;
- System.out.print("Minimum distance = " + minDistance(arr, n));
- }
+ public static void main(String[] args) {
+ int arr[] = { 6, 3, 1, 3, 6, 5, 4, 1 };
+ int n = arr.length;
+ System.out.print("Minimum distance = " + minDistance(arr, n));
+ }
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MinimumPathSum.java b/src/geeksforgeeks/MinimumPathSum.java
new file mode 100644
index 0000000..58b6da4
--- /dev/null
+++ b/src/geeksforgeeks/MinimumPathSum.java
@@ -0,0 +1,40 @@
+package geeksforgeeks;
+
+class MinPathSum {
+ public int minPathSum(int[][] grid) {
+ if (grid == null || grid.length == 0)
+ return 0;
+ int dp[][] = new int[grid.length][grid[0].length];
+ return getMinPathSum(0, 0, grid, dp);
+ }
+
+ public int getMinPathSum(int i, int j, int[][] grid, int[][] dp) {
+ if (i == grid.length - 1 && j == grid[0].length - 1)
+ return grid[i][j];
+ else if (i > grid.length - 1 || j > grid[0].length - 1)
+ return Integer.MAX_VALUE;
+ else {
+ if (dp[i][j] != 0)
+ return dp[i][j];
+ dp[i][j] = grid[i][j] + Math.min(getMinPathSum(i + 1, j, grid, dp), getMinPathSum(i, j + 1, grid, dp));
+ }
+ return dp[i][j];
+ }
+
+ public int minPathSum1(int[][] grid) {
+
+ for(int i=1;i s;
+ Stack stack;
Integer minEle;
MyStack() {
- s = new Stack();
+ stack = new Stack<>();
}
void getMin() {
- if (s.isEmpty())
+ if (stack.isEmpty()) {
System.out.println("Stack is empty");
- else
+ } else {
System.out.println("Minimum Element in the " + " stack is: " + minEle);
+ }
}
void peek() {
- if (s.isEmpty()) {
+ if (stack.isEmpty()) {
System.out.println("Stack is empty ");
return;
}
- Integer t = s.peek();
+ Integer t = stack.peek();
System.out.print("Top Most Element is: ");
- if (t < minEle)
+ if (t < minEle) {
System.out.println(minEle);
- else
+ } else {
System.out.println(t);
+ }
}
void pop() {
- if (s.isEmpty()) {
+ if (stack.isEmpty()) {
System.out.println("Stack is empty");
return;
}
System.out.print("Top Most Element Removed: ");
- Integer t = s.pop();
+ Integer t = stack.pop();
if (t < minEle) {
System.out.println(minEle);
minEle = 2 * minEle - t;
- } else
+ } else {
System.out.println(t);
+ }
}
void push(Integer x) {
- if (s.isEmpty()) {
+ if (stack.isEmpty()) {
minEle = x;
- s.push(x);
+ stack.push(x);
System.out.println("Number Inserted: " + x);
return;
}
@@ -61,10 +64,11 @@ void push(Integer x) {
// x-minEle<0
// x-minEle+x<0+x
// 2x-minEle
+ * https://www.techiedelight.com/chess-knight-problem-find-shortest-path-source-destination/
+ */
class MinimumStepsKnight {
- static class Cell {
- int x;
- int y;
- int dis;
-
- public Cell(int x, int y, int dis) {
- this.x = x;
- this.y = y;
- this.dis = dis;
- }
-
- }
-
- // Utility method returns true if (x, y) lies
- // inside Board
- static boolean isInside(int x, int y, int N) {
- if (x >= 1 && x <= N && y >= 1 && y <= N)
- return true;
- return false;
- }
-
- // Method returns minimum step
- // to reach target position
- static int minStepToReachTarget(int knightPos[], int targetPos[], int N) {
- // x and y direction, where a knight can move
- int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 };
- int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 };
-
- // queue for storing states of knight in board
- Queue q = new LinkedList<>();
-
- // push starting position of knight with 0 distance
- q.add(new Cell(knightPos[0], knightPos[1], 0));
-
- Cell t;
- int x, y;
- boolean visit[][] = new boolean[N + 1][N + 1];
-
- // make all cell unvisited
- for (int i = 1; i <= N; i++)
- for (int j = 1; j <= N; j++)
- visit[i][j] = false;
-
- // visit starting state
- visit[knightPos[0]][knightPos[1]] = true;
-
- // loop untill we have one element in queue
- while (!q.isEmpty()) {
- t = q.remove();
-
- // if current cell is equal to target cell,
- // return its distance
- if (t.x == targetPos[0] && t.y == targetPos[1])
- return t.dis;
-
- // loop for all reachable states
- for (int i = 0; i < 8; i++) {
- x = t.x + dx[i];
- y = t.y + dy[i];
-
- // If reachable state is not yet visited and
- // inside board, push that state into queue
- if (isInside(x, y, N) && !visit[x][y]) {
- visit[x][y] = true;
- q.add(new Cell(x, y, t.dis + 1));
- }
- }
- }
- return Integer.MAX_VALUE;
- }
-
- public static void main(String[] args) {
- int N = 30;
- int[] knightPos = { 1, 1 };
- int[] targetPos = { 30, 30 };
- System.out.println(minStepToReachTarget(knightPos, targetPos, N));
- }
+ static class Cell {
+ int x;
+ int y;
+ int steps;
+
+ public Cell(int x, int y, int steps) {
+ this.x = x;
+ this.y = y;
+ this.steps = steps;
+ }
+
+ }
+
+ // Utility method returns true if (x, y) lies
+ // inside Board
+ static boolean isInside(int x, int y, int N) {
+ if (x >= 1 && x <= N && y >= 1 && y <= N) {
+ return true;
+ }
+ return false;
+ }
+
+ // Method returns minimum step
+ // to reach target position
+ static int minStepToReachTarget(int knightPos[], int targetPos[], int N) {
+ // x and y direction, where a knight can move
+ int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 };
+ int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 };
+
+ // queue for storing states of knight in board
+ Queue| q = new LinkedList<>();
+
+ // push starting position of knight with 0 distance
+ q.add(new Cell(knightPos[0], knightPos[1], 0));
+
+ Cell cell;
+ int x, y;
+ boolean visit[][] = new boolean[N + 1][N + 1];
+
+ // make all cell unvisited
+ for (int i = 1; i <= N; i++)
+ for (int j = 1; j <= N; j++)
+ visit[i][j] = false;
+
+ // visit starting state
+ visit[knightPos[0]][knightPos[1]] = true;
+
+ // loop untill we have one element in queue
+ while (!q.isEmpty()) {
+ cell = q.remove();
+
+ // if current cell is equal to target cell,
+ // return its distance
+ if (cell.x == targetPos[0] && cell.y == targetPos[1]) {
+ return cell.steps;
+ }
+
+ // loop for all reachable states
+ for (int i = 0; i < 8; i++) {
+ x = cell.x + dx[i];
+ y = cell.y + dy[i];
+
+ // If reachable state is not yet visited and
+ // inside board, push that state into queue
+ if (isInside(x, y, N) && !visit[x][y]) {
+ visit[x][y] = true;
+ q.add(new Cell(x, y, cell.steps + 1));
+ }
+ }
+ }
+ return Integer.MAX_VALUE;
+ }
+
+ public static void main(String[] args) {
+ int N = 30;
+ int[] knightPos = { 1, 1 };
+ int[] targetPos = { 30, 30 };
+ System.out.println(minStepToReachTarget(knightPos, targetPos, N));
+ }
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MinimumSwapSortArray.java b/src/geeksforgeeks/MinimumSwapSortArray.java
index ebea898..662e278 100644
--- a/src/geeksforgeeks/MinimumSwapSortArray.java
+++ b/src/geeksforgeeks/MinimumSwapSortArray.java
@@ -1,48 +1,124 @@
package geeksforgeeks;
-import java.util.Map;
-import java.util.TreeMap;
+import java.util.Collections;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+
/**
* https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/
- *
*/
class MinimumSwapSortArray {
+ private static class Pair {
+ T key;
+ I value;
+
+ public T getKey() {
+ return key;
+ }
+
+ public I getValue() {
+ return value;
+ }
+
+ public void setKey(T key) {
+ this.key = key;
+ }
+
+ public void setValue(I value) {
+ this.value = value;
+ }
+ public Pair(T key, I value){
+ this.key=key;
+ this.value=value;
+ }
+
+ @Override
+ public String toString() {
+ return "Pair{" +
+ "key=" + key +
+ ", value=" + value +
+ '}';
+ }
+ }
+
+ public static int minSwaps(int[] arr) {
+ int n = arr.length;
+
+ // Create two arrays and use as pairs where first
+ // array is element and second array
+ // is position of first element
+ ArrayList> arrpos =
+ new ArrayList>();
+ for (int i = 0; i < n; i++)
+ arrpos.add(new Pair(arr[i], i));
+
+ // Sort the array by array element values to
+ // get right position of every element as the
+ // elements of second array.
+ Collections.sort(arrpos, (a,b)-> {
+ if (a.getKey() == b.getKey()) {
+ return 0;
+ }
+ return Integer.compare(b.getKey(), a.getKey());
+ });
+ // arrpos.sort(new Comparator>() {
+ // @Override
+ // public int compare(Pair o1,
+ // Pair o2) {
+ // if (o1.getKey() > o2.getKey())
+ // return -1;
+
+ // // We can change this to make it then look at the
+ // // words alphabetical order
+ // else if (o1.getKey().equals(o2.getKey()))
+ // return 0;
+
+ // else
+ // return 1;
+ // }
+ // });
+ System.out.println(arrpos);
+ // To keep track of visited elements. Initialize
+ // all elements as not visited or false.
+ Boolean[] vis = new Boolean[n];
+ Arrays.fill(vis, false);
+
+ // Initialize result
+ int ans = 0;
+
+ // Traverse array elements
+ for (int i = 0; i < n; i++) {
+ // already swapped and corrected or
+ // already present at correct pos
+ if (vis[i] || arrpos.get(i).getValue() == i)
+ continue;
+
+ // find out the number of node in
+ // this cycle and add in ans
+ int cycle_size = 0;
+ int j = i;
+ while (!vis[j]) {
+ vis[j] = true;
+
+ // move to next node
+ j = arrpos.get(j).getValue();
+ cycle_size++;
+ }
+
+ // Update answer by adding current cycle.
+ if (cycle_size > 0) {
+ ans += (cycle_size - 1);
+ }
+ }
+
+ // Return result
+ return ans;
+ }
- public int minSwaps(int[] A, int N) {
- int i = 0;
- // Tree map sorts the order
- Map resMap = new TreeMap<>();
- for (; i < N; i++) {
- System.out.print(A[i] + " --> " + i + " ");
- resMap.put(A[i], i);
-
- }
- System.out.println();
- i = 0;
- for (Map.Entry entry : resMap.entrySet()) {
- System.out.print(entry.getKey() + " --> " + i + " ");
- entry.setValue(i++);
- }
- int swap = 0;
- for (i = 0; i < N;) {
- System.out.println(A[i] + "--" + resMap.get(A[i]) + "--" + i);
- // check if array position is same as treeMap's index
- if (resMap.get(A[i]) != i) {
- int temp = A[i];
- A[i] = A[resMap.get(temp)];
- A[resMap.get(temp)] = temp;
- swap++;
- } else {
- i++;
- }
- }
- return swap;
- }
-
- public static void main(String[] args) {
- int[] a = { 1, 5, 4, 3, 2 };
- MinimumSwapSortArray g = new MinimumSwapSortArray();
- System.out.println(g.minSwaps(a, a.length));
- }
+ public static void main(String[] args) {
+ int[] a = {1, 5, 4, 3, 2};
+ System.out.println(minSwaps(a));
+ }
}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MinimumWindowSubsequence.java b/src/geeksforgeeks/MinimumWindowSubsequence.java
index 2e4c2ca..4e67c90 100644
--- a/src/geeksforgeeks/MinimumWindowSubsequence.java
+++ b/src/geeksforgeeks/MinimumWindowSubsequence.java
@@ -1,45 +1,80 @@
package geeksforgeeks;
-import java.util.Arrays;
-
-/*https://www.programcreek.com/2014/01/leetcode-minimum-window-subsequence-java/*/
+/**
+ * Input:
+ * S = "abcdebdde", T = "bde"
+ * Output: "bcde"
+ * Explanation:
+ * "bcde" is the answer because it occurs before "bdde" which has the same length.
+ * "deb" is not a smaller window because the elements of T in the window must occur in order.
+ */
// unresolved
-public class MinimumWindowSubsequence {
-
- public static String minWindow(String S, String T) {
- int m = T.length(), n = S.length();
- int[][] dp = new int[m + 1][n + 1];
- // fill first row with index values
- for (int j = 0; j <= n; j++) {
- dp[0][j] = j + 1;
+public class MinimumWindowSubsequence {
+ public String minWindow(String S, String T) {
+ if (S.length() == 0 || T.length() == 0) {
+ return "";
}
- // if any element is not present then it will set that row as zero so there wont
- // be any valid values in last row
- for (int i = 1; i <= m; i++) {
- for (int j = 1; j <= n; j++) {
- if (T.charAt(i - 1) == S.charAt(j - 1)) {
- dp[i][j] = dp[i - 1][j - 1];
- } else {
- dp[i][j] = dp[i][j - 1];
+
+ /**
+ * we can conduct two steps by using two pointers for this probelm:
+ * 1. check feasibility from left to right
+ * 2. check optimization from right to left
+ * we can traverse from left to right, find a possible candidate until reach the first ending character of T
+ * eg: for the string s = abcdebdde and t = bde, we should traverse s string until we find first e,
+ * i.e. abcde, then traverse back from current "e" to find if we have other combination of bde with smaller
+ * length.
+ * @param right: fast pointer that always points the last character of T in S
+ * @param left: slow pointer that used to traverse back when right pointer find the last character of T in S
+ * @param tIndex: third pointer used to scan string T
+ * @param minLen: current minimum length of subsequence
+ * */
+ int right = 0;
+ int minLen = Integer.MAX_VALUE;
+ String result = "";
+
+ while (right < S.length()) {
+ int tIndex = 0;
+ // use fast pointer to find the last character of T in S
+ while (right < S.length()) {
+ if (S.charAt(right) == T.charAt(tIndex)) {
+ tIndex++;
+ }
+ if (tIndex == T.length()) {
+ break;
}
+ right++;
+ }
+
+ // if right pointer is over than boundary
+ if (right == S.length()) {
+ break;
}
- }
- int start = 0;
- int len = n + 1;
- for (int j = 1; j <= n; j++) {
- if (dp[m][j] != 0) {
- if (j - dp[m][j] + 1 < len) {
- start = dp[m][j] - 1;
- len = j - dp[m][j] + 1;
+ // use another slow pointer to traverse from right to left until find first character of T in S
+ int left = right;
+ tIndex = T.length() - 1;
+ while (left >= 0) {
+ if (S.charAt(left) == T.charAt(tIndex)) {
+ tIndex--;
}
+ if (tIndex < 0) {
+ break;
+ }
+ left--;
+ }
+ // if we found another subsequence with smaller length, update result
+ if (right - left + 1 < minLen) {
+ minLen = right - left + 1;
+ result = S.substring(left, right + 1);
}
+ // WARNING: we have to move right pointer to the next position of left pointer, NOT the next position
+ // of right pointer
+ right = left + 1;
}
- System.out.println(Arrays.deepToString(dp));
- return len == n + 1 ? "" : S.substring(start, start + len);
+ return result;
}
- public static void main(String args[]) {
- System.out.println(minWindow("abcdebdde", "bdd"));
+ public static void main(String[] args) {
+ System.out.printf(new MinimumWindowSubsequence().minWindow("abcdebdde","bcde"));
}
}
diff --git a/src/geeksforgeeks/MinimumWindowSubstring.java b/src/geeksforgeeks/MinimumWindowSubstring.java
index 64030c2..d36878a 100644
--- a/src/geeksforgeeks/MinimumWindowSubstring.java
+++ b/src/geeksforgeeks/MinimumWindowSubstring.java
@@ -3,53 +3,60 @@
import java.util.HashMap;
import java.util.Map;
+/**
+ * https://leetcode.com/problems/minimum-window-substring/
+ */
class MinimumWindowSubstring {
- public static String minWindow(String s, String t) {
+ public static void main(String[] args) {
+ System.out.println(minWindow("AADOBECODEBANC", "ABC"));
+ System.out.println(minWindow("abcdebdde", "bde"));
+ }
- if (s.length() == 0 || t.length() == 0) {
+ public static String minWindow(String s, String t) {
+ if (t.length() > s.length()) {
return "";
}
+ Map map = new HashMap<>();
+ for (char c : t.toCharArray()) {
+ map.put(c, map.getOrDefault(c, 0) + 1);
+ }
- Map dictT = new HashMap<>();
- for (int i = 0; i < t.length(); i++) {
- dictT.put(t.charAt(i), dictT.getOrDefault(t.charAt(i), 0) + 1);
- }
-
- int required = dictT.size();
- int left = 0;
- int right = 0;
- int formed = 0;
- Map windowCounts = new HashMap<>();
- int[] ans = {-1, 0, 0};
+ int counter = map.size();
- while (right < s.length()) {
- char c = s.charAt(right);
- windowCounts.put(c, windowCounts.getOrDefault(c, 0) + 1);
+ int begin = 0, end = 0;
+ int head = 0;
+ int len = Integer.MAX_VALUE;
- if (dictT.containsKey(c) && windowCounts.get(c).intValue() == dictT.get(c).intValue()) {
- formed++;
- }
- while (left <= right && formed == required) {
- c = s.charAt(left);
- if (ans[0] == -1 || right - left + 1 < ans[0]) {
- ans[0] = right - left + 1;
- ans[1] = left;
- ans[2] = right;
+ while (end < s.length()) {
+ char c = s.charAt(end);
+ if (map.containsKey(c)) {
+ map.put(c, map.get(c) - 1);
+ if (map.get(c) == 0) {
+ counter--;
+ }
}
- windowCounts.put(c, windowCounts.get(c) - 1);
- if (dictT.containsKey(c) && windowCounts.get(c).intValue() < dictT.get(c).intValue()) {
- formed--;
+ end++;
+
+ while (counter == 0) {
+ char tempc = s.charAt(begin);
+ if (map.containsKey(tempc)) {
+ map.put(tempc, map.get(tempc) + 1);
+ if (map.get(tempc) > 0) {
+ counter++;
+ }
+ }
+ if (end - begin < len) {
+ len = end - begin;
+ head = begin;
+ }
+ begin++;
}
- left++;
+
}
- right++;
+ if (len == Integer.MAX_VALUE) {
+ return "";
+ }
+ return s.substring(head, head + len);
}
- return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
- }
-
- public static void main(String[] args) {
- System.out.println(minWindow("AADOBECODEBANC", "ABC"));
- System.out.println(minWindow("abcdebdde", "bde"));
}
-}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MirrorBinaryTree.java b/src/geeksforgeeks/MirrorBinaryTree.java
index 4b166ed..8b1e8d2 100644
--- a/src/geeksforgeeks/MirrorBinaryTree.java
+++ b/src/geeksforgeeks/MirrorBinaryTree.java
@@ -1,8 +1,12 @@
-package geeksforgeeks;// Iterative Java program to convert a Binary
-// Tree to its mirror
+package geeksforgeeks;
import java.util.*;
+/**
+ * https://www.geeksforgeeks.org/write-an-efficient-c-function-to-convert-a-tree-into-its-mirror-tree/
+ *
+ * Iterative Java program to convert a Binary Tree to its mirror
+ */
class MirrorBinaryTree {
static class Node {
@@ -11,7 +15,6 @@ static class Node {
Node right;
}
-
static Node newNode(int data) {
Node node = new Node();
node.data = data;
@@ -20,37 +23,37 @@ static Node newNode(int data) {
}
static void mirror(Node root) {
- if (root == null)
+ if (root == null) {
return;
+ }
Queue q = new LinkedList<>();
q.add(root);
while (q.size() > 0) {
- Node curr = q.peek();
- q.remove();
-
+ Node curr = q.poll();
Node temp = curr.left;
curr.left = curr.right;
curr.right = temp;
- if (curr.left != null)
+ if (curr.left != null) {
q.add(curr.left);
- if (curr.right != null)
+ }
+ if (curr.right != null) {
q.add(curr.right);
+ }
}
}
-
static void inOrder(Node node) {
- if (node == null)
+ if (node == null) {
return;
+ }
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
-
public static void main(String args[]) {
Node root = newNode(1);
root.left = newNode(2);
@@ -58,14 +61,12 @@ public static void main(String args[]) {
root.left.left = newNode(4);
root.left.right = newNode(5);
- System.out.print("\n Inorder traversal of the"
- + " coned tree is \n");
+ System.out.print("\n Inorder traversal of the" + " coned tree is \n");
inOrder(root);
mirror(root);
- System.out.print("\n Inorder traversal of the " +
- "mirror tree is \n");
+ System.out.print("\n Inorder traversal of the " + "mirror tree is \n");
inOrder(root);
}
}
diff --git a/src/geeksforgeeks/MobileKeyPadCombinations.java b/src/geeksforgeeks/MobileKeyPadCombinations.java
new file mode 100644
index 0000000..a53ea51
--- /dev/null
+++ b/src/geeksforgeeks/MobileKeyPadCombinations.java
@@ -0,0 +1,59 @@
+package geeksforgeeks;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * https://www.geeksforgeeks.org/find-possible-words-phone-digits/
+ */
+public class MobileKeyPadCombinations {
+
+ public List letterCombinations(String digits) {
+ List result = new ArrayList<>();
+ if (digits == null || digits.length() == 0) {
+ return result;
+ }
+
+ String[] keypad = { "--", "00", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
+
+ generateCombinations(digits, keypad, digits.length(), 0, new StringBuilder(), result);
+ return result;
+ }
+
+ public void generateCombinations(String digits, String[] keypad, int len, int startIndex, StringBuilder sb,
+ List result) {
+ if (startIndex == len) {
+ result.add(sb.toString());
+ return;
+ }
+
+ for (char ch : keypad[digits.charAt(startIndex) - '0'].toCharArray()) {
+ sb.append(ch);
+ generateCombinations(digits, keypad, len, startIndex + 1, sb, result);
+ sb.deleteCharAt(sb.length() - 1);
+ }
+ }
+
+ public static void main(String[] args) {
+ new MobileKeyPadCombinations().letterCombinations("23").stream().forEach(System.out::println);
+ }
+
+ public List letterCombinationsIterative(String digits) {
+ LinkedList ans = new LinkedList<>();
+ if (digits.isEmpty()) {
+ return ans;
+ }
+ String[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
+ ans.add("");
+ for (int i = 0; i < digits.length(); i++) {
+ int x = Character.getNumericValue(digits.charAt(i));
+ while (ans.peek().length() == i) {
+ String t = ans.remove();
+ for (char s : mapping[x].toCharArray())
+ ans.add(t + s);
+ }
+ }
+ return ans;
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/MoveZeroes.java b/src/geeksforgeeks/MoveZeroes.java
new file mode 100644
index 0000000..2dcdd93
--- /dev/null
+++ b/src/geeksforgeeks/MoveZeroes.java
@@ -0,0 +1,33 @@
+package geeksforgeeks;
+
+import java.util.Arrays;
+
+/**
+ * https://leetcode.com/problems/move-zeroes/
+ */
+class MoveZeroes {
+
+ public static void main(String[] args) {
+ MoveZeroes mz = new MoveZeroes();
+ int[] arr = { 0, 1, 0, 3, 12 };
+ mz.moveZeroes(arr);
+ System.out.println(Arrays.toString(arr));
+ }
+
+ public void moveZeroes(int[] nums) {
+ if (nums == null || nums.length == 0) {
+ return;
+ }
+
+ int insertPos = 0;
+ for (int num : nums) {
+ if (num != 0) {
+ nums[insertPos++] = num;
+ }
+ }
+
+ while (insertPos < nums.length) {
+ nums[insertPos++] = 0;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/geeksforgeeks/NQueens.java b/src/geeksforgeeks/NQueens.java
new file mode 100644
index 0000000..3a34980
--- /dev/null
+++ b/src/geeksforgeeks/NQueens.java
@@ -0,0 +1,90 @@
+package geeksforgeeks;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * https://leetcode.com/problems/n-queens/
+ *
+ * Input: 4
+ * Output: [
+ * [".Q..", // Solution 1
+ * "...Q",
+ * "Q...",
+ * "..Q."],
+ *
+ * ["..Q.", // Solution 2
+ * "Q...",
+ * "...Q",
+ * ".Q.."]
+ * ]
+ * Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
+ */
+public class NQueens {
+
+ public List> solveNQueens(int n) {
+ if(n==0) return Collections.emptyList();
+
+ List> result= new ArrayList<>();
+ char[][] board= new char[n][n];
+ for(int i=0;i> result) {
+
+ if(row==board.length){
+ result.add(construct(board));
+ return;
+ }
+ for(int i=0;i | |