From 4d296b78bcac7ba5d410914c12bbd68f37ac8e89 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 2 Mar 2015 13:03:47 +0530 Subject: [PATCH 001/417] initial commit --- .gitignore | 65 +++++++++++++++++++++++++++++++ src/me/ramswaroop/BotTesting.java | 64 ++++++++++++++++++++++++++++++ src/me/ramswaroop/Main.java | 8 ++++ 3 files changed, 137 insertions(+) create mode 100644 .gitignore create mode 100644 src/me/ramswaroop/BotTesting.java create mode 100644 src/me/ramswaroop/Main.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..8aebf097 --- /dev/null +++ b/.gitignore @@ -0,0 +1,65 @@ +# Created by .ignore support plugin (hsz.mobi) +### Java template +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + + +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + + diff --git a/src/me/ramswaroop/BotTesting.java b/src/me/ramswaroop/BotTesting.java new file mode 100644 index 00000000..e38e7599 --- /dev/null +++ b/src/me/ramswaroop/BotTesting.java @@ -0,0 +1,64 @@ +package me.ramswaroop; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 2/26/15 + * Time: 4:16 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class BotTesting { + public static void main(String args[]) throws MalformedURLException { + final URL myURL = new URL("http://localhost:8080/ifb.html"); + ExecutorService executorService = Executors.newFixedThreadPool(20); + Long start = System.currentTimeMillis(); + for (int i = 0; i <= 50; i++) { + executorService.execute(new Runnable() { + + @Override + public void run() { + + try { + HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection(); + + myURLConnection.setRequestProperty("x-msisdn", "919871296875"); + myURLConnection.setRequestProperty("x-rat", "1"); + myURLConnection.setRequestProperty("X-Forwarded-For", "171.48.0.1"); + String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 " + Math.random(); + myURLConnection.setRequestProperty("user-agent", userAgent); + myURLConnection.setRequestMethod("GET"); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream())); + String line; + StringBuffer content = new StringBuffer(""); + + + bufferedReader.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + } + Long diff = System.currentTimeMillis() - start; + System.out.println("Difference: " + diff + "ms"); + executorService.shutdown(); + } + + private class MyThread extends Thread { + + @Override + public void run(){ + + } + } +} diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java new file mode 100644 index 00000000..f7366621 --- /dev/null +++ b/src/me/ramswaroop/Main.java @@ -0,0 +1,8 @@ +package me.ramswaroop; + +public class Main { + + public static void main(String[] args) { + // write your code here + } +} From 4b19e01d8c8a10cf39f5f0fa0cdf5add90e7da55 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 24 Mar 2015 15:06:42 +0530 Subject: [PATCH 002/417] tree initial commit --- src/me/ramswaroop/common/Stack.java | 11 +++++++++++ src/me/ramswaroop/{ => rough}/BotTesting.java | 2 +- src/me/ramswaroop/rough/Equals.java | 17 +++++++++++++++++ .../ramswaroop/trees/ImplicitTreeTraversal.java | 11 +++++++++++ 4 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/common/Stack.java rename src/me/ramswaroop/{ => rough}/BotTesting.java (98%) create mode 100644 src/me/ramswaroop/rough/Equals.java create mode 100644 src/me/ramswaroop/trees/ImplicitTreeTraversal.java diff --git a/src/me/ramswaroop/common/Stack.java b/src/me/ramswaroop/common/Stack.java new file mode 100644 index 00000000..23af94f5 --- /dev/null +++ b/src/me/ramswaroop/common/Stack.java @@ -0,0 +1,11 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/24/15 + * Time: 3:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class Stack { +} diff --git a/src/me/ramswaroop/BotTesting.java b/src/me/ramswaroop/rough/BotTesting.java similarity index 98% rename from src/me/ramswaroop/BotTesting.java rename to src/me/ramswaroop/rough/BotTesting.java index e38e7599..13c802f3 100644 --- a/src/me/ramswaroop/BotTesting.java +++ b/src/me/ramswaroop/rough/BotTesting.java @@ -1,4 +1,4 @@ -package me.ramswaroop; +package me.ramswaroop.rough; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/rough/Equals.java b/src/me/ramswaroop/rough/Equals.java new file mode 100644 index 00000000..9a5cddf7 --- /dev/null +++ b/src/me/ramswaroop/rough/Equals.java @@ -0,0 +1,17 @@ +package me.ramswaroop.rough; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/14/15 + * Time: 4:38 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class Equals { + public static void main(String[] a) { + Short i = new Short((short) 12); + Short j = new Short((short) 12); + System.out.print(j == i); // prints false as compiler compares 2 references instead of their values + System.out.print(12 == i); // prints true as the compiler unboxes "i" and then compares the value + } +} diff --git a/src/me/ramswaroop/trees/ImplicitTreeTraversal.java b/src/me/ramswaroop/trees/ImplicitTreeTraversal.java new file mode 100644 index 00000000..12c39d5d --- /dev/null +++ b/src/me/ramswaroop/trees/ImplicitTreeTraversal.java @@ -0,0 +1,11 @@ +package me.ramswaroop.trees; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/24/15 + * Time: 3:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class ImplicitTreeTraversal { +} From c519f08bccd3c3f126ce5933bd616453dd1526a1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 24 Mar 2015 16:35:15 +0530 Subject: [PATCH 003/417] renamed git repo --- src/me/ramswaroop/common/Stack.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/me/ramswaroop/common/Stack.java b/src/me/ramswaroop/common/Stack.java index 23af94f5..7d8c8293 100644 --- a/src/me/ramswaroop/common/Stack.java +++ b/src/me/ramswaroop/common/Stack.java @@ -8,4 +8,6 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class Stack { + int top; + } From 6cff3e7bd688848cfdb8a9bc514b96dc460ba9b2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 26 Mar 2015 15:20:22 +0530 Subject: [PATCH 004/417] legacy non-generic code test --- .../{rough => tests}/BotTesting.java | 2 +- .../ramswaroop/{rough => tests}/Equals.java | 2 +- .../tests/GenericNonGenericMix.java | 28 +++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) rename src/me/ramswaroop/{rough => tests}/BotTesting.java (98%) rename src/me/ramswaroop/{rough => tests}/Equals.java (94%) create mode 100644 src/me/ramswaroop/tests/GenericNonGenericMix.java diff --git a/src/me/ramswaroop/rough/BotTesting.java b/src/me/ramswaroop/tests/BotTesting.java similarity index 98% rename from src/me/ramswaroop/rough/BotTesting.java rename to src/me/ramswaroop/tests/BotTesting.java index 13c802f3..a33ffda7 100644 --- a/src/me/ramswaroop/rough/BotTesting.java +++ b/src/me/ramswaroop/tests/BotTesting.java @@ -1,4 +1,4 @@ -package me.ramswaroop.rough; +package me.ramswaroop.tests; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/rough/Equals.java b/src/me/ramswaroop/tests/Equals.java similarity index 94% rename from src/me/ramswaroop/rough/Equals.java rename to src/me/ramswaroop/tests/Equals.java index 9a5cddf7..43def93d 100644 --- a/src/me/ramswaroop/rough/Equals.java +++ b/src/me/ramswaroop/tests/Equals.java @@ -1,4 +1,4 @@ -package me.ramswaroop.rough; +package me.ramswaroop.tests; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/tests/GenericNonGenericMix.java b/src/me/ramswaroop/tests/GenericNonGenericMix.java new file mode 100644 index 00000000..f71a7a3a --- /dev/null +++ b/src/me/ramswaroop/tests/GenericNonGenericMix.java @@ -0,0 +1,28 @@ +package me.ramswaroop.tests; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/26/15 + * Time: 3:06 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class GenericNonGenericMix { + static List add(ArrayList list) { + list.add(new String("100")); + list.add(new Integer(10)); // will throw exception at runtime + return list; + } + + public static void main(String[] a) { + ArrayList stringArrayList = new ArrayList<>(); + stringArrayList.add("ram"); + add(stringArrayList); + for (String s : stringArrayList) { + System.out.println(s); + } + } +} From 6fce234067a71991c65d32e35b7fdb82fe3e778e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 30 Mar 2015 10:38:29 +0530 Subject: [PATCH 005/417] Initial commit --- LICENSE | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 LICENSE create mode 100644 README.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..cf421538 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Ram swaroop + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/README.md b/README.md new file mode 100644 index 00000000..e29b81dd --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# JavaConcepts From 90c8a6f14464693dcc3f1e7c11d2611a61a3bc91 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 30 Mar 2015 10:45:33 +0530 Subject: [PATCH 006/417] testing push to multiple repos --- src/me/ramswaroop/common/Stack.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/common/Stack.java b/src/me/ramswaroop/common/Stack.java index 7d8c8293..46e7bb1a 100644 --- a/src/me/ramswaroop/common/Stack.java +++ b/src/me/ramswaroop/common/Stack.java @@ -7,7 +7,7 @@ * Time: 3:02 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class Stack { +public class Stack { int top; } From 65020da4d365f6d6aefcaac7888fa8ed872c22ed Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 4 Apr 2015 15:18:09 +0530 Subject: [PATCH 007/417] stack interface + implementation --- src/me/ramswaroop/common/LinkedStack.java | 93 +++++++++++++++++++++++ src/me/ramswaroop/common/Stack.java | 13 ---- src/me/ramswaroop/interfaces/Stack.java | 45 +++++++++++ 3 files changed, 138 insertions(+), 13 deletions(-) create mode 100644 src/me/ramswaroop/common/LinkedStack.java delete mode 100644 src/me/ramswaroop/common/Stack.java create mode 100644 src/me/ramswaroop/interfaces/Stack.java diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java new file mode 100644 index 00000000..e36d8f56 --- /dev/null +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -0,0 +1,93 @@ +package me.ramswaroop.common; + +import me.ramswaroop.interfaces.Stack; + +import java.util.NoSuchElementException; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/24/15 + * Time: 3:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ + +/** + * Stack implementation using + * a singly linked list + * + * @param + */ +public class LinkedStack implements Stack { + + private Node top = null; + + /** + * Pushes an item onto the top of this stack. + * + * @param item + */ + @Override + public void push(E item) { + top = new Node(item, top); + } + + /** + * Removes the object at the top of this stack and returns that object as the value of this function. + * + * @return + */ + @Override + public E pop() { + E item = peek(); + top = top.next; + return item; + } + + /** + * Looks at the object at the top of this stack without removing it from the stack. + * + * @return + */ + @Override + public E peek() { + if (top == null) { + throw new NoSuchElementException(); + } + return top.data; + } + + /** + * Returns the number of items currently in the stack. + * + * @return + */ + @Override + public int size() { + int count = 0; + for (Node node = top; node != null; node = top.next) { + count++; + } + return count; + } + + /** + * Tests if this stack is empty. + * + * @return + */ + @Override + public boolean isEmpty() { + return top == null; + } + + private class Node { + E data; + Node next; + + Node(E data, Node next) { + this.data = data; + this.next = next; + } + } +} diff --git a/src/me/ramswaroop/common/Stack.java b/src/me/ramswaroop/common/Stack.java deleted file mode 100644 index 46e7bb1a..00000000 --- a/src/me/ramswaroop/common/Stack.java +++ /dev/null @@ -1,13 +0,0 @@ -package me.ramswaroop.common; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 3/24/15 - * Time: 3:02 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class Stack { - int top; - -} diff --git a/src/me/ramswaroop/interfaces/Stack.java b/src/me/ramswaroop/interfaces/Stack.java new file mode 100644 index 00000000..9499850d --- /dev/null +++ b/src/me/ramswaroop/interfaces/Stack.java @@ -0,0 +1,45 @@ +package me.ramswaroop.interfaces; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/3/15 + * Time: 9:47 AM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public interface Stack { + /** + * Pushes an item onto the top of this stack. + * + * @param item + */ + public void push(E item); + + /** + * Removes the object at the top of this stack and returns that object as the value of this function. + * + * @return + */ + public E pop(); + + /** + * Looks at the object at the top of this stack without removing it from the stack. + * + * @return + */ + public E peek(); + + /** + * Returns the number of items currently in the stack. + * + * @return + */ + public int size(); + + /** + * Tests if this stack is empty. + * + * @return + */ + public boolean isEmpty(); +} From cd52ec6f8e6ff7e971e71ae4c2f18b1c13e57bff Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 10 Apr 2015 23:07:39 +0530 Subject: [PATCH 008/417] tree boilerplate code done --- src/me/ramswaroop/bits/CountSetBits.java | 59 ++++++++++++++++++ src/me/ramswaroop/common/LinkedStack.java | 3 +- src/me/ramswaroop/common/Node.java | 20 ++++++ .../common/interfaces/BinaryTree.java | 12 ++++ .../{ => common}/interfaces/Stack.java | 2 +- src/me/ramswaroop/common/interfaces/Tree.java | 62 +++++++++++++++++++ 6 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 src/me/ramswaroop/bits/CountSetBits.java create mode 100644 src/me/ramswaroop/common/Node.java create mode 100644 src/me/ramswaroop/common/interfaces/BinaryTree.java rename src/me/ramswaroop/{ => common}/interfaces/Stack.java (95%) create mode 100644 src/me/ramswaroop/common/interfaces/Tree.java diff --git a/src/me/ramswaroop/bits/CountSetBits.java b/src/me/ramswaroop/bits/CountSetBits.java new file mode 100644 index 00000000..9502bc4c --- /dev/null +++ b/src/me/ramswaroop/bits/CountSetBits.java @@ -0,0 +1,59 @@ +package me.ramswaroop.bits; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/4/15 + * Time: 8:52 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class CountSetBits { + + /** + * Unoptimized version + * + * @param number + * @return + */ + static int countSetBits(int number) { + int count = 0; + for (int i = 0; i < 32; i++) { + if ((number & 1) == 1) { + count++; + } + number = number >>> 1; + } + return count; + } + + /** + * Optimized version + * + * @param n + * @return + */ + static int countSetBits(long n) { + int count = 0; + while (n > 0) { + n &= n - 1; + count++; + } + return count; + } + + public static void main(String[] a) { + Scanner in = new Scanner(System.in); + + long n = Long.parseLong(in.nextLine()); + System.out.println(countSetBits(n)); + } +} + +/** + * + * Learn more: + * http://javarevisited.blogspot.in/2014/06/how-to-count-number-of-set-bits-or-1s.html + * + */ \ No newline at end of file diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java index e36d8f56..d2f92f04 100644 --- a/src/me/ramswaroop/common/LinkedStack.java +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -1,6 +1,7 @@ package me.ramswaroop.common; -import me.ramswaroop.interfaces.Stack; + +import me.ramswaroop.common.interfaces.Stack; import java.util.NoSuchElementException; diff --git a/src/me/ramswaroop/common/Node.java b/src/me/ramswaroop/common/Node.java new file mode 100644 index 00000000..02eb63c4 --- /dev/null +++ b/src/me/ramswaroop/common/Node.java @@ -0,0 +1,20 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/5/15 + * Time: 4:47 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class Node { + private E data; + private Node left; + private Node right; + + public Node(E data, Node left, Node right) { + this.data = data; + this.left = left; + this.right = right; + } +} diff --git a/src/me/ramswaroop/common/interfaces/BinaryTree.java b/src/me/ramswaroop/common/interfaces/BinaryTree.java new file mode 100644 index 00000000..7645208c --- /dev/null +++ b/src/me/ramswaroop/common/interfaces/BinaryTree.java @@ -0,0 +1,12 @@ +package me.ramswaroop.common.interfaces; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/10/15 + * Time: 10:57 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public interface BinaryTree extends Tree { + +} diff --git a/src/me/ramswaroop/interfaces/Stack.java b/src/me/ramswaroop/common/interfaces/Stack.java similarity index 95% rename from src/me/ramswaroop/interfaces/Stack.java rename to src/me/ramswaroop/common/interfaces/Stack.java index 9499850d..0bdc2959 100644 --- a/src/me/ramswaroop/interfaces/Stack.java +++ b/src/me/ramswaroop/common/interfaces/Stack.java @@ -1,4 +1,4 @@ -package me.ramswaroop.interfaces; +package me.ramswaroop.common.interfaces; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/common/interfaces/Tree.java b/src/me/ramswaroop/common/interfaces/Tree.java new file mode 100644 index 00000000..dea0a6c6 --- /dev/null +++ b/src/me/ramswaroop/common/interfaces/Tree.java @@ -0,0 +1,62 @@ +package me.ramswaroop.common.interfaces; + +import me.ramswaroop.common.Node; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/5/15 + * Time: 5:16 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public interface Tree { + + /** + * @param node + */ + public void insert(Node node); + + + /** + * @param node + */ + public void delete(Node node); + + + /** + * + * + */ + public void preOrder(); + + + /** + * + * + */ + public void inOrder(); + + + /** + * + * + */ + public void postOrder(); + + + /** + * Returns the number of nodes currently in the tree. + * + * @return + */ + public int size(); + + + /** + * Tests if this tree is empty. + * + * @return + */ + public boolean isEmpty(); + +} From 6b8ff13c3f978c9aa25f564773c57eb53f52626f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 10 Apr 2015 23:21:50 +0530 Subject: [PATCH 009/417] tree boilerplate code complete --- src/me/ramswaroop/common/interfaces/Tree.java | 10 ++- .../trees/BinaryTreeRecursiveImpl.java | 83 +++++++++++++++++++ .../trees/ImplicitTreeTraversal.java | 11 --- 3 files changed, 90 insertions(+), 14 deletions(-) create mode 100644 src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java delete mode 100644 src/me/ramswaroop/trees/ImplicitTreeTraversal.java diff --git a/src/me/ramswaroop/common/interfaces/Tree.java b/src/me/ramswaroop/common/interfaces/Tree.java index dea0a6c6..0d5982bc 100644 --- a/src/me/ramswaroop/common/interfaces/Tree.java +++ b/src/me/ramswaroop/common/interfaces/Tree.java @@ -12,33 +12,37 @@ public interface Tree { /** + * Inserts a node to the tree. + * * @param node */ public void insert(Node node); /** + * Deletes a particular node from the tree. + * * @param node */ public void delete(Node node); /** - * + * Prints the pre-order traversal of the tree. * */ public void preOrder(); /** - * + * Prints the in-order traversal of the tree. * */ public void inOrder(); /** - * + * Prints the post-order traversal of the tree. * */ public void postOrder(); diff --git a/src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java b/src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java new file mode 100644 index 00000000..62438104 --- /dev/null +++ b/src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java @@ -0,0 +1,83 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.Node; +import me.ramswaroop.common.interfaces.BinaryTree; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/24/15 + * Time: 3:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class BinaryTreeRecursiveImpl implements BinaryTree { + + public static void main(String[] a) { + BinaryTreeRecursiveImpl obj = new BinaryTreeRecursiveImpl(); + + } + + /** + * Inserts a node to the tree. + * + * @param node + */ + @Override + public void insert(Node node) { + + } + + /** + * Deletes a particular node from the tree. + * + * @param node + */ + @Override + public void delete(Node node) { + + } + + /** + * Prints the pre-order traversal of the tree. + */ + @Override + public void preOrder() { + + } + + /** + * Prints the in-order traversal of the tree. + */ + @Override + public void inOrder() { + + } + + /** + * Prints the post-order traversal of the tree. + */ + @Override + public void postOrder() { + + } + + /** + * Returns the number of nodes currently in the tree. + * + * @return + */ + @Override + public int size() { + return 0; + } + + /** + * Tests if this tree is empty. + * + * @return + */ + @Override + public boolean isEmpty() { + return false; + } +} diff --git a/src/me/ramswaroop/trees/ImplicitTreeTraversal.java b/src/me/ramswaroop/trees/ImplicitTreeTraversal.java deleted file mode 100644 index 12c39d5d..00000000 --- a/src/me/ramswaroop/trees/ImplicitTreeTraversal.java +++ /dev/null @@ -1,11 +0,0 @@ -package me.ramswaroop.trees; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 3/24/15 - * Time: 3:02 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class ImplicitTreeTraversal { -} From 9dbe767bab5d52f1b1cc89c64e1d02731ec71caa Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 12 Apr 2015 15:22:55 +0530 Subject: [PATCH 010/417] stack and queue implementation done --- src/me/ramswaroop/Main.java | 59 +++++++++ src/me/ramswaroop/common/BinaryNode.java | 44 +++++++ .../BinaryTree.java => BinarySearchTree.java} | 4 +- src/me/ramswaroop/common/LinkedQueue.java | 89 ++++++++++++++ src/me/ramswaroop/common/LinkedStack.java | 40 ++++-- src/me/ramswaroop/common/Node.java | 20 --- src/me/ramswaroop/common/Queue.java | 63 ++++++++++ .../common/{interfaces => }/Stack.java | 17 ++- .../common/{interfaces => }/Tree.java | 17 +-- .../trees/BinarySearchTreeRecursiveImpl.java | 114 ++++++++++++++++++ .../trees/BinaryTreeRecursiveImpl.java | 83 ------------- 11 files changed, 420 insertions(+), 130 deletions(-) create mode 100644 src/me/ramswaroop/common/BinaryNode.java rename src/me/ramswaroop/common/{interfaces/BinaryTree.java => BinarySearchTree.java} (66%) create mode 100644 src/me/ramswaroop/common/LinkedQueue.java delete mode 100644 src/me/ramswaroop/common/Node.java create mode 100644 src/me/ramswaroop/common/Queue.java rename src/me/ramswaroop/common/{interfaces => }/Stack.java (57%) rename src/me/ramswaroop/common/{interfaces => }/Tree.java (77%) create mode 100644 src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java delete mode 100644 src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index f7366621..3f012196 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -1,8 +1,67 @@ package me.ramswaroop; +import me.ramswaroop.common.LinkedQueue; +import me.ramswaroop.common.LinkedStack; + public class Main { public static void main(String[] args) { // write your code here + + System.out.println("======== Stack ========"); + + LinkedStack stack = new LinkedStack(); + stack.push(5); + stack.push(7); + stack.push(2); + stack.push(6); + stack.print(); + stack.pop(); + stack.pop(); + stack.pop(); + stack.pop(); + stack.print(); + stack.push(1); + stack.push(2); + stack.print(); + System.out.print(stack.peek()); + stack.print(); + + System.out.println("\n======== Queue ========"); + + LinkedQueue queue = new LinkedQueue(); + queue.add(5); + queue.add(7); + queue.add(2); + queue.add(6); + queue.add(8); + queue.add(10); + queue.add(11); + queue.add(4); + queue.print(); + queue.remove(); + queue.remove(); + queue.remove(); + queue.print(); + queue.remove(); + queue.print(); + queue.remove(); + queue.remove(); + queue.remove(); + queue.remove(); + queue.print(); + //queue.remove(); + //queue.remove(); + queue.add(1); + queue.add(2); + queue.add(3); + queue.add(5); + queue.print(); + queue.remove(); + queue.remove(); + queue.remove(); + queue.print(); + queue.remove(); + queue.print(); } } diff --git a/src/me/ramswaroop/common/BinaryNode.java b/src/me/ramswaroop/common/BinaryNode.java new file mode 100644 index 00000000..cfd20358 --- /dev/null +++ b/src/me/ramswaroop/common/BinaryNode.java @@ -0,0 +1,44 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/11/15 + * Time: 7:11 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class BinaryNode { + E data; + BinaryNode left; + BinaryNode right; + + public BinaryNode(E data, BinaryNode left, BinaryNode right) { + this.data = data; + this.left = left; + this.right = right; + } + + public E getData() { + return data; + } + + public void setData(E data) { + this.data = data; + } + + public BinaryNode getLeft() { + return left; + } + + public void setLeft(BinaryNode left) { + this.left = left; + } + + public BinaryNode getRight() { + return right; + } + + public void setRight(BinaryNode right) { + this.right = right; + } +} diff --git a/src/me/ramswaroop/common/interfaces/BinaryTree.java b/src/me/ramswaroop/common/BinarySearchTree.java similarity index 66% rename from src/me/ramswaroop/common/interfaces/BinaryTree.java rename to src/me/ramswaroop/common/BinarySearchTree.java index 7645208c..e4933395 100644 --- a/src/me/ramswaroop/common/interfaces/BinaryTree.java +++ b/src/me/ramswaroop/common/BinarySearchTree.java @@ -1,4 +1,4 @@ -package me.ramswaroop.common.interfaces; +package me.ramswaroop.common; /** * Created by IntelliJ IDEA. @@ -7,6 +7,6 @@ * Time: 10:57 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public interface BinaryTree extends Tree { +public interface BinarySearchTree extends Tree { } diff --git a/src/me/ramswaroop/common/LinkedQueue.java b/src/me/ramswaroop/common/LinkedQueue.java new file mode 100644 index 00000000..303bddf7 --- /dev/null +++ b/src/me/ramswaroop/common/LinkedQueue.java @@ -0,0 +1,89 @@ +package me.ramswaroop.common; + +import java.util.NoSuchElementException; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/12/15 + * Time: 11:07 AM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class LinkedQueue implements Queue { + + Node front; + Node rear; + + public LinkedQueue() { + front = null; + rear = null; + } + + @Override + public E add(E item) { + if (front == null || rear == null) { + front = rear = new Node<>(item, null); + } else { + rear.next = new Node<>(item, null); + rear = rear.next; + } + return item; + } + + @Override + public E remove() { + if (rear.next == front) { + throw new NoSuchElementException(); + } + E item = element(); + front = front.next; + return item; + } + + @Override + public E element() { + if (front == null) { + throw new NoSuchElementException(); + } + return front.data; + } + + @Override + public int size() { + int count = 0; + if (rear.next == front) return count; + for (Node node = front; node != rear; node = node.next) { + count++; + } + return count; + } + + @Override + public boolean isEmpty() { + return rear.next == front; + } + + @Override + public void print() { + Node node; + System.out.print("["); + if (rear.next == front) { + System.out.print("]"); + return; + } + for (node = front; node != rear; node = node.next) { + System.out.print(node.data + ","); + } + System.out.print(node.data + "]"); + } + + private class Node { + E data; + Node next; + + public Node(E data, Node next) { + this.data = data; + this.next = next; + } + } +} diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java index d2f92f04..df2ae5ab 100644 --- a/src/me/ramswaroop/common/LinkedStack.java +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -1,9 +1,7 @@ package me.ramswaroop.common; -import me.ramswaroop.common.interfaces.Stack; - -import java.util.NoSuchElementException; +import java.util.EmptyStackException; /** * Created by IntelliJ IDEA. @@ -21,7 +19,11 @@ */ public class LinkedStack implements Stack { - private Node top = null; + private Node top; + + public LinkedStack() { + top = null; + } /** * Pushes an item onto the top of this stack. @@ -29,8 +31,9 @@ public class LinkedStack implements Stack { * @param item */ @Override - public void push(E item) { - top = new Node(item, top); + public E push(E item) { + top = new Node<>(item, top); + return item; } /** @@ -53,7 +56,7 @@ public E pop() { @Override public E peek() { if (top == null) { - throw new NoSuchElementException(); + throw new EmptyStackException(); } return top.data; } @@ -66,12 +69,29 @@ public E peek() { @Override public int size() { int count = 0; - for (Node node = top; node != null; node = top.next) { + for (Node node = top; node != null; node = node.next) { count++; } return count; } + /** + * Prints the content of the stack. + */ + @Override + public void print() { + Node node; + System.out.print("["); + if (top == null) { + System.out.print("]"); + return; + } + for (node = top; node.next != null; node = node.next) { + System.out.print(node.data + ","); + } + System.out.print(node.data + "]"); + } + /** * Tests if this stack is empty. * @@ -82,9 +102,9 @@ public boolean isEmpty() { return top == null; } - private class Node { + private class Node { E data; - Node next; + Node next; Node(E data, Node next) { this.data = data; diff --git a/src/me/ramswaroop/common/Node.java b/src/me/ramswaroop/common/Node.java deleted file mode 100644 index 02eb63c4..00000000 --- a/src/me/ramswaroop/common/Node.java +++ /dev/null @@ -1,20 +0,0 @@ -package me.ramswaroop.common; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 4/5/15 - * Time: 4:47 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class Node { - private E data; - private Node left; - private Node right; - - public Node(E data, Node left, Node right) { - this.data = data; - this.left = left; - this.right = right; - } -} diff --git a/src/me/ramswaroop/common/Queue.java b/src/me/ramswaroop/common/Queue.java new file mode 100644 index 00000000..999a7a9a --- /dev/null +++ b/src/me/ramswaroop/common/Queue.java @@ -0,0 +1,63 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/12/15 + * Time: 10:39 AM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public interface Queue { + + + /** + * Inserts the specified element into this queue. + * + * @param item + * @return + */ + public E add(E item); + + + /** + * Retrieves and removes the head of this queue. This method throws an + * exception if this queue is empty. + * + * @return + */ + public E remove(); + + + /** + * Retrieves, but does not remove, the head of this queue. This method throws an + * exception if this queue is empty. + * + * @return + */ + public E element(); + + + /** + * Returns the size of this queue. + * + * @return + */ + public int size(); + + + /** + * Tests whether the queue is empty or not. + * + * @return + */ + public boolean isEmpty(); + + + /** + * Prints the content of the queue. + * + */ + public void print(); + + +} diff --git a/src/me/ramswaroop/common/interfaces/Stack.java b/src/me/ramswaroop/common/Stack.java similarity index 57% rename from src/me/ramswaroop/common/interfaces/Stack.java rename to src/me/ramswaroop/common/Stack.java index 0bdc2959..a59dc420 100644 --- a/src/me/ramswaroop/common/interfaces/Stack.java +++ b/src/me/ramswaroop/common/Stack.java @@ -1,4 +1,4 @@ -package me.ramswaroop.common.interfaces; +package me.ramswaroop.common; /** * Created by IntelliJ IDEA. @@ -13,17 +13,21 @@ public interface Stack { * * @param item */ - public void push(E item); + public E push(E item); /** - * Removes the object at the top of this stack and returns that object as the value of this function. + * Removes the object at the top of this stack and returns + * that object as the value of this function. This method + * throws an exception if this queue is empty. * * @return */ public E pop(); /** - * Looks at the object at the top of this stack without removing it from the stack. + * Looks at the object at the top of this stack without + * removing it from the stack. This method throws an + * exception if this queue is empty. * * @return */ @@ -42,4 +46,9 @@ public interface Stack { * @return */ public boolean isEmpty(); + + /** + * Prints the content of the stack. + */ + public void print(); } diff --git a/src/me/ramswaroop/common/interfaces/Tree.java b/src/me/ramswaroop/common/Tree.java similarity index 77% rename from src/me/ramswaroop/common/interfaces/Tree.java rename to src/me/ramswaroop/common/Tree.java index 0d5982bc..eff391e2 100644 --- a/src/me/ramswaroop/common/interfaces/Tree.java +++ b/src/me/ramswaroop/common/Tree.java @@ -1,6 +1,4 @@ -package me.ramswaroop.common.interfaces; - -import me.ramswaroop.common.Node; +package me.ramswaroop.common; /** * Created by IntelliJ IDEA. @@ -14,36 +12,33 @@ public interface Tree { /** * Inserts a node to the tree. * - * @param node + * @param data */ - public void insert(Node node); + public void insert(E data, BinaryNode node); /** * Deletes a particular node from the tree. * - * @param node + * @param data */ - public void delete(Node node); + public void delete(E data); /** * Prints the pre-order traversal of the tree. - * */ - public void preOrder(); + public void preOrder(BinaryNode node); /** * Prints the in-order traversal of the tree. - * */ public void inOrder(); /** * Prints the post-order traversal of the tree. - * */ public void postOrder(); diff --git a/src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java b/src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java new file mode 100644 index 00000000..8bb7272c --- /dev/null +++ b/src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java @@ -0,0 +1,114 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; + +import java.util.NoSuchElementException; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/24/15 + * Time: 3:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class BinarySearchTreeRecursiveImpl implements BinarySearchTree { + + BinaryNode root; + + BinarySearchTreeRecursiveImpl() { + root = null; + } + + public static void main(String[] a) { + BinarySearchTreeRecursiveImpl obj = new BinarySearchTreeRecursiveImpl(); + obj.insert(2, null); + obj.insert(3, obj.root); + obj.insert(5, obj.root); + obj.insert(6, obj.root); + obj.preOrder(obj.root); + + } + + /** + * Inserts a node to the tree. + * + * @param data + */ + @Override + public void insert(E data, BinaryNode node) { + if (node == null) { + node = new BinaryNode<>(data, null, null); + } else { + if (data.intValue() < node.getData().intValue()) { + insert(data, node.getLeft()); + } else { + insert(data, node.getRight()); + } + } + } + + /** + * Deletes a particular node from the tree. + * + * @param data + */ + @Override + public void delete(E data) { + + } + + /** + * Prints the pre-order traversal of the tree. + */ + @Override + public void preOrder(BinaryNode node) { + if (node == null) { + throw new NoSuchElementException(); + } + print(node.getData()); + preOrder(node.getLeft()); + preOrder(node.getRight()); + } + + /** + * Prints the in-order traversal of the tree. + */ + @Override + public void inOrder() { + + } + + /** + * Prints the post-order traversal of the tree. + */ + @Override + public void postOrder() { + + } + + /** + * Returns the number of nodes currently in the tree. + * + * @return + */ + @Override + public int size() { + return 0; + } + + /** + * Tests if this tree is empty. + * + * @return + */ + @Override + public boolean isEmpty() { + return false; + } + + private void print(E value) { + System.out.print(value); + } + +} diff --git a/src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java b/src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java deleted file mode 100644 index 62438104..00000000 --- a/src/me/ramswaroop/trees/BinaryTreeRecursiveImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -package me.ramswaroop.trees; - -import me.ramswaroop.common.Node; -import me.ramswaroop.common.interfaces.BinaryTree; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 3/24/15 - * Time: 3:02 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class BinaryTreeRecursiveImpl implements BinaryTree { - - public static void main(String[] a) { - BinaryTreeRecursiveImpl obj = new BinaryTreeRecursiveImpl(); - - } - - /** - * Inserts a node to the tree. - * - * @param node - */ - @Override - public void insert(Node node) { - - } - - /** - * Deletes a particular node from the tree. - * - * @param node - */ - @Override - public void delete(Node node) { - - } - - /** - * Prints the pre-order traversal of the tree. - */ - @Override - public void preOrder() { - - } - - /** - * Prints the in-order traversal of the tree. - */ - @Override - public void inOrder() { - - } - - /** - * Prints the post-order traversal of the tree. - */ - @Override - public void postOrder() { - - } - - /** - * Returns the number of nodes currently in the tree. - * - * @return - */ - @Override - public int size() { - return 0; - } - - /** - * Tests if this tree is empty. - * - * @return - */ - @Override - public boolean isEmpty() { - return false; - } -} From f8391d4d3966473e30dcc016cbdfd742bad612a0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 19 Apr 2015 13:38:38 +0530 Subject: [PATCH 011/417] main control menu done + tree almost done --- src/me/ramswaroop/Main.java | 151 +++++++++++------- src/me/ramswaroop/common/BinaryNode.java | 34 +--- .../ramswaroop/common/BinarySearchTree.java | 12 -- src/me/ramswaroop/common/LinkedQueue.java | 12 +- src/me/ramswaroop/common/LinkedStack.java | 12 +- src/me/ramswaroop/common/Tree.java | 61 ------- src/me/ramswaroop/tests/DivideByZero.java | 14 ++ .../ramswaroop/tests/MethodLocalVSInner.java | 36 +++++ src/me/ramswaroop/tests/Threads.java | 34 ++++ .../trees/BinarySearchTreeRecursiveImpl.java | 114 ------------- src/me/ramswaroop/trees/RecursiveBST.java | 137 ++++++++++++++++ src/me/ramswaroop/utils/Utils.java | 17 ++ 12 files changed, 350 insertions(+), 284 deletions(-) delete mode 100644 src/me/ramswaroop/common/BinarySearchTree.java delete mode 100644 src/me/ramswaroop/common/Tree.java create mode 100644 src/me/ramswaroop/tests/DivideByZero.java create mode 100644 src/me/ramswaroop/tests/MethodLocalVSInner.java create mode 100644 src/me/ramswaroop/tests/Threads.java delete mode 100644 src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java create mode 100644 src/me/ramswaroop/trees/RecursiveBST.java create mode 100644 src/me/ramswaroop/utils/Utils.java diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 3f012196..44387e67 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -2,66 +2,103 @@ import me.ramswaroop.common.LinkedQueue; import me.ramswaroop.common.LinkedStack; +import me.ramswaroop.utils.Utils; + +import java.util.Scanner; public class Main { public static void main(String[] args) { - // write your code here - - System.out.println("======== Stack ========"); - - LinkedStack stack = new LinkedStack(); - stack.push(5); - stack.push(7); - stack.push(2); - stack.push(6); - stack.print(); - stack.pop(); - stack.pop(); - stack.pop(); - stack.pop(); - stack.print(); - stack.push(1); - stack.push(2); - stack.print(); - System.out.print(stack.peek()); - stack.print(); - - System.out.println("\n======== Queue ========"); - - LinkedQueue queue = new LinkedQueue(); - queue.add(5); - queue.add(7); - queue.add(2); - queue.add(6); - queue.add(8); - queue.add(10); - queue.add(11); - queue.add(4); - queue.print(); - queue.remove(); - queue.remove(); - queue.remove(); - queue.print(); - queue.remove(); - queue.print(); - queue.remove(); - queue.remove(); - queue.remove(); - queue.remove(); - queue.print(); - //queue.remove(); - //queue.remove(); - queue.add(1); - queue.add(2); - queue.add(3); - queue.add(5); - queue.print(); - queue.remove(); - queue.remove(); - queue.remove(); - queue.print(); - queue.remove(); - queue.print(); + int k1, k2; + Scanner in = new Scanner(System.in); + LinkedStack stack = new LinkedStack<>(); + LinkedQueue queue = new LinkedQueue<>(); + firstLoop: + while (true) { + Utils.println("Choose module:"); + Utils.println("=============="); + Utils.println("1. Stack"); + Utils.println("2. Queue"); + Utils.println("3. BST"); + Utils.println("4. Exit"); + k1 = Integer.parseInt(in.nextLine()); + switch (k1) { + case 1: + while (true) { + Utils.println("Select operation:"); + Utils.println("================="); + Utils.println("1. Push"); + Utils.println("2. Pop"); + Utils.println("3. Peek"); + Utils.println("4. Print"); + Utils.println("5. Exit module"); + k2 = Integer.parseInt(in.nextLine()); + switch (k2) { + case 1: + Utils.println("Enter value:"); + int input = Integer.parseInt(in.nextLine()); + stack.push(input); + stack.print(); + break; + case 2: + stack.pop(); + stack.print(); + break; + case 3: + stack.peek(); + stack.print(); + break; + case 4: + stack.print(); + break; + case 5: + continue firstLoop; + default: + Utils.println("Wrong choice!"); + } + } + case 2: + while (true) { + Utils.println("Select operation:"); + Utils.println("================="); + Utils.println("1. Add"); + Utils.println("2. Remove"); + Utils.println("3. Front Element"); + Utils.println("4. Print"); + Utils.println("5. Exit module"); + k2 = Integer.parseInt(in.nextLine()); + switch (k2) { + case 1: + Utils.println("Enter value:"); + int input = Integer.parseInt(in.nextLine()); + queue.add(input); + queue.print(); + break; + case 2: + queue.remove(); + queue.print(); + break; + case 3: + queue.element(); + queue.print(); + break; + case 4: + queue.print(); + break; + case 5: + continue firstLoop; + default: + Utils.println("Wrong choice!"); + } + } + case 3: + break; + case 4: + Utils.println("Exiting..."); + System.exit(0); + default: + Utils.println("Wrong choice!"); + } + } } } diff --git a/src/me/ramswaroop/common/BinaryNode.java b/src/me/ramswaroop/common/BinaryNode.java index cfd20358..360a2630 100644 --- a/src/me/ramswaroop/common/BinaryNode.java +++ b/src/me/ramswaroop/common/BinaryNode.java @@ -8,37 +8,15 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class BinaryNode { - E data; - BinaryNode left; - BinaryNode right; - public BinaryNode(E data, BinaryNode left, BinaryNode right) { - this.data = data; - this.left = left; - this.right = right; - } - - public E getData() { - return data; - } - - public void setData(E data) { - this.data = data; - } + public E value; + public BinaryNode left; + public BinaryNode right; - public BinaryNode getLeft() { - return left; - } - - public void setLeft(BinaryNode left) { + public BinaryNode(E value, BinaryNode left, BinaryNode right) { + this.value = value; this.left = left; - } - - public BinaryNode getRight() { - return right; - } - - public void setRight(BinaryNode right) { this.right = right; } + } diff --git a/src/me/ramswaroop/common/BinarySearchTree.java b/src/me/ramswaroop/common/BinarySearchTree.java deleted file mode 100644 index e4933395..00000000 --- a/src/me/ramswaroop/common/BinarySearchTree.java +++ /dev/null @@ -1,12 +0,0 @@ -package me.ramswaroop.common; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 4/10/15 - * Time: 10:57 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public interface BinarySearchTree extends Tree { - -} diff --git a/src/me/ramswaroop/common/LinkedQueue.java b/src/me/ramswaroop/common/LinkedQueue.java index 303bddf7..edcc17c5 100644 --- a/src/me/ramswaroop/common/LinkedQueue.java +++ b/src/me/ramswaroop/common/LinkedQueue.java @@ -45,7 +45,7 @@ public E element() { if (front == null) { throw new NoSuchElementException(); } - return front.data; + return front.value; } @Override @@ -72,17 +72,17 @@ public void print() { return; } for (node = front; node != rear; node = node.next) { - System.out.print(node.data + ","); + System.out.print(node.value + ","); } - System.out.print(node.data + "]"); + System.out.println(node.value + "]"); } private class Node { - E data; + E value; Node next; - public Node(E data, Node next) { - this.data = data; + public Node(E value, Node next) { + this.value = value; this.next = next; } } diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java index df2ae5ab..48400d55 100644 --- a/src/me/ramswaroop/common/LinkedStack.java +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -58,7 +58,7 @@ public E peek() { if (top == null) { throw new EmptyStackException(); } - return top.data; + return top.value; } /** @@ -87,9 +87,9 @@ public void print() { return; } for (node = top; node.next != null; node = node.next) { - System.out.print(node.data + ","); + System.out.print(node.value + ","); } - System.out.print(node.data + "]"); + System.out.println(node.value + "]"); } /** @@ -103,11 +103,11 @@ public boolean isEmpty() { } private class Node { - E data; + E value; Node next; - Node(E data, Node next) { - this.data = data; + Node(E value, Node next) { + this.value = value; this.next = next; } } diff --git a/src/me/ramswaroop/common/Tree.java b/src/me/ramswaroop/common/Tree.java deleted file mode 100644 index eff391e2..00000000 --- a/src/me/ramswaroop/common/Tree.java +++ /dev/null @@ -1,61 +0,0 @@ -package me.ramswaroop.common; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 4/5/15 - * Time: 5:16 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public interface Tree { - - /** - * Inserts a node to the tree. - * - * @param data - */ - public void insert(E data, BinaryNode node); - - - /** - * Deletes a particular node from the tree. - * - * @param data - */ - public void delete(E data); - - - /** - * Prints the pre-order traversal of the tree. - */ - public void preOrder(BinaryNode node); - - - /** - * Prints the in-order traversal of the tree. - */ - public void inOrder(); - - - /** - * Prints the post-order traversal of the tree. - */ - public void postOrder(); - - - /** - * Returns the number of nodes currently in the tree. - * - * @return - */ - public int size(); - - - /** - * Tests if this tree is empty. - * - * @return - */ - public boolean isEmpty(); - -} diff --git a/src/me/ramswaroop/tests/DivideByZero.java b/src/me/ramswaroop/tests/DivideByZero.java new file mode 100644 index 00000000..a3c352e3 --- /dev/null +++ b/src/me/ramswaroop/tests/DivideByZero.java @@ -0,0 +1,14 @@ +package me.ramswaroop.tests; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/18/15 + * Time: 2:50 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class DivideByZero { + public static void main(String[] a) { + System.out.print(5.0/0); + } +} diff --git a/src/me/ramswaroop/tests/MethodLocalVSInner.java b/src/me/ramswaroop/tests/MethodLocalVSInner.java new file mode 100644 index 00000000..ec3ae677 --- /dev/null +++ b/src/me/ramswaroop/tests/MethodLocalVSInner.java @@ -0,0 +1,36 @@ +package me.ramswaroop.tests; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/14/15 + * Time: 11:39 AM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +class A { + void m() { + System.out.println("outer"); + } +} + +public class MethodLocalVSInner { + + public static void main(String[] args) { + new MethodLocalVSInner().go(); + } + + void go() { + class A { + void m() { + System.out.println("inner"); + } + } + new A().m(); + } + + class A { + void m() { + System.out.println("middle"); + } + } +} diff --git a/src/me/ramswaroop/tests/Threads.java b/src/me/ramswaroop/tests/Threads.java new file mode 100644 index 00000000..0111b6e0 --- /dev/null +++ b/src/me/ramswaroop/tests/Threads.java @@ -0,0 +1,34 @@ +package me.ramswaroop.tests; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/15/15 + * Time: 11:27 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class Threads { + public static void main(String[] a) { + Runnable r = new Runnable() { + @Override + public void run() { + for (int i = 0; i < 10; i++) { + System.out.println(Thread.currentThread().getName() + ": " + i); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + + } + System.out.println("====== " + Thread.currentThread().getName() + " woke up ======"); + } + } + }; + Thread t1 = new Thread(r); + Thread t2 = new Thread(r); + Thread t3 = new Thread(r); + + t1.start(); + t2.start(); + t3.start(); + } +} diff --git a/src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java b/src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java deleted file mode 100644 index 8bb7272c..00000000 --- a/src/me/ramswaroop/trees/BinarySearchTreeRecursiveImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -package me.ramswaroop.trees; - -import me.ramswaroop.common.BinaryNode; -import me.ramswaroop.common.BinarySearchTree; - -import java.util.NoSuchElementException; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 3/24/15 - * Time: 3:02 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class BinarySearchTreeRecursiveImpl implements BinarySearchTree { - - BinaryNode root; - - BinarySearchTreeRecursiveImpl() { - root = null; - } - - public static void main(String[] a) { - BinarySearchTreeRecursiveImpl obj = new BinarySearchTreeRecursiveImpl(); - obj.insert(2, null); - obj.insert(3, obj.root); - obj.insert(5, obj.root); - obj.insert(6, obj.root); - obj.preOrder(obj.root); - - } - - /** - * Inserts a node to the tree. - * - * @param data - */ - @Override - public void insert(E data, BinaryNode node) { - if (node == null) { - node = new BinaryNode<>(data, null, null); - } else { - if (data.intValue() < node.getData().intValue()) { - insert(data, node.getLeft()); - } else { - insert(data, node.getRight()); - } - } - } - - /** - * Deletes a particular node from the tree. - * - * @param data - */ - @Override - public void delete(E data) { - - } - - /** - * Prints the pre-order traversal of the tree. - */ - @Override - public void preOrder(BinaryNode node) { - if (node == null) { - throw new NoSuchElementException(); - } - print(node.getData()); - preOrder(node.getLeft()); - preOrder(node.getRight()); - } - - /** - * Prints the in-order traversal of the tree. - */ - @Override - public void inOrder() { - - } - - /** - * Prints the post-order traversal of the tree. - */ - @Override - public void postOrder() { - - } - - /** - * Returns the number of nodes currently in the tree. - * - * @return - */ - @Override - public int size() { - return 0; - } - - /** - * Tests if this tree is empty. - * - * @return - */ - @Override - public boolean isEmpty() { - return false; - } - - private void print(E value) { - System.out.print(value); - } - -} diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java new file mode 100644 index 00000000..e3f2eaf4 --- /dev/null +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -0,0 +1,137 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/24/15 + * Time: 3:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class RecursiveBST> { + + BinaryNode root; + + public static void main(String[] a) { + RecursiveBST obj = new RecursiveBST(); + obj.put(6); + obj.put(3); + obj.put(5); + obj.put(7); + obj.preOrder(); + obj.print("\n"); + obj.inOrder(); + obj.print("\n"); + obj.postOrder(); + } + + /** + * Inserts a node to the tree. + * + * @param value + */ + public void put(E value) { + put(root, value); + } + + public BinaryNode put(BinaryNode node, E value) { + if (node == null) { + return root = new BinaryNode<>(value, null, null); + } else { + if (value.compareTo(node.value) < 0) { + if (node.left == null) { + return node.left = new BinaryNode<>(value, null, null); + } else { + return put(node.left, value); + } + } else { + if (node.right == null) { + return node.right = new BinaryNode<>(value, null, null); + } else { + return put(node.right, value); + } + } + } + } + + /** + * Deletes a particular node from the tree. + * + * @param value + */ + public void delete(E value) { + + } + + /** + * Prints the pre-order traversal of the tree. + */ + public void preOrder() { + preOrder(root); + } + + public void preOrder(BinaryNode node) { + if (node == null) { + return; + } + print(node.value); + preOrder(node.left); + preOrder(node.right); + } + + /** + * Prints the in-order traversal of the tree. + */ + public void inOrder() { + inOrder(root); + } + + public void inOrder(BinaryNode node) { + if (node == null) { + return; + } + inOrder(node.left); + print(node.value); + inOrder(node.right); + } + + /** + * Prints the post-order traversal of the tree. + */ + public void postOrder() { + postOrder(root); + } + + public void postOrder(BinaryNode node) { + if (node == null) { + return; + } + postOrder(node.left); + postOrder(node.right); + print(node.value); + } + + /** + * Returns the number of nodes currently in the tree. + * + * @return + */ + public int size() { + return 0; + } + + /** + * Tests if this tree is empty. + * + * @return + */ + public boolean isEmpty() { + return false; + } + + private void print(E value) { + System.out.print(value); + } + +} diff --git a/src/me/ramswaroop/utils/Utils.java b/src/me/ramswaroop/utils/Utils.java new file mode 100644 index 00000000..613b55ca --- /dev/null +++ b/src/me/ramswaroop/utils/Utils.java @@ -0,0 +1,17 @@ +package me.ramswaroop.utils; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/19/15 + * Time: 11:57 AM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class Utils { + public static void print(Object o) { + System.out.print(o); + } + public static void println(Object o) { + System.out.println(o); + } +} From 81448b3ff543d15a19d10a8f4886e51f5d9c461b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 19 Apr 2015 18:38:30 +0530 Subject: [PATCH 012/417] tree size done --- src/me/ramswaroop/trees/BinarySearchTree.java | 12 +++++++++++ src/me/ramswaroop/trees/BinaryTree.java | 16 ++++++++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 21 ++++++++++++++++--- src/me/ramswaroop/trees/Tree.java | 12 +++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/trees/BinarySearchTree.java create mode 100644 src/me/ramswaroop/trees/BinaryTree.java create mode 100644 src/me/ramswaroop/trees/Tree.java diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/trees/BinarySearchTree.java new file mode 100644 index 00000000..c794cfd6 --- /dev/null +++ b/src/me/ramswaroop/trees/BinarySearchTree.java @@ -0,0 +1,12 @@ +package me.ramswaroop.trees; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/19/15 + * Time: 6:36 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class BinarySearchTree extends BinaryTree { + +} diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java new file mode 100644 index 00000000..629f4c61 --- /dev/null +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -0,0 +1,16 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/19/15 + * Time: 6:35 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class BinaryTree extends Tree { + public static boolean isIdentical(BinaryNode node1, BinaryNode node2) { + return false; + } +} diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index e3f2eaf4..3fd7dd8e 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -1,6 +1,7 @@ package me.ramswaroop.trees; import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.utils.Utils; /** * Created by IntelliJ IDEA. @@ -9,7 +10,7 @@ * Time: 3:02 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class RecursiveBST> { +public class RecursiveBST> extends Tree { BinaryNode root; @@ -24,6 +25,7 @@ public static void main(String[] a) { obj.inOrder(); obj.print("\n"); obj.postOrder(); + Utils.println("\n" + obj.size()); } /** @@ -118,7 +120,15 @@ public void postOrder(BinaryNode node) { * @return */ public int size() { - return 0; + return size(root); + } + + public int size(BinaryNode node) { + if (node == null) { + return 0; + } else { + return size(node.left) + 1 + size(node.right); + } } /** @@ -127,9 +137,14 @@ public int size() { * @return */ public boolean isEmpty() { - return false; + return root == null; } + /** + * Utility methods + * + * @param value + */ private void print(E value) { System.out.print(value); } diff --git a/src/me/ramswaroop/trees/Tree.java b/src/me/ramswaroop/trees/Tree.java new file mode 100644 index 00000000..df128eb6 --- /dev/null +++ b/src/me/ramswaroop/trees/Tree.java @@ -0,0 +1,12 @@ +package me.ramswaroop.trees; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/19/15 + * Time: 6:30 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class Tree { + +} From 709d72a02f9e8260fa6bf2ad905804a92d9e5eed Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 19 Apr 2015 23:44:05 +0530 Subject: [PATCH 013/417] tree identical done --- src/me/ramswaroop/Main.java | 6 ++--- src/me/ramswaroop/trees/BinaryTree.java | 23 +++++++++++++++++++- src/me/ramswaroop/trees/NonRecursiveBST.java | 12 ++++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 6 +++-- 4 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 src/me/ramswaroop/trees/NonRecursiveBST.java diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 44387e67..d8f20a47 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -13,7 +13,7 @@ public static void main(String[] args) { Scanner in = new Scanner(System.in); LinkedStack stack = new LinkedStack<>(); LinkedQueue queue = new LinkedQueue<>(); - firstLoop: + chooseModule: while (true) { Utils.println("Choose module:"); Utils.println("=============="); @@ -52,7 +52,7 @@ public static void main(String[] args) { stack.print(); break; case 5: - continue firstLoop; + continue chooseModule; default: Utils.println("Wrong choice!"); } @@ -86,7 +86,7 @@ public static void main(String[] args) { queue.print(); break; case 5: - continue firstLoop; + continue chooseModule; default: Utils.println("Wrong choice!"); } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 629f4c61..f7788555 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -10,7 +10,28 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class BinaryTree extends Tree { + BinaryNode root; + public static boolean isIdentical(BinaryNode node1, BinaryNode node2) { - return false; + if (node1 == null && node2 == null) return true; + if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; + + if (node1.value == node2.value) { + return true && isIdentical(node1.left, node2.left) && isIdentical(node1.right, node2.right); + } else { + return false; + } + } + + public int height() { + return height(root); + } + + public int height(BinaryNode node) { + return 0; + } + + public boolean isIdentical(BinaryNode node) { + return isIdentical(this.root, node); } } diff --git a/src/me/ramswaroop/trees/NonRecursiveBST.java b/src/me/ramswaroop/trees/NonRecursiveBST.java new file mode 100644 index 00000000..cd9ceefe --- /dev/null +++ b/src/me/ramswaroop/trees/NonRecursiveBST.java @@ -0,0 +1,12 @@ +package me.ramswaroop.trees; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/19/15 + * Time: 11:41 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class NonRecursiveBST> extends BinarySearchTree { + +} diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 3fd7dd8e..0b979a81 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -10,9 +10,9 @@ * Time: 3:02 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class RecursiveBST> extends Tree { +public class RecursiveBST> extends BinarySearchTree { - BinaryNode root; + //BinaryNode root; public static void main(String[] a) { RecursiveBST obj = new RecursiveBST(); @@ -26,6 +26,8 @@ public static void main(String[] a) { obj.print("\n"); obj.postOrder(); Utils.println("\n" + obj.size()); + Utils.println(BinaryTree.isIdentical(obj.root.right, obj.root.right)); + Utils.println(obj.isIdentical(obj.root)); } /** From ca3160b95fed37c53fc16772aa7a16aabc8b746c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 20 Apr 2015 11:56:15 +0530 Subject: [PATCH 014/417] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e29b81dd..b188aef4 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -# JavaConcepts +# Algorithms and Data Structures in Java From 5cfb4898ea2e62a67b6f3e271207dccfec0d9976 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 22 Apr 2015 20:15:49 +0530 Subject: [PATCH 015/417] tree mirror done --- src/me/ramswaroop/trees/BinaryTree.java | 38 ++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index f7788555..e680d00d 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -23,15 +23,45 @@ public static boolean isIdentical(BinaryNode node1, BinaryNode node2) } } + public boolean isIdentical(BinaryNode node) { + return isIdentical(this.root, node); + } + + /** + * Converts a Tree to its Mirror Tree. + *

+ * MIRROR OF A BINARY TREE T is another Binary Tree M(T) with + * left and right children of all non-leaf nodes interchanged. + *

+ * TIP: In-order traversal of mirror tree is exactly the + * reverse of the in-order traversal of the original tree. + */ + public void mirror() { + mirror(root); + } + + public void mirror(BinaryNode node) { + if (node == null) return; + + BinaryNode tempNode; + + // mirror sub-trees + mirror(node.left); + mirror(node.right); + + // swap nodes + tempNode = node.left; + node.left = node.right; + node.right = tempNode; + } + public int height() { return height(root); } public int height(BinaryNode node) { - return 0; - } + if (node == null) return 0; - public boolean isIdentical(BinaryNode node) { - return isIdentical(this.root, node); + return Math.max(height(node.left), height(node.right)) + 1; } } From f0409746357c559f8e7ec27b820a7be92d44b0e0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 23 Apr 2015 09:44:10 +0530 Subject: [PATCH 016/417] tree root to leaf done --- src/me/ramswaroop/trees/BinaryTree.java | 148 ++++++++++++++++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 114 +++-------------- 2 files changed, 164 insertions(+), 98 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index e680d00d..4b51ac66 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -1,6 +1,7 @@ package me.ramswaroop.trees; import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.utils.Utils; /** * Created by IntelliJ IDEA. @@ -10,8 +11,18 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class BinaryTree extends Tree { + BinaryNode root; + /** + * Checks whether two trees having their roots at node1 and node2 + * are identical or not. + * + * @param node1 + * @param node2 + * @param + * @return + */ public static boolean isIdentical(BinaryNode node1, BinaryNode node2) { if (node1 == null && node2 == null) return true; if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; @@ -23,6 +34,83 @@ public static boolean isIdentical(BinaryNode node1, BinaryNode node2) } } + /** + * Prints the pre-order traversal of the tree. + */ + public void preOrder() { + preOrder(root); + } + + public void preOrder(BinaryNode node) { + if (node == null) { + return; + } + Utils.print(node.value); + preOrder(node.left); + preOrder(node.right); + } + + /** + * Prints the in-order traversal of the tree. + */ + public void inOrder() { + inOrder(root); + } + + public void inOrder(BinaryNode node) { + if (node == null) { + return; + } + inOrder(node.left); + Utils.print(node.value); + inOrder(node.right); + } + + /** + * Prints the post-order traversal of the tree. + */ + public void postOrder() { + postOrder(root); + } + + public void postOrder(BinaryNode node) { + if (node == null) { + return; + } + postOrder(node.left); + postOrder(node.right); + Utils.print(node.value); + } + + /** + * Deletes a particular node from the tree. + * + * @param value + */ + public void delete(E value) { + + } + + /** + * TODO + * Deletes the entire tree. + */ + public void delete() { + delete(root); + root = null; + } + + public void delete(BinaryNode node) { + if (node == null) { + return; + } + // first delete the child nodes + delete(node.left); + delete(node.right); + //Utils.println("Deleting node: " + node.value); + node = null; // delete node + } + public boolean isIdentical(BinaryNode node) { return isIdentical(this.root, node); } @@ -55,6 +143,11 @@ public void mirror(BinaryNode node) { node.right = tempNode; } + /** + * Return the height of the tree. + * + * @return + */ public int height() { return height(root); } @@ -64,4 +157,59 @@ public int height(BinaryNode node) { return Math.max(height(node.left), height(node.right)) + 1; } + + /** + * Returns the number of nodes currently in the tree. + * + * @return + */ + public int size() { + return size(root); + } + + public int size(BinaryNode node) { + if (node == null) { + return 0; + } else { + return size(node.left) + 1 + size(node.right); + } + } + + /** + * Tests if this tree is empty. + * + * @return + */ + public boolean isEmpty() { + return root == null; + } + + /** + * Prints the node to leaf paths, one per line. + */ + public void rootToLeafPaths() { + E[] pathList = (E[]) new Object[100]; + rootToLeafPaths(root, pathList, 0); + } + + public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { + if (node == null) return; + + pathList[pathLength] = node.value; + pathLength++; + + // if its a leaf node then print the list + if (node.left == null && node.right == null) { + int i; + for (i = 0; i < pathLength - 1; i++) { + Utils.print(pathList[i] + " -> "); + } + // outside the loop so that "->" doesn't appear after the last node + Utils.println(pathList[i]); + } else { + // do the same for subtrees + rootToLeafPaths(node.left, pathList, pathLength); + rootToLeafPaths(node.right, pathList, pathLength); + } + } } diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 0b979a81..3d929623 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -12,26 +12,37 @@ */ public class RecursiveBST> extends BinarySearchTree { - //BinaryNode root; - public static void main(String[] a) { RecursiveBST obj = new RecursiveBST(); obj.put(6); obj.put(3); obj.put(5); obj.put(7); + obj.put(8); + obj.put(9); obj.preOrder(); - obj.print("\n"); + Utils.println(""); obj.inOrder(); - obj.print("\n"); + Utils.println(""); obj.postOrder(); Utils.println("\n" + obj.size()); Utils.println(BinaryTree.isIdentical(obj.root.right, obj.root.right)); Utils.println(obj.isIdentical(obj.root)); + Utils.println(obj.height()); + /*obj.delete(); + Utils.println("After deletion: "); + obj.postOrder();*/ + Utils.println("In Order: "); + obj.inOrder(); + Utils.println("\nAfter mirroring: "); + obj.mirror(); + obj.inOrder(); + Utils.println("\nRoot to leafs: "); + obj.rootToLeafPaths(); } /** - * Inserts a node to the tree. + * Inserts a node into the tree. * * @param value */ @@ -58,97 +69,4 @@ public BinaryNode put(BinaryNode node, E value) { } } } - - /** - * Deletes a particular node from the tree. - * - * @param value - */ - public void delete(E value) { - - } - - /** - * Prints the pre-order traversal of the tree. - */ - public void preOrder() { - preOrder(root); - } - - public void preOrder(BinaryNode node) { - if (node == null) { - return; - } - print(node.value); - preOrder(node.left); - preOrder(node.right); - } - - /** - * Prints the in-order traversal of the tree. - */ - public void inOrder() { - inOrder(root); - } - - public void inOrder(BinaryNode node) { - if (node == null) { - return; - } - inOrder(node.left); - print(node.value); - inOrder(node.right); - } - - /** - * Prints the post-order traversal of the tree. - */ - public void postOrder() { - postOrder(root); - } - - public void postOrder(BinaryNode node) { - if (node == null) { - return; - } - postOrder(node.left); - postOrder(node.right); - print(node.value); - } - - /** - * Returns the number of nodes currently in the tree. - * - * @return - */ - public int size() { - return size(root); - } - - public int size(BinaryNode node) { - if (node == null) { - return 0; - } else { - return size(node.left) + 1 + size(node.right); - } - } - - /** - * Tests if this tree is empty. - * - * @return - */ - public boolean isEmpty() { - return root == null; - } - - /** - * Utility methods - * - * @param value - */ - private void print(E value) { - System.out.print(value); - } - } From 49100c7f00cf4456f1aaa47e4b1713916e5c1fca Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 24 Apr 2015 23:34:38 +0530 Subject: [PATCH 017/417] tree changes --- src/me/ramswaroop/common/BinaryNode.java | 2 +- src/me/ramswaroop/trees/BinarySearchTree.java | 2 +- src/me/ramswaroop/trees/BinaryTree.java | 110 ++++++++++++------ src/me/ramswaroop/trees/RecursiveBST.java | 57 ++++++++- src/me/ramswaroop/trees/Tree.java | 2 +- 5 files changed, 133 insertions(+), 40 deletions(-) diff --git a/src/me/ramswaroop/common/BinaryNode.java b/src/me/ramswaroop/common/BinaryNode.java index 360a2630..1b7f9d0e 100644 --- a/src/me/ramswaroop/common/BinaryNode.java +++ b/src/me/ramswaroop/common/BinaryNode.java @@ -7,7 +7,7 @@ * Time: 7:11 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class BinaryNode { +public class BinaryNode> { public E value; public BinaryNode left; diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/trees/BinarySearchTree.java index c794cfd6..9df1e1f8 100644 --- a/src/me/ramswaroop/trees/BinarySearchTree.java +++ b/src/me/ramswaroop/trees/BinarySearchTree.java @@ -7,6 +7,6 @@ * Time: 6:36 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class BinarySearchTree extends BinaryTree { +public class BinarySearchTree> extends BinaryTree { } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 4b51ac66..3be037d2 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -3,6 +3,9 @@ import me.ramswaroop.common.BinaryNode; import me.ramswaroop.utils.Utils; +import java.util.ArrayList; +import java.util.List; + /** * Created by IntelliJ IDEA. * User: ramswaroop @@ -10,7 +13,7 @@ * Time: 6:35 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class BinaryTree extends Tree { +public class BinaryTree> extends Tree { BinaryNode root; @@ -23,7 +26,7 @@ public class BinaryTree extends Tree { * @param * @return */ - public static boolean isIdentical(BinaryNode node1, BinaryNode node2) { + public static > boolean isIdentical(BinaryNode node1, BinaryNode node2) { if (node1 == null && node2 == null) return true; if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; @@ -111,38 +114,6 @@ public void delete(BinaryNode node) { node = null; // delete node } - public boolean isIdentical(BinaryNode node) { - return isIdentical(this.root, node); - } - - /** - * Converts a Tree to its Mirror Tree. - *

- * MIRROR OF A BINARY TREE T is another Binary Tree M(T) with - * left and right children of all non-leaf nodes interchanged. - *

- * TIP: In-order traversal of mirror tree is exactly the - * reverse of the in-order traversal of the original tree. - */ - public void mirror() { - mirror(root); - } - - public void mirror(BinaryNode node) { - if (node == null) return; - - BinaryNode tempNode; - - // mirror sub-trees - mirror(node.left); - mirror(node.right); - - // swap nodes - tempNode = node.left; - node.left = node.right; - node.right = tempNode; - } - /** * Return the height of the tree. * @@ -184,10 +155,50 @@ public boolean isEmpty() { return root == null; } + /** + * Checks whether this tree and another with @param node + * as root are identical or not. + * + * @param node + * @return + */ + public boolean isIdentical(BinaryNode node) { + return isIdentical(this.root, node); + } + + /** + * Converts a Tree to its Mirror Tree. + *

+ * MIRROR OF A BINARY TREE T is another Binary Tree M(T) with + * left and right children of all non-leaf nodes interchanged. + *

+ * TIP: In-order traversal of mirror tree is exactly the + * reverse of the in-order traversal of the original tree. + */ + public void mirror() { + mirror(root); + } + + public void mirror(BinaryNode node) { + if (node == null) return; + + BinaryNode tempNode; + + // mirror sub-trees + mirror(node.left); + mirror(node.right); + + // swap nodes + tempNode = node.left; + node.left = node.right; + node.right = tempNode; + } + /** * Prints the node to leaf paths, one per line. + * (Using array) */ - public void rootToLeafPaths() { + /*public void rootToLeafPaths() { E[] pathList = (E[]) new Object[100]; rootToLeafPaths(root, pathList, 0); } @@ -211,5 +222,34 @@ public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { rootToLeafPaths(node.left, pathList, pathLength); rootToLeafPaths(node.right, pathList, pathLength); } + }*/ + + /** + * Prints the node to leaf paths, one per line. + * (Using ArrayList) + */ + public void rootToLeafPaths() { + List pathList = new ArrayList<>(); + rootToLeafPaths(root, pathList); + } + + public void rootToLeafPaths(BinaryNode node, List pathList) { + if (node == null) return; + + pathList.add(node.value); + + // if its a leaf node then print the list + if (node.left == null && node.right == null) { + int i; + for (i = 0; i < pathList.size() - 1; i++) { + Utils.print(pathList.get(i) + " -> "); + } + // outside the loop so that "->" doesn't appear after the last node + Utils.println(pathList.get(i)); + } else { + // do the same for subtrees + rootToLeafPaths(node.left, new ArrayList<>(pathList)); + rootToLeafPaths(node.right, new ArrayList<>(pathList)); + } } } diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 3d929623..c95d9d13 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -34,11 +34,12 @@ public static void main(String[] a) { obj.postOrder();*/ Utils.println("In Order: "); obj.inOrder(); - Utils.println("\nAfter mirroring: "); + /*Utils.println("\nAfter mirroring: "); obj.mirror(); - obj.inOrder(); + obj.inOrder();*/ Utils.println("\nRoot to leafs: "); obj.rootToLeafPaths(); + Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 16, 8).value); } /** @@ -69,4 +70,56 @@ public BinaryNode put(BinaryNode node, E value) { } } } + + /** + * Determines the LCA for a BST + *

+ * DEFINITION OF LCA: + * Let T be a rooted tree. The lowest + * common ancestor between two nodes n1 and + * n2 is defined as the lowest node in T that has + * both n1 and n2 as descendants (where we allow + * a node to be a descendant of itself). + */ + public void leastCommonAncestor() { + /*int value1, value2; + Scanner in = new Scanner(System.in); + Utils.println("Enter value 1: "); + value1 = (E) Integer.valueOf(in.nextLine()); + Utils.println("Enter value 1: "); + value2 = (E) in.nextLine(); + Utils.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ + } + + public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { + if (node == null || value1.compareTo(value2) > 0) return null; + + if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) { + return node; + } else if (value1.compareTo(node.value) > 0 && value2.compareTo(node.value) > 0) { + return leastCommonAncestor(node.right, value1, value2); + } else { + return leastCommonAncestor(node.left, value1, value2); + } + } + + /** + * A recursive function that takes an ordered binary tree + * and rearranges the internal pointers to make a circular + * doubly linked list out of the tree nodes. The list should + * be arranged so that the nodes are in increasing order. + */ + public void treeToList() { + + } + + /** + * Returns the head pointer to the new list. + * + * @param node + * @return + */ + public BinaryNode treeToList(BinaryNode node) { + return null; + } } diff --git a/src/me/ramswaroop/trees/Tree.java b/src/me/ramswaroop/trees/Tree.java index df128eb6..f07a6b0d 100644 --- a/src/me/ramswaroop/trees/Tree.java +++ b/src/me/ramswaroop/trees/Tree.java @@ -7,6 +7,6 @@ * Time: 6:30 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class Tree { +public class Tree> { } From aae420accff99208127937073ca698084d554946 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 27 Apr 2015 10:32:14 +0530 Subject: [PATCH 018/417] tree: min value done --- .../{tests => practice}/BotTesting.java | 2 +- .../{tests => practice}/DivideByZero.java | 2 +- .../{tests => practice}/Equals.java | 2 +- .../GenericNonGenericMix.java | 2 +- .../MethodLocalVSInner.java | 2 +- .../{tests => practice}/Threads.java | 2 +- src/me/ramswaroop/trees/AVLTree.java | 12 +++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 26 +++++++++++++++++-- 8 files changed, 42 insertions(+), 8 deletions(-) rename src/me/ramswaroop/{tests => practice}/BotTesting.java (98%) rename src/me/ramswaroop/{tests => practice}/DivideByZero.java (90%) rename src/me/ramswaroop/{tests => practice}/Equals.java (94%) rename src/me/ramswaroop/{tests => practice}/GenericNonGenericMix.java (95%) rename src/me/ramswaroop/{tests => practice}/MethodLocalVSInner.java (95%) rename src/me/ramswaroop/{tests => practice}/Threads.java (96%) create mode 100644 src/me/ramswaroop/trees/AVLTree.java diff --git a/src/me/ramswaroop/tests/BotTesting.java b/src/me/ramswaroop/practice/BotTesting.java similarity index 98% rename from src/me/ramswaroop/tests/BotTesting.java rename to src/me/ramswaroop/practice/BotTesting.java index a33ffda7..887ce7dc 100644 --- a/src/me/ramswaroop/tests/BotTesting.java +++ b/src/me/ramswaroop/practice/BotTesting.java @@ -1,4 +1,4 @@ -package me.ramswaroop.tests; +package me.ramswaroop.practice; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/tests/DivideByZero.java b/src/me/ramswaroop/practice/DivideByZero.java similarity index 90% rename from src/me/ramswaroop/tests/DivideByZero.java rename to src/me/ramswaroop/practice/DivideByZero.java index a3c352e3..5169ba39 100644 --- a/src/me/ramswaroop/tests/DivideByZero.java +++ b/src/me/ramswaroop/practice/DivideByZero.java @@ -1,4 +1,4 @@ -package me.ramswaroop.tests; +package me.ramswaroop.practice; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/tests/Equals.java b/src/me/ramswaroop/practice/Equals.java similarity index 94% rename from src/me/ramswaroop/tests/Equals.java rename to src/me/ramswaroop/practice/Equals.java index 43def93d..82817e03 100644 --- a/src/me/ramswaroop/tests/Equals.java +++ b/src/me/ramswaroop/practice/Equals.java @@ -1,4 +1,4 @@ -package me.ramswaroop.tests; +package me.ramswaroop.practice; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/tests/GenericNonGenericMix.java b/src/me/ramswaroop/practice/GenericNonGenericMix.java similarity index 95% rename from src/me/ramswaroop/tests/GenericNonGenericMix.java rename to src/me/ramswaroop/practice/GenericNonGenericMix.java index f71a7a3a..406487e6 100644 --- a/src/me/ramswaroop/tests/GenericNonGenericMix.java +++ b/src/me/ramswaroop/practice/GenericNonGenericMix.java @@ -1,4 +1,4 @@ -package me.ramswaroop.tests; +package me.ramswaroop.practice; import java.util.ArrayList; import java.util.List; diff --git a/src/me/ramswaroop/tests/MethodLocalVSInner.java b/src/me/ramswaroop/practice/MethodLocalVSInner.java similarity index 95% rename from src/me/ramswaroop/tests/MethodLocalVSInner.java rename to src/me/ramswaroop/practice/MethodLocalVSInner.java index ec3ae677..72617088 100644 --- a/src/me/ramswaroop/tests/MethodLocalVSInner.java +++ b/src/me/ramswaroop/practice/MethodLocalVSInner.java @@ -1,4 +1,4 @@ -package me.ramswaroop.tests; +package me.ramswaroop.practice; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/tests/Threads.java b/src/me/ramswaroop/practice/Threads.java similarity index 96% rename from src/me/ramswaroop/tests/Threads.java rename to src/me/ramswaroop/practice/Threads.java index 0111b6e0..4638fe95 100644 --- a/src/me/ramswaroop/tests/Threads.java +++ b/src/me/ramswaroop/practice/Threads.java @@ -1,4 +1,4 @@ -package me.ramswaroop.tests; +package me.ramswaroop.practice; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/trees/AVLTree.java b/src/me/ramswaroop/trees/AVLTree.java new file mode 100644 index 00000000..d4c6bf7e --- /dev/null +++ b/src/me/ramswaroop/trees/AVLTree.java @@ -0,0 +1,12 @@ +package me.ramswaroop.trees; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 4/25/15 + * @time: 10:25 AM + */ +public class AVLTree> { + +} diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index c95d9d13..88334d80 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -3,6 +3,8 @@ import me.ramswaroop.common.BinaryNode; import me.ramswaroop.utils.Utils; +import java.util.NoSuchElementException; + /** * Created by IntelliJ IDEA. * User: ramswaroop @@ -39,7 +41,8 @@ public static void main(String[] a) { obj.inOrder();*/ Utils.println("\nRoot to leafs: "); obj.rootToLeafPaths(); - Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 16, 8).value); + Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 6, 8).value); + Utils.println("Min: " + obj.min().value); } /** @@ -71,6 +74,25 @@ public BinaryNode put(BinaryNode node, E value) { } } + /** + * Returns the node with minimum value. + * + * @return + */ + public BinaryNode min() { + return min(root); + } + + public BinaryNode min(BinaryNode node) { + if (node == null) throw new NoSuchElementException(); + + if (node.left == null) { + return node; + } else { + return min(node.left); + } + } + /** * Determines the LCA for a BST *

@@ -92,7 +114,7 @@ public void leastCommonAncestor() { } public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { - if (node == null || value1.compareTo(value2) > 0) return null; + if (node == null || value1.compareTo(value2) > 0) throw new NoSuchElementException(); if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) { return node; From 6c599c3f7f831a017495952b112c238a938b5a8c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 30 Apr 2015 23:17:37 +0530 Subject: [PATCH 019/417] tree to list done --- src/me/ramswaroop/common/BinaryNode.java | 5 +++ src/me/ramswaroop/trees/RecursiveBST.java | 48 ++++++++++++++++++----- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/common/BinaryNode.java b/src/me/ramswaroop/common/BinaryNode.java index 1b7f9d0e..64259869 100644 --- a/src/me/ramswaroop/common/BinaryNode.java +++ b/src/me/ramswaroop/common/BinaryNode.java @@ -19,4 +19,9 @@ public BinaryNode(E value, BinaryNode left, BinaryNode right) { this.right = right; } + public BinaryNode(BinaryNode node) { + this.value = node.value; + this.left = node.left; + this.right = node.right; + } } diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 88334d80..f7689dbf 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -14,8 +14,10 @@ */ public class RecursiveBST> extends BinarySearchTree { + BinaryNode listRoot; + public static void main(String[] a) { - RecursiveBST obj = new RecursiveBST(); + RecursiveBST obj = new RecursiveBST<>(); obj.put(6); obj.put(3); obj.put(5); @@ -43,6 +45,7 @@ public static void main(String[] a) { obj.rootToLeafPaths(); Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 6, 8).value); Utils.println("Min: " + obj.min().value); + obj.treeToList(); } /** @@ -130,18 +133,45 @@ public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) * and rearranges the internal pointers to make a circular * doubly linked list out of the tree nodes. The list should * be arranged so that the nodes are in increasing order. + * + * P.S: For a better solution - http://cslibrary.stanford.edu/109/TreeListRecursion.html */ public void treeToList() { + treeToList(root); + // print the list + BinaryNode node; + Utils.print("["); + for (node = listRoot; node.right != listRoot; node = node.right) { + Utils.print(node.value + ","); + } + Utils.print(node.value + "]"); } - /** - * Returns the head pointer to the new list. - * - * @param node - * @return - */ - public BinaryNode treeToList(BinaryNode node) { - return null; + public void treeToList(BinaryNode node) { + if (node == null) return; + + treeToList(node.left); + addToList(new BinaryNode<>(node)); + treeToList(node.right); + } + + private void addToList(BinaryNode node) { + if (listRoot == null) { + listRoot = new BinaryNode<>(node.value, null, null); + listRoot.left = listRoot; + listRoot.right = listRoot; + } else { + BinaryNode head = listRoot; + // go to the last node + while (head.right != listRoot) { + head = head.right; + } + // make it circular + head.right = node; + node.left = head; + node.right = listRoot; + listRoot.left = head; + } } } From 74835a1fbda02452a5ed4b2527660f710bc69c47 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 1 May 2015 00:22:24 +0530 Subject: [PATCH 020/417] tree: bft done --- src/me/ramswaroop/trees/BinaryTree.java | 41 ++++++++++++++++++++++- src/me/ramswaroop/trees/RecursiveBST.java | 33 ++++++++++++------ 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 3be037d2..1d33b173 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -85,6 +85,35 @@ public void postOrder(BinaryNode node) { Utils.print(node.value); } + /** + * Prints the node of the tree breadth-wise. + *

+ * DEF: Breadth-first search (BFS) is an algorithm for traversing or searching tree + * or graph data structures. It starts at the tree root (or some arbitrary node of a + * graph, sometimes referred to as a `search key'[1]) and explores the neighbor nodes + * first, before moving to the next level neighbors. + */ + public void breadthFirstTraversal() { + // assuming level starts at zero + breadthFirstTraversal(root, 0); + } + + public void breadthFirstTraversal(BinaryNode node, int level) { + if (node == null) return; + + // print the starting node + if (level == 0) printValue(node); + + // print the neighbour nodes + printValue(node.left); + printValue(node.right); + + // go to next level + level++; + breadthFirstTraversal(node.left, level); + breadthFirstTraversal(node.right, level); + } + /** * Deletes a particular node from the tree. * @@ -110,7 +139,6 @@ public void delete(BinaryNode node) { // first delete the child nodes delete(node.left); delete(node.right); - //Utils.println("Deleting node: " + node.value); node = null; // delete node } @@ -252,4 +280,15 @@ public void rootToLeafPaths(BinaryNode node, List pathList) { rootToLeafPaths(node.right, new ArrayList<>(pathList)); } } + + + /** + * Utility methods. + */ + + private void printValue(BinaryNode node) { + if (node == null) return; + + Utils.print(node.value); + } } diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index f7689dbf..3be11049 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -46,6 +46,8 @@ public static void main(String[] a) { Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 6, 8).value); Utils.println("Min: " + obj.min().value); obj.treeToList(); + Utils.println(""); + obj.breadthFirstTraversal(); } /** @@ -133,24 +135,33 @@ public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) * and rearranges the internal pointers to make a circular * doubly linked list out of the tree nodes. The list should * be arranged so that the nodes are in increasing order. - * + *

* P.S: For a better solution - http://cslibrary.stanford.edu/109/TreeListRecursion.html */ public void treeToList() { treeToList(root); // print the list - BinaryNode node; + BinaryNode current = listRoot; Utils.print("["); - for (node = listRoot; node.right != listRoot; node = node.right) { - Utils.print(node.value + ","); + if (current == null) { + System.out.print("]"); + return; + } + while (current.right != listRoot) { + Utils.print(current.value + ","); + current = current.right; } - Utils.print(node.value + "]"); + Utils.print(current.value + "]"); } public void treeToList(BinaryNode node) { if (node == null) return; + /** + * Process left node then root and then right node, so + * that the values in the list are in ascending order. + */ treeToList(node.left); addToList(new BinaryNode<>(node)); treeToList(node.right); @@ -162,16 +173,16 @@ private void addToList(BinaryNode node) { listRoot.left = listRoot; listRoot.right = listRoot; } else { - BinaryNode head = listRoot; + BinaryNode current = listRoot; // go to the last node - while (head.right != listRoot) { - head = head.right; + while (current.right != listRoot) { + current = current.right; } // make it circular - head.right = node; - node.left = head; + current.right = node; + node.left = current; node.right = listRoot; - listRoot.left = head; + listRoot.left = current; } } } From cc5a9a8c62199fe37a2558d915ac53f315805b31 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 3 May 2015 17:45:46 +0530 Subject: [PATCH 021/417] tree: bft using queue done --- src/me/ramswaroop/Main.java | 10 ++++----- src/me/ramswaroop/common/LinkedQueue.java | 2 +- src/me/ramswaroop/common/LinkedStack.java | 2 +- src/me/ramswaroop/trees/BinaryTree.java | 25 +++++++++++++++++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 4 +++- 5 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index d8f20a47..989e976f 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -41,11 +41,11 @@ public static void main(String[] args) { stack.print(); break; case 2: - stack.pop(); + Utils.println("Removed element: " + stack.pop()); stack.print(); break; case 3: - stack.peek(); + Utils.println("Front element: " + stack.peek()); stack.print(); break; case 4: @@ -63,7 +63,7 @@ public static void main(String[] args) { Utils.println("================="); Utils.println("1. Add"); Utils.println("2. Remove"); - Utils.println("3. Front Element"); + Utils.println("3. Front element"); Utils.println("4. Print"); Utils.println("5. Exit module"); k2 = Integer.parseInt(in.nextLine()); @@ -75,11 +75,11 @@ public static void main(String[] args) { queue.print(); break; case 2: - queue.remove(); + Utils.println("Removed element: " + queue.remove()); queue.print(); break; case 3: - queue.element(); + Utils.println("Front element: " + queue.element()); queue.print(); break; case 4: diff --git a/src/me/ramswaroop/common/LinkedQueue.java b/src/me/ramswaroop/common/LinkedQueue.java index edcc17c5..4c4e402f 100644 --- a/src/me/ramswaroop/common/LinkedQueue.java +++ b/src/me/ramswaroop/common/LinkedQueue.java @@ -68,7 +68,7 @@ public void print() { Node node; System.out.print("["); if (rear.next == front) { - System.out.print("]"); + System.out.println("]"); return; } for (node = front; node != rear; node = node.next) { diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java index 48400d55..da5e0171 100644 --- a/src/me/ramswaroop/common/LinkedStack.java +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -83,7 +83,7 @@ public void print() { Node node; System.out.print("["); if (top == null) { - System.out.print("]"); + System.out.println("]"); return; } for (node = top; node.next != null; node = node.next) { diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 1d33b173..fa27f7c4 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -1,10 +1,12 @@ package me.ramswaroop.trees; import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.LinkedQueue; import me.ramswaroop.utils.Utils; import java.util.ArrayList; import java.util.List; +import java.util.NoSuchElementException; /** * Created by IntelliJ IDEA. @@ -114,6 +116,29 @@ public void breadthFirstTraversal(BinaryNode node, int level) { breadthFirstTraversal(node.right, level); } + /** + * Breadth first traversal (Level-order traversal using Queue) + */ + public void breadthFirstTraversalUsingQueue() { + LinkedQueue> queue = new LinkedQueue<>(); + breadthFirstTraversalUsingQueue(root, queue); + } + + public void breadthFirstTraversalUsingQueue(BinaryNode node, LinkedQueue> queue) { + + if (node != null) { + printValue(node); + queue.add(node.left); + queue.add(node.right); + } + + try { + breadthFirstTraversalUsingQueue(queue.remove(), queue); + } catch (NoSuchElementException e) { + return; + } + } + /** * Deletes a particular node from the tree. * diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 3be11049..42490d75 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -46,8 +46,10 @@ public static void main(String[] a) { Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 6, 8).value); Utils.println("Min: " + obj.min().value); obj.treeToList(); - Utils.println(""); + Utils.println("\nBFS: "); obj.breadthFirstTraversal(); + Utils.println("\nBFS using queue: "); + obj.breadthFirstTraversalUsingQueue(); } /** From 73ca0310b8e724b651b5cbfaa23d85b6535c9552 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 4 May 2015 16:53:26 +0530 Subject: [PATCH 022/417] tree to list almost done --- src/me/ramswaroop/trees/BinaryTree.java | 25 +++---- src/me/ramswaroop/trees/RecursiveBST.java | 87 ++++++++++++----------- 2 files changed, 57 insertions(+), 55 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index fa27f7c4..35073af7 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -117,7 +117,7 @@ public void breadthFirstTraversal(BinaryNode node, int level) { } /** - * Breadth first traversal (Level-order traversal using Queue) + * Breadth first traversal (Level-order traversal using Queue). */ public void breadthFirstTraversalUsingQueue() { LinkedQueue> queue = new LinkedQueue<>(); @@ -249,13 +249,19 @@ public void mirror(BinaryNode node) { /** * Prints the node to leaf paths, one per line. - * (Using array) */ - /*public void rootToLeafPaths() { - E[] pathList = (E[]) new Object[100]; - rootToLeafPaths(root, pathList, 0); + public void rootToLeafPaths() { + List pathList = new ArrayList<>(); + rootToLeafPaths(root, pathList); + + /*E[] pathList = (E[]) new Object[100]; + rootToLeafPaths(root, pathList, 0);*/ } + /** + * Prints the node to leaf paths, one per line. + * (Using array) + */ public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { if (node == null) return; @@ -275,17 +281,12 @@ public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { rootToLeafPaths(node.left, pathList, pathLength); rootToLeafPaths(node.right, pathList, pathLength); } - }*/ + } /** * Prints the node to leaf paths, one per line. * (Using ArrayList) */ - public void rootToLeafPaths() { - List pathList = new ArrayList<>(); - rootToLeafPaths(root, pathList); - } - public void rootToLeafPaths(BinaryNode node, List pathList) { if (node == null) return; @@ -311,7 +312,7 @@ public void rootToLeafPaths(BinaryNode node, List pathList) { * Utility methods. */ - private void printValue(BinaryNode node) { + protected void printValue(BinaryNode node) { if (node == null) return; Utils.print(node.value); diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 42490d75..5baf4ad2 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -14,8 +14,6 @@ */ public class RecursiveBST> extends BinarySearchTree { - BinaryNode listRoot; - public static void main(String[] a) { RecursiveBST obj = new RecursiveBST<>(); obj.put(6); @@ -45,11 +43,12 @@ public static void main(String[] a) { obj.rootToLeafPaths(); Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 6, 8).value); Utils.println("Min: " + obj.min().value); - obj.treeToList(); - Utils.println("\nBFS: "); + Utils.println("BFS: "); obj.breadthFirstTraversal(); Utils.println("\nBFS using queue: "); obj.breadthFirstTraversalUsingQueue(); + Utils.println("\nTree to list: "); + obj.treeToList(); } /** @@ -137,54 +136,56 @@ public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) * and rearranges the internal pointers to make a circular * doubly linked list out of the tree nodes. The list should * be arranged so that the nodes are in increasing order. - *

- * P.S: For a better solution - http://cslibrary.stanford.edu/109/TreeListRecursion.html */ public void treeToList() { - treeToList(root); - // print the list - BinaryNode current = listRoot; + printList(treeToList(root)); + } + + public BinaryNode treeToList(BinaryNode node) { + if (node == null) return null; + + BinaryNode list1 = treeToList(node.left); + BinaryNode list2 = treeToList(node.right); + + node.left = node; + node.right = node; + + list1 = addToList(list1, node); + list1 = addToList(list1, list2); + + return list1; + } + + private BinaryNode addToList(BinaryNode node1, BinaryNode node2) { + + if (node1 == null) return node2; + if (node2 == null) return node1; + + node2.left = node1.left; + node2.right = node1; + node1.left.right = node2; + node1.left = node2; + + return node1; + } + + + /** + * Utility methods. + */ + + private void printList(BinaryNode node) { + BinaryNode current = node; Utils.print("["); if (current == null) { - System.out.print("]"); + System.out.println("]"); return; } - while (current.right != listRoot) { + while (current.right != node) { Utils.print(current.value + ","); current = current.right; } - Utils.print(current.value + "]"); - } - - public void treeToList(BinaryNode node) { - if (node == null) return; - - /** - * Process left node then root and then right node, so - * that the values in the list are in ascending order. - */ - treeToList(node.left); - addToList(new BinaryNode<>(node)); - treeToList(node.right); - } - - private void addToList(BinaryNode node) { - if (listRoot == null) { - listRoot = new BinaryNode<>(node.value, null, null); - listRoot.left = listRoot; - listRoot.right = listRoot; - } else { - BinaryNode current = listRoot; - // go to the last node - while (current.right != listRoot) { - current = current.right; - } - // make it circular - current.right = node; - node.left = current; - node.right = listRoot; - listRoot.left = current; - } + Utils.println(current.value + "]"); } } From 8c228fbb0ab96e7f21f6657ab32c9c512c6406a4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 4 May 2015 20:43:06 +0530 Subject: [PATCH 023/417] tree to list conversion (in place) done --- src/me/ramswaroop/practice/TreeList.java | 174 ++++++++++++++++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 34 +++-- 2 files changed, 195 insertions(+), 13 deletions(-) create mode 100644 src/me/ramswaroop/practice/TreeList.java diff --git a/src/me/ramswaroop/practice/TreeList.java b/src/me/ramswaroop/practice/TreeList.java new file mode 100644 index 00000000..eb093d53 --- /dev/null +++ b/src/me/ramswaroop/practice/TreeList.java @@ -0,0 +1,174 @@ +package me.ramswaroop.practice; + +/** + * Created by IntelliJ IDEA. + * + * @date: 5/4/15 + * @time: 8:17 PM + */ +// TreeList.java +/* + Demonstrates the greatest recursive pointer problem ever -- + recursively changing an ordered binary tree into a circular + doubly linked list. + See http://cslibrary.stanford.edu/109/ + + This code is not especially OOP. + + This code is free for any purpose. + Feb 22, 2000 + Nick Parlante nick.parlante@cs.stanford.edu +*/ + + + +/* + This is the simple Node class from which the tree and list + are built. This does not have any methods -- it's just used + as dumb storage by TreeList. + The code below tries to be clear where it treats a Node pointer + as a tree vs. where it is treated as a list. +*/ +class Node { + int data; + Node small; + Node large; + + public Node(int data) { + this.data = data; + small = null; + large = null; + } +} + + +/* + TreeList main methods: + -join() -- utility to connect two list nodes + -append() -- utility to append two lists + -treeToList() -- the core recursive function + -treeInsert() -- used to build the tree +*/ +class TreeList { + /* + helper function -- given two list nodes, join them + together so the second immediately follow the first. + Sets the .next of the first and the .previous of the second. + */ + public static void join(Node a, Node b) { + a.large = b; + b.small = a; + } + + + /* + helper function -- given two circular doubly linked + lists, append them and return the new list. + */ + public static Node append(Node a, Node b) { + // if either is null, return the other + if (a == null) return (b); + if (b == null) return (a); + + // find the last node in each using the .previous pointer + Node aLast = a.small; + Node bLast = b.small; + + // join the two together to make it connected and circular + join(aLast, b); + join(bLast, a); + + return (a); + } + + + /* + --Recursion-- + Given an ordered binary tree, recursively change it into + a circular doubly linked list which is returned. + */ + public static Node treeToList(Node root) { + // base case: empty tree -> empty list + if (root == null) return (null); + + // Recursively do the subtrees (leap of faith!) + Node aList = treeToList(root.small); + Node bList = treeToList(root.large); + + // Make the single root node into a list length-1 + // in preparation for the appending + root.small = root; + root.large = root; + + // At this point we have three lists, and it's + // just a matter of appending them together + // in the right order (aList, root, bList) + aList = append(aList, root); + aList = append(aList, bList); + + return (aList); + } + + + /* + Given a non-empty tree, insert a new node in the proper + place. The tree must be non-empty because Java's lack + of reference variables makes that case and this + method messier than they should be. + */ + public static void treeInsert(Node root, int newData) { + if (newData <= root.data) { + if (root.small != null) treeInsert(root.small, newData); + else root.small = new Node(newData); + } else { + if (root.large != null) treeInsert(root.large, newData); + else root.large = new Node(newData); + } + } + + + // Do an inorder traversal to print a tree + // Does not print the ending "\n" + public static void printTree(Node root) { + if (root == null) return; + printTree(root.small); + System.out.print(Integer.toString(root.data) + " "); + printTree(root.large); + } + + + // Do a traversal of the list and print it out + public static void printList(Node head) { + Node current = head; + + while (current != null) { + System.out.print(Integer.toString(current.data) + " "); + current = current.large; + if (current == head) break; + } + + System.out.println(); + } + + + // Demonstrate tree->list with the list 1..5 + public static void main(String[] args) { + + // first build the tree shown in the problem document + // http://cslibrary.stanford.edu/109/ + Node root = new Node(6); + treeInsert(root, 3); + treeInsert(root, 5); + treeInsert(root, 7); + treeInsert(root, 8); + treeInsert(root, 9); + + System.out.println("tree:"); + printTree(root); // 1 2 3 4 5 + System.out.println(); + + System.out.println("list:"); + Node head = treeToList(root); + printList(head); // 1 2 3 4 5 yay! + } +} diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 5baf4ad2..389714be 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -145,29 +145,37 @@ public void treeToList() { public BinaryNode treeToList(BinaryNode node) { if (node == null) return null; - BinaryNode list1 = treeToList(node.left); - BinaryNode list2 = treeToList(node.right); + BinaryNode aList = treeToList(node.left); + BinaryNode bList = treeToList(node.right); node.left = node; node.right = node; - list1 = addToList(list1, node); - list1 = addToList(list1, list2); + // attach left child then root followed by right child (so that final list is in ascending order) + aList = addToList(aList, node); + aList = addToList(aList, bList); - return list1; + return aList; } - private BinaryNode addToList(BinaryNode node1, BinaryNode node2) { + private BinaryNode addToList(BinaryNode aList, BinaryNode bList) { - if (node1 == null) return node2; - if (node2 == null) return node1; + if (aList == null) return bList; + if (bList == null) return aList; - node2.left = node1.left; - node2.right = node1; - node1.left.right = node2; - node1.left = node2; + // find the last node in each list + BinaryNode aListLast = aList.left; + BinaryNode bListLast = bList.left; - return node1; + // join end of one list to beginning of another + aListLast.right = bList; + bList.left = aListLast; + + // make circular + aListLast.left = bListLast; + bListLast.right = aList; + + return aList; } From 66a0d9741c34ec9df5b0fdadf9a95d9e1d1c99d4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 4 May 2015 23:16:48 +0530 Subject: [PATCH 024/417] tree: count leaf node done --- src/me/ramswaroop/trees/BinaryTree.java | 16 ++++++++++++++++ src/me/ramswaroop/trees/RecursiveBST.java | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 35073af7..a2af6b11 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -307,6 +307,22 @@ public void rootToLeafPaths(BinaryNode node, List pathList) { } } + /** + * Returns the number of leaf nodes in a binary tree. + * + * @param node + * @return + */ + public int countLeafNodes(BinaryNode node) { + if (node == null) { + return 0; + } else if (node.left == null && node.right == null) { + return 1; + } else { + return countLeafNodes(node.left) + countLeafNodes(node.right); + } + } + /** * Utility methods. diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 389714be..53c3b507 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -47,7 +47,8 @@ public static void main(String[] a) { obj.breadthFirstTraversal(); Utils.println("\nBFS using queue: "); obj.breadthFirstTraversalUsingQueue(); - Utils.println("\nTree to list: "); + Utils.println("\nNo. of leaf nodes: " + obj.countLeafNodes(obj.root)); + Utils.print("Tree to list: "); obj.treeToList(); } From 2ae83c2616ca408248e0f94532785a1f331440c4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 4 May 2015 23:23:51 +0530 Subject: [PATCH 025/417] tree: refactor code --- src/me/ramswaroop/trees/BinaryTree.java | 56 +++++++++++++++-------- src/me/ramswaroop/trees/RecursiveBST.java | 44 +++++++++--------- 2 files changed, 59 insertions(+), 41 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index a2af6b11..358c0315 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -19,25 +19,6 @@ public class BinaryTree> extends Tree { BinaryNode root; - /** - * Checks whether two trees having their roots at node1 and node2 - * are identical or not. - * - * @param node1 - * @param node2 - * @param - * @return - */ - public static > boolean isIdentical(BinaryNode node1, BinaryNode node2) { - if (node1 == null && node2 == null) return true; - if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; - - if (node1.value == node2.value) { - return true && isIdentical(node1.left, node2.left) && isIdentical(node1.right, node2.right); - } else { - return false; - } - } /** * Prints the pre-order traversal of the tree. @@ -55,6 +36,7 @@ public void preOrder(BinaryNode node) { preOrder(node.right); } + /** * Prints the in-order traversal of the tree. */ @@ -71,6 +53,7 @@ public void inOrder(BinaryNode node) { inOrder(node.right); } + /** * Prints the post-order traversal of the tree. */ @@ -87,6 +70,7 @@ public void postOrder(BinaryNode node) { Utils.print(node.value); } + /** * Prints the node of the tree breadth-wise. *

@@ -139,6 +123,7 @@ public void breadthFirstTraversalUsingQueue(BinaryNode node, LinkedQueue node) { node = null; // delete node } + /** * Return the height of the tree. * @@ -182,6 +168,7 @@ public int height(BinaryNode node) { return Math.max(height(node.left), height(node.right)) + 1; } + /** * Returns the number of nodes currently in the tree. * @@ -219,6 +206,27 @@ public boolean isIdentical(BinaryNode node) { return isIdentical(this.root, node); } + /** + * Checks whether two trees having their roots at node1 and node2 + * are identical or not. + * + * @param node1 + * @param node2 + * @param + * @return + */ + public static > boolean isIdentical(BinaryNode node1, BinaryNode node2) { + if (node1 == null && node2 == null) return true; + if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; + + if (node1.value == node2.value) { + return true && isIdentical(node1.left, node2.left) && isIdentical(node1.right, node2.right); + } else { + return false; + } + } + + /** * Converts a Tree to its Mirror Tree. *

@@ -247,6 +255,7 @@ public void mirror(BinaryNode node) { node.right = tempNode; } + /** * Prints the node to leaf paths, one per line. */ @@ -323,6 +332,15 @@ public int countLeafNodes(BinaryNode node) { } } + /** + * Checks whether the binary tree is a BST or not. + * + * @return + */ + public boolean isBST() { + return false; + } + /** * Utility methods. diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 53c3b507..1501fa49 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -15,41 +15,41 @@ public class RecursiveBST> extends BinarySearchTree { public static void main(String[] a) { - RecursiveBST obj = new RecursiveBST<>(); - obj.put(6); - obj.put(3); - obj.put(5); - obj.put(7); - obj.put(8); - obj.put(9); - obj.preOrder(); + RecursiveBST bst = new RecursiveBST<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + bst.preOrder(); Utils.println(""); - obj.inOrder(); + bst.inOrder(); Utils.println(""); - obj.postOrder(); - Utils.println("\n" + obj.size()); - Utils.println(BinaryTree.isIdentical(obj.root.right, obj.root.right)); - Utils.println(obj.isIdentical(obj.root)); - Utils.println(obj.height()); + bst.postOrder(); + Utils.println("\n" + bst.size()); + Utils.println(BinaryTree.isIdentical(bst.root.right, bst.root.right)); + Utils.println(bst.isIdentical(bst.root)); + Utils.println(bst.height()); /*obj.delete(); Utils.println("After deletion: "); obj.postOrder();*/ Utils.println("In Order: "); - obj.inOrder(); + bst.inOrder(); /*Utils.println("\nAfter mirroring: "); obj.mirror(); obj.inOrder();*/ Utils.println("\nRoot to leafs: "); - obj.rootToLeafPaths(); - Utils.println("LCA: " + obj.leastCommonAncestor(obj.root, 6, 8).value); - Utils.println("Min: " + obj.min().value); + bst.rootToLeafPaths(); + Utils.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); + Utils.println("Min: " + bst.min().value); Utils.println("BFS: "); - obj.breadthFirstTraversal(); + bst.breadthFirstTraversal(); Utils.println("\nBFS using queue: "); - obj.breadthFirstTraversalUsingQueue(); - Utils.println("\nNo. of leaf nodes: " + obj.countLeafNodes(obj.root)); + bst.breadthFirstTraversalUsingQueue(); + Utils.println("\nNo. of leaf nodes: " + bst.countLeafNodes(bst.root)); Utils.print("Tree to list: "); - obj.treeToList(); + bst.treeToList(); } /** From 332a666117f6c12082833ee72db3d4dcfc5823fb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 6 May 2015 23:54:01 +0530 Subject: [PATCH 026/417] tree: refactor code + insert bt done + isBST done --- src/me/ramswaroop/Main.java | 6 +- src/me/ramswaroop/trees/BinaryTree.java | 79 +++++++++++++++++++++-- src/me/ramswaroop/trees/RecursiveBST.java | 15 +++-- 3 files changed, 90 insertions(+), 10 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 989e976f..086a6a13 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -2,6 +2,8 @@ import me.ramswaroop.common.LinkedQueue; import me.ramswaroop.common.LinkedStack; +import me.ramswaroop.common.Queue; +import me.ramswaroop.common.Stack; import me.ramswaroop.utils.Utils; import java.util.Scanner; @@ -11,8 +13,8 @@ public class Main { public static void main(String[] args) { int k1, k2; Scanner in = new Scanner(System.in); - LinkedStack stack = new LinkedStack<>(); - LinkedQueue queue = new LinkedQueue<>(); + Stack stack = new LinkedStack<>(); + Queue queue = new LinkedQueue<>(); chooseModule: while (true) { Utils.println("Choose module:"); diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 358c0315..b15d81b4 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -2,6 +2,7 @@ import me.ramswaroop.common.BinaryNode; import me.ramswaroop.common.LinkedQueue; +import me.ramswaroop.common.Queue; import me.ramswaroop.utils.Utils; import java.util.ArrayList; @@ -18,6 +19,50 @@ public class BinaryTree> extends Tree { BinaryNode root; + Queue> queue = new LinkedQueue<>(); // needed for insertion + + public static void main(String[] a) { + BinaryTree binaryTree = new BinaryTree<>(); + binaryTree.put(5); + binaryTree.put(3); + binaryTree.put(8); + binaryTree.put(2); + binaryTree.put(4); + binaryTree.put(6); + binaryTree.breadthFirstTraversal(); + Utils.println(""); + binaryTree.inOrder(); + Utils.println("\nIs BST: " + binaryTree.isBST()); + } + + /** + * Inserts a node into the binary tree such that + * it always forms a complete binary tree. + * + * @param value + */ + public void put(E value) { + put(root, value); + } + + public BinaryNode put(BinaryNode node, E value) { + // create a new node from the value + BinaryNode newNode = new BinaryNode<>(value, null, null); + + if (node == null) { + return root = queue.add(newNode); + } else { + BinaryNode parentNode = queue.element(); + if (parentNode.left == null) { + parentNode.left = newNode; + } else if (parentNode.right == null) { + parentNode.right = newNode; + queue.remove(); + } + queue.add(newNode); + } + return node; + } /** @@ -104,11 +149,11 @@ public void breadthFirstTraversal(BinaryNode node, int level) { * Breadth first traversal (Level-order traversal using Queue). */ public void breadthFirstTraversalUsingQueue() { - LinkedQueue> queue = new LinkedQueue<>(); + Queue> queue = new LinkedQueue<>(); breadthFirstTraversalUsingQueue(root, queue); } - public void breadthFirstTraversalUsingQueue(BinaryNode node, LinkedQueue> queue) { + public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue> queue) { if (node != null) { printValue(node); @@ -319,9 +364,12 @@ public void rootToLeafPaths(BinaryNode node, List pathList) { /** * Returns the number of leaf nodes in a binary tree. * - * @param node * @return */ + public int countLeafNodes() { + return countLeafNodes(root); + } + public int countLeafNodes(BinaryNode node) { if (node == null) { return 0; @@ -332,13 +380,36 @@ public int countLeafNodes(BinaryNode node) { } } + /** * Checks whether the binary tree is a BST or not. * * @return */ public boolean isBST() { - return false; + return isBST(root); + } + + public boolean isBST(BinaryNode node) { + if (node == null || (node.left == null && node.right == null)) return true; + + if (node.left == null && node.right != null) { + if (node.right.value.compareTo(node.value) > 0) { + return true; + } else { + return false; + } + } else if (node.left != null && node.right == null) { + if (node.left.value.compareTo(node.value) < 0) { + return true; + } else { + return false; + } + } else if (node.left.value.compareTo(node.value) < 0 && node.right.value.compareTo(node.value) > 0) { + return isBST(node.left) && isBST(node.right); + } else { + return false; + } } diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index 1501fa49..e1dbdbdb 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -47,13 +47,15 @@ public static void main(String[] a) { bst.breadthFirstTraversal(); Utils.println("\nBFS using queue: "); bst.breadthFirstTraversalUsingQueue(); - Utils.println("\nNo. of leaf nodes: " + bst.countLeafNodes(bst.root)); + Utils.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); + Utils.println("Is BST: " + bst.isBST()); Utils.print("Tree to list: "); bst.treeToList(); } + /** - * Inserts a node into the tree. + * Inserts a node into the BST. * * @param value */ @@ -62,18 +64,20 @@ public void put(E value) { } public BinaryNode put(BinaryNode node, E value) { + BinaryNode newNode = new BinaryNode<>(value, null, null); + if (node == null) { return root = new BinaryNode<>(value, null, null); } else { if (value.compareTo(node.value) < 0) { if (node.left == null) { - return node.left = new BinaryNode<>(value, null, null); + return node.left = newNode; } else { return put(node.left, value); } } else { if (node.right == null) { - return node.right = new BinaryNode<>(value, null, null); + return node.right = newNode; } else { return put(node.right, value); } @@ -81,6 +85,7 @@ public BinaryNode put(BinaryNode node, E value) { } } + /** * Returns the node with minimum value. * @@ -100,6 +105,7 @@ public BinaryNode min(BinaryNode node) { } } + /** * Determines the LCA for a BST *

@@ -132,6 +138,7 @@ public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) } } + /** * A recursive function that takes an ordered binary tree * and rearranges the internal pointers to make a circular From d3d0e9d4fd594b2d71fe86b71b46dd6d5c4c1433 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 7 May 2015 10:44:27 +0530 Subject: [PATCH 027/417] tree: isBST fixed --- src/me/ramswaroop/trees/BinaryTree.java | 39 ++++++++++++------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index b15d81b4..d213a0ff 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -25,10 +25,10 @@ public static void main(String[] a) { BinaryTree binaryTree = new BinaryTree<>(); binaryTree.put(5); binaryTree.put(3); - binaryTree.put(8); + binaryTree.put(9); binaryTree.put(2); binaryTree.put(4); - binaryTree.put(6); + binaryTree.put(8); binaryTree.breadthFirstTraversal(); Utils.println(""); binaryTree.inOrder(); @@ -384,32 +384,31 @@ public int countLeafNodes(BinaryNode node) { /** * Checks whether the binary tree is a BST or not. * + * Approach: Performs in-order traversal of the tree and if + * the result isn't in ascending order then returns false. + * * @return */ public boolean isBST() { - return isBST(root); + List> list = new ArrayList<>(); + return isBST(root, list); } - public boolean isBST(BinaryNode node) { - if (node == null || (node.left == null && node.right == null)) return true; + public boolean isBST(BinaryNode node, List> list) { + if (node == null) return true; - if (node.left == null && node.right != null) { - if (node.right.value.compareTo(node.value) > 0) { - return true; - } else { - return false; - } - } else if (node.left != null && node.right == null) { - if (node.left.value.compareTo(node.value) < 0) { - return true; - } else { - return false; - } - } else if (node.left.value.compareTo(node.value) < 0 && node.right.value.compareTo(node.value) > 0) { - return isBST(node.left) && isBST(node.right); - } else { + boolean left = isBST(node.left, list); + + // while adding node to list, compare it with previous node in list + if (list.size() > 0 && list.get(list.size() - 1).value.compareTo(node.value) > 0) { return false; + } else { + list.add(node); } + + boolean right = isBST(node.right, list); + + return left && right; } From f21f94511a687044483788389d48b3ab14bbd158 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 7 May 2015 12:24:45 +0530 Subject: [PATCH 028/417] isBST using prev node --- src/me/ramswaroop/common/BinaryNode.java | 2 ++ src/me/ramswaroop/trees/BinaryTree.java | 41 +++++++++++++++++++++--- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/common/BinaryNode.java b/src/me/ramswaroop/common/BinaryNode.java index 64259869..a572f57e 100644 --- a/src/me/ramswaroop/common/BinaryNode.java +++ b/src/me/ramswaroop/common/BinaryNode.java @@ -20,6 +20,8 @@ public BinaryNode(E value, BinaryNode left, BinaryNode right) { } public BinaryNode(BinaryNode node) { + if (node == null) return; + this.value = node.value; this.left = node.left; this.right = node.right; diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index d213a0ff..7f667e66 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -28,7 +28,7 @@ public static void main(String[] a) { binaryTree.put(9); binaryTree.put(2); binaryTree.put(4); - binaryTree.put(8); + binaryTree.put(18); binaryTree.breadthFirstTraversal(); Utils.println(""); binaryTree.inOrder(); @@ -383,17 +383,26 @@ public int countLeafNodes(BinaryNode node) { /** * Checks whether the binary tree is a BST or not. - * + *

* Approach: Performs in-order traversal of the tree and if * the result isn't in ascending order then returns false. * * @return */ public boolean isBST() { - List> list = new ArrayList<>(); - return isBST(root, list); + //List> list = new ArrayList<>(); + BinaryNode prev = null; + return isBST(root, prev); } + /** + * Traverse the tree in in-order fashion and insert all nodes + * in a list and check for sort order of list. + * + * @param node + * @param list + * @return + */ public boolean isBST(BinaryNode node, List> list) { if (node == null) return true; @@ -411,6 +420,30 @@ public boolean isBST(BinaryNode node, List> list) { return left && right; } + /** + * Traverse the tree in in-order fashion and keep track of prev node. + * + * @param node + * @param prev + * @return + */ + public boolean isBST(BinaryNode node, BinaryNode prev) { + if (node == null) return true; + + boolean left = isBST(node.left, prev); + + // compare current node with previous node + if (prev != null && prev.value.compareTo(node.value) > 0) { + return false; + } else { + prev = node; + } + + boolean right = isBST(node.right, prev); + + return left && right; + } + /** * Utility methods. From afa26dbbd83d297509db87cf034b0eb2693b9624 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 7 May 2015 12:28:42 +0530 Subject: [PATCH 029/417] added comments --- src/me/ramswaroop/trees/BinaryTree.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 7f667e66..b5d34622 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -57,7 +57,7 @@ public BinaryNode put(BinaryNode node, E value) { parentNode.left = newNode; } else if (parentNode.right == null) { parentNode.right = newNode; - queue.remove(); + queue.remove(); // parent node has both left and right child now, so dequeue it } queue.add(newNode); } From f411e19485b1c33ad02ee3d7e4f1fbdc5c7de31d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 7 May 2015 16:38:27 +0530 Subject: [PATCH 030/417] tree: isBST done with prev node --- src/me/ramswaroop/trees/BinaryTree.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index b5d34622..919f6d6c 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -23,12 +23,13 @@ public class BinaryTree> extends Tree { public static void main(String[] a) { BinaryTree binaryTree = new BinaryTree<>(); - binaryTree.put(5); + binaryTree.put(6); binaryTree.put(3); binaryTree.put(9); binaryTree.put(2); binaryTree.put(4); - binaryTree.put(18); + binaryTree.put(5); + //binaryTree.put(16); binaryTree.breadthFirstTraversal(); Utils.println(""); binaryTree.inOrder(); @@ -391,7 +392,7 @@ public int countLeafNodes(BinaryNode node) { */ public boolean isBST() { //List> list = new ArrayList<>(); - BinaryNode prev = null; + BinaryNode prev = new BinaryNode<>(null); return isBST(root, prev); } @@ -411,9 +412,8 @@ public boolean isBST(BinaryNode node, List> list) { // while adding node to list, compare it with previous node in list if (list.size() > 0 && list.get(list.size() - 1).value.compareTo(node.value) > 0) { return false; - } else { - list.add(node); } + list.add(node); boolean right = isBST(node.right, list); @@ -433,11 +433,10 @@ public boolean isBST(BinaryNode node, BinaryNode prev) { boolean left = isBST(node.left, prev); // compare current node with previous node - if (prev != null && prev.value.compareTo(node.value) > 0) { + if (prev.value != null && prev.value.compareTo(node.value) > 0) { return false; - } else { - prev = node; } + prev.value = node.value; boolean right = isBST(node.right, prev); From 4bc46df149e9e23c4ca9b293020c23c20ccaff3d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 8 May 2015 13:01:44 +0530 Subject: [PATCH 031/417] method overloading concepts --- .../practice/MethodOverloading.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/me/ramswaroop/practice/MethodOverloading.java diff --git a/src/me/ramswaroop/practice/MethodOverloading.java b/src/me/ramswaroop/practice/MethodOverloading.java new file mode 100644 index 00000000..ff331734 --- /dev/null +++ b/src/me/ramswaroop/practice/MethodOverloading.java @@ -0,0 +1,55 @@ +package me.ramswaroop.practice; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/8/15 + * @time: 12:08 PM + */ +class MethodOverloading { + + static void go(Long x) { + System.out.print("Long "); + } + + static void go(double x) { + System.out.print("double "); + } + + static void go(Double x) { + System.out.print("Double "); + } + + static void go(int x, int y) { + System.out.print("int,int "); + } + + static void go(byte... x) { + System.out.print("byte... "); + } + + static void go(Long x, Long y) { + System.out.print("Long,Long "); + } + + static void go(long... x) { + System.out.print("long... "); + } + + public static void main(String[] args) { + byte b = 5; + short s = 5; + long l = 5; + float f = 5.0f; + // widening beats autoboxing + go(b); + go(s); + go(l); + go(f); + // widening beats var-args + go(b, b); + // auto-boxing beats var-args + go(l, l); + } +} From 7622c67576dac0bfdc40f777946e7322f38f21ae Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 10 May 2015 16:12:22 +0530 Subject: [PATCH 032/417] tree: spiral traversal done using stacks --- src/me/ramswaroop/trees/BinaryTree.java | 98 +++++++++++++++++++++++-- 1 file changed, 93 insertions(+), 5 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 919f6d6c..e434755c 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -1,11 +1,10 @@ package me.ramswaroop.trees; -import me.ramswaroop.common.BinaryNode; -import me.ramswaroop.common.LinkedQueue; -import me.ramswaroop.common.Queue; +import me.ramswaroop.common.*; import me.ramswaroop.utils.Utils; import java.util.ArrayList; +import java.util.EmptyStackException; import java.util.List; import java.util.NoSuchElementException; @@ -30,10 +29,13 @@ public static void main(String[] a) { binaryTree.put(4); binaryTree.put(5); //binaryTree.put(16); + Utils.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); - Utils.println(""); + Utils.print("\nSpiral Traversal: "); + binaryTree.spiralTraversal(); + Utils.print("\nIn order traversal: "); binaryTree.inOrder(); - Utils.println("\nIs BST: " + binaryTree.isBST()); + Utils.print("\nIs BST: " + binaryTree.isBST()); } /** @@ -170,6 +172,90 @@ public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue node, int level) { + if (node == null) return; + + // print the starting node + if (level == 0) printValue(node); + + // print the neighbour nodes + if (level % 2 == 0) { + printValue(node.left); + printValue(node.right); + } else { + printValue(node.right); + printValue(node.left); + } + + // go to next level + level++; + if (level % 2 == 0) { + spiralTraversal(node.left, level); + spiralTraversal(node.right, level); + } else { + spiralTraversal(node.right, level); + spiralTraversal(node.left, level); + } + } + + public void spiralTraversal(BinaryNode node) { + Stack> stack1 = new LinkedStack<>(); // for nodes to be printed ltr + Stack> stack2 = new LinkedStack<>(); // for nodes to be printed rtl + + printValue(node); + + stack1.push(node.right); + stack1.push(node.left); + + // pop stack1 and push their child nodes in stack2 + while (!stack1.isEmpty()) { + + BinaryNode leftChild = stack1.pop(); + BinaryNode rightChild = stack1.pop(); + + printValue(leftChild); + printValue(rightChild); + + try { + if (leftChild != null) stack2.push(leftChild.left); + if (leftChild != null) stack2.push(leftChild.right); + if (rightChild != null) stack2.push(rightChild.left); + if (rightChild != null) stack2.push(rightChild.right); + } catch (EmptyStackException e) { + // ignore error when stack empty + } + } + + // pop stack2 and push their child nodes in stack1 + while (!stack2.isEmpty()) { + + BinaryNode rightChild = stack2.pop(); + BinaryNode leftChild = stack2.pop(); + + printValue(rightChild); + printValue(leftChild); + + try { + if (rightChild != null) stack1.push(rightChild.right); + if (rightChild != null) stack1.push(rightChild.left); + if (leftChild != null) stack1.push(leftChild.right); + if (leftChild != null) stack1.push(leftChild.left); + } catch (EmptyStackException e) { + // ignore error when stack empty + } + } + } + + /** * Deletes a particular node from the tree. * @@ -422,6 +508,8 @@ public boolean isBST(BinaryNode node, List> list) { /** * Traverse the tree in in-order fashion and keep track of prev node. + *

+ * TODO Clarify doubt: Why it doesn't work if I replace "prev.value" with "prev" * * @param node * @param prev From f76fd8a65f10af3b78ea4d0965c27214483c5656 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 10 May 2015 19:34:22 +0530 Subject: [PATCH 033/417] tree: is children sum done --- src/me/ramswaroop/trees/BinaryTree.java | 41 +++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index e434755c..5b94472f 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -22,13 +22,19 @@ public class BinaryTree> extends Tree { public static void main(String[] a) { BinaryTree binaryTree = new BinaryTree<>(); - binaryTree.put(6); + /*binaryTree.put(6); binaryTree.put(3); binaryTree.put(9); binaryTree.put(2); binaryTree.put(4); + binaryTree.put(5);*/ + binaryTree.put(10); + binaryTree.put(8); + binaryTree.put(2); + binaryTree.put(3); binaryTree.put(5); - //binaryTree.put(16); + binaryTree.put(1); + binaryTree.put(1); Utils.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); Utils.print("\nSpiral Traversal: "); @@ -36,6 +42,7 @@ public static void main(String[] a) { Utils.print("\nIn order traversal: "); binaryTree.inOrder(); Utils.print("\nIs BST: " + binaryTree.isBST()); + Utils.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); } /** @@ -531,6 +538,36 @@ public boolean isBST(BinaryNode node, BinaryNode prev) { return left && right; } + /** + * For every node, the value must be equal to + * sum of values in the left and right child. + * Consider data value as 0 for NULL child. + * + * @return + */ + public boolean isChildrenSum() { + return isChildrenSum(root); + } + + public boolean isChildrenSum(BinaryNode node) { + if (node == null || node.left == null && node.right == null) return true; + + E leftChildValue = (E) (node.left == null ? 0 : node.left.value); + E rightChildValue = (E) (node.right == null ? 0 : node.right.value); + + boolean left = isChildrenSum(node.left); + boolean right = isChildrenSum(node.right); + + if (!node.value.toString().equals( + String.valueOf(Integer.parseInt(leftChildValue.toString()) + + Integer.parseInt(rightChildValue.toString())) + )) { + return false; + } + + return left && right; + } + /** * Utility methods. From 59bfb0fa6282aa9837ee36bc4a91b6339de5c8ea Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 10 May 2015 19:39:04 +0530 Subject: [PATCH 034/417] changed to static import for System.out --- src/me/ramswaroop/trees/BinaryTree.java | 29 ++++++------- src/me/ramswaroop/trees/RecursiveBST.java | 51 ++++++++++++----------- src/me/ramswaroop/utils/Utils.java | 7 +--- 3 files changed, 42 insertions(+), 45 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 5b94472f..6f73df75 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -1,13 +1,14 @@ package me.ramswaroop.trees; import me.ramswaroop.common.*; -import me.ramswaroop.utils.Utils; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.List; import java.util.NoSuchElementException; +import static java.lang.System.out; + /** * Created by IntelliJ IDEA. * User: ramswaroop @@ -35,14 +36,14 @@ public static void main(String[] a) { binaryTree.put(5); binaryTree.put(1); binaryTree.put(1); - Utils.print("Breadth-first Traversal: "); + out.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); - Utils.print("\nSpiral Traversal: "); + out.print("\nSpiral Traversal: "); binaryTree.spiralTraversal(); - Utils.print("\nIn order traversal: "); + out.print("\nIn order traversal: "); binaryTree.inOrder(); - Utils.print("\nIs BST: " + binaryTree.isBST()); - Utils.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); + out.print("\nIs BST: " + binaryTree.isBST()); + out.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); } /** @@ -86,7 +87,7 @@ public void preOrder(BinaryNode node) { if (node == null) { return; } - Utils.print(node.value); + out.print(node.value); preOrder(node.left); preOrder(node.right); } @@ -104,7 +105,7 @@ public void inOrder(BinaryNode node) { return; } inOrder(node.left); - Utils.print(node.value); + out.print(node.value); inOrder(node.right); } @@ -122,7 +123,7 @@ public void postOrder(BinaryNode node) { } postOrder(node.left); postOrder(node.right); - Utils.print(node.value); + out.print(node.value); } @@ -420,10 +421,10 @@ public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { if (node.left == null && node.right == null) { int i; for (i = 0; i < pathLength - 1; i++) { - Utils.print(pathList[i] + " -> "); + out.print(pathList[i] + " -> "); } // outside the loop so that "->" doesn't appear after the last node - Utils.println(pathList[i]); + out.println(pathList[i]); } else { // do the same for subtrees rootToLeafPaths(node.left, pathList, pathLength); @@ -444,10 +445,10 @@ public void rootToLeafPaths(BinaryNode node, List pathList) { if (node.left == null && node.right == null) { int i; for (i = 0; i < pathList.size() - 1; i++) { - Utils.print(pathList.get(i) + " -> "); + out.print(pathList.get(i) + " -> "); } // outside the loop so that "->" doesn't appear after the last node - Utils.println(pathList.get(i)); + out.println(pathList.get(i)); } else { // do the same for subtrees rootToLeafPaths(node.left, new ArrayList<>(pathList)); @@ -576,6 +577,6 @@ public boolean isChildrenSum(BinaryNode node) { protected void printValue(BinaryNode node) { if (node == null) return; - Utils.print(node.value); + out.print(node.value); } } diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java index e1dbdbdb..b2813676 100644 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ b/src/me/ramswaroop/trees/RecursiveBST.java @@ -1,10 +1,11 @@ package me.ramswaroop.trees; import me.ramswaroop.common.BinaryNode; -import me.ramswaroop.utils.Utils; import java.util.NoSuchElementException; +import static java.lang.System.out; + /** * Created by IntelliJ IDEA. * User: ramswaroop @@ -23,33 +24,33 @@ public static void main(String[] a) { bst.put(8); bst.put(9); bst.preOrder(); - Utils.println(""); + out.println(""); bst.inOrder(); - Utils.println(""); + out.println(""); bst.postOrder(); - Utils.println("\n" + bst.size()); - Utils.println(BinaryTree.isIdentical(bst.root.right, bst.root.right)); - Utils.println(bst.isIdentical(bst.root)); - Utils.println(bst.height()); + out.println("\n" + bst.size()); + out.println(BinaryTree.isIdentical(bst.root.right, bst.root.right)); + out.println(bst.isIdentical(bst.root)); + out.println(bst.height()); /*obj.delete(); - Utils.println("After deletion: "); + out.println("After deletion: "); obj.postOrder();*/ - Utils.println("In Order: "); + out.println("In Order: "); bst.inOrder(); - /*Utils.println("\nAfter mirroring: "); + /*out.println("\nAfter mirroring: "); obj.mirror(); obj.inOrder();*/ - Utils.println("\nRoot to leafs: "); + out.println("\nRoot to leafs: "); bst.rootToLeafPaths(); - Utils.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); - Utils.println("Min: " + bst.min().value); - Utils.println("BFS: "); + out.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); + out.println("Min: " + bst.min().value); + out.println("BFS: "); bst.breadthFirstTraversal(); - Utils.println("\nBFS using queue: "); + out.println("\nBFS using queue: "); bst.breadthFirstTraversalUsingQueue(); - Utils.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); - Utils.println("Is BST: " + bst.isBST()); - Utils.print("Tree to list: "); + out.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); + out.println("Is BST: " + bst.isBST()); + out.print("Tree to list: "); bst.treeToList(); } @@ -119,11 +120,11 @@ public BinaryNode min(BinaryNode node) { public void leastCommonAncestor() { /*int value1, value2; Scanner in = new Scanner(System.in); - Utils.println("Enter value 1: "); + out.println("Enter value 1: "); value1 = (E) Integer.valueOf(in.nextLine()); - Utils.println("Enter value 1: "); + out.println("Enter value 1: "); value2 = (E) in.nextLine(); - Utils.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ + out.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ } public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { @@ -193,15 +194,15 @@ private BinaryNode addToList(BinaryNode aList, BinaryNode bList) { private void printList(BinaryNode node) { BinaryNode current = node; - Utils.print("["); + out.print("["); if (current == null) { - System.out.println("]"); + out.println("]"); return; } while (current.right != node) { - Utils.print(current.value + ","); + out.print(current.value + ","); current = current.right; } - Utils.println(current.value + "]"); + out.println(current.value + "]"); } } diff --git a/src/me/ramswaroop/utils/Utils.java b/src/me/ramswaroop/utils/Utils.java index 613b55ca..448c4205 100644 --- a/src/me/ramswaroop/utils/Utils.java +++ b/src/me/ramswaroop/utils/Utils.java @@ -8,10 +8,5 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class Utils { - public static void print(Object o) { - System.out.print(o); - } - public static void println(Object o) { - System.out.println(o); - } + } From d793c9f8f9b2f8a977a18b7722e96b1d4358a085 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 11 May 2015 23:38:02 +0530 Subject: [PATCH 035/417] convert binary tree to hold children sum invariant --- src/me/ramswaroop/Main.java | 63 +++++++++++++------------ src/me/ramswaroop/trees/BinaryTree.java | 53 ++++++++++++++++++++- 2 files changed, 83 insertions(+), 33 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 086a6a13..32148cf2 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -4,10 +4,11 @@ import me.ramswaroop.common.LinkedStack; import me.ramswaroop.common.Queue; import me.ramswaroop.common.Stack; -import me.ramswaroop.utils.Utils; import java.util.Scanner; +import static java.lang.System.out; + public class Main { public static void main(String[] args) { @@ -17,37 +18,37 @@ public static void main(String[] args) { Queue queue = new LinkedQueue<>(); chooseModule: while (true) { - Utils.println("Choose module:"); - Utils.println("=============="); - Utils.println("1. Stack"); - Utils.println("2. Queue"); - Utils.println("3. BST"); - Utils.println("4. Exit"); + out.println("Choose module:"); + out.println("=============="); + out.println("1. Stack"); + out.println("2. Queue"); + out.println("3. BST"); + out.println("4. Exit"); k1 = Integer.parseInt(in.nextLine()); switch (k1) { case 1: while (true) { - Utils.println("Select operation:"); - Utils.println("================="); - Utils.println("1. Push"); - Utils.println("2. Pop"); - Utils.println("3. Peek"); - Utils.println("4. Print"); - Utils.println("5. Exit module"); + out.println("Select operation:"); + out.println("================="); + out.println("1. Push"); + out.println("2. Pop"); + out.println("3. Peek"); + out.println("4. Print"); + out.println("5. Exit module"); k2 = Integer.parseInt(in.nextLine()); switch (k2) { case 1: - Utils.println("Enter value:"); + out.println("Enter value:"); int input = Integer.parseInt(in.nextLine()); stack.push(input); stack.print(); break; case 2: - Utils.println("Removed element: " + stack.pop()); + out.println("Removed element: " + stack.pop()); stack.print(); break; case 3: - Utils.println("Front element: " + stack.peek()); + out.println("Front element: " + stack.peek()); stack.print(); break; case 4: @@ -56,32 +57,32 @@ public static void main(String[] args) { case 5: continue chooseModule; default: - Utils.println("Wrong choice!"); + out.println("Wrong choice!"); } } case 2: while (true) { - Utils.println("Select operation:"); - Utils.println("================="); - Utils.println("1. Add"); - Utils.println("2. Remove"); - Utils.println("3. Front element"); - Utils.println("4. Print"); - Utils.println("5. Exit module"); + out.println("Select operation:"); + out.println("================="); + out.println("1. Add"); + out.println("2. Remove"); + out.println("3. Front element"); + out.println("4. Print"); + out.println("5. Exit module"); k2 = Integer.parseInt(in.nextLine()); switch (k2) { case 1: - Utils.println("Enter value:"); + out.println("Enter value:"); int input = Integer.parseInt(in.nextLine()); queue.add(input); queue.print(); break; case 2: - Utils.println("Removed element: " + queue.remove()); + out.println("Removed element: " + queue.remove()); queue.print(); break; case 3: - Utils.println("Front element: " + queue.element()); + out.println("Front element: " + queue.element()); queue.print(); break; case 4: @@ -90,16 +91,16 @@ public static void main(String[] args) { case 5: continue chooseModule; default: - Utils.println("Wrong choice!"); + out.println("Wrong choice!"); } } case 3: break; case 4: - Utils.println("Exiting..."); + out.println("Exiting..."); System.exit(0); default: - Utils.println("Wrong choice!"); + out.println("Wrong choice!"); } } } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 6f73df75..89c9d552 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -31,7 +31,7 @@ public static void main(String[] a) { binaryTree.put(5);*/ binaryTree.put(10); binaryTree.put(8); - binaryTree.put(2); + binaryTree.put(1); binaryTree.put(3); binaryTree.put(5); binaryTree.put(1); @@ -44,6 +44,9 @@ public static void main(String[] a) { binaryTree.inOrder(); out.print("\nIs BST: " + binaryTree.isBST()); out.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); + binaryTree.toChildrenSum(); + out.print("\nBreadth-first Traversal after to children sum: "); + binaryTree.breadthFirstTraversal(); } /** @@ -540,7 +543,7 @@ public boolean isBST(BinaryNode node, BinaryNode prev) { } /** - * For every node, the value must be equal to + * Children Sum Invariant: For every node, the value must be equal to * sum of values in the left and right child. * Consider data value as 0 for NULL child. * @@ -569,6 +572,52 @@ public boolean isChildrenSum(BinaryNode node) { return left && right; } + /** + * Converts a tree to hold the children sum invariant. + *

+ * It only increments data values in any node (Does not + * change structure of tree and cannot decrement value of + * any node). + */ + public void toChildrenSum() { + toChildrenSum(root); + } + + public void toChildrenSum(BinaryNode node) { + + if (node == null || node.left == null && node.right == null) return; + + toChildrenSum(node.left); + toChildrenSum(node.right); + + Integer nodeValue = (Integer) (node == null ? 0 : node.value); + Integer leftChildValue = (Integer) (node.left == null ? 0 : node.left.value); + Integer rightChildValue = (Integer) (node.right == null ? 0 : node.right.value); + + int diff = (nodeValue - (leftChildValue + rightChildValue)); + + if (diff < 0) { + increment(node, diff); + } else if (diff > 0) { + if (node.left != null) { + increment(node.left, diff); + } else { + increment(node.right, diff); + } + } + } + + // TODO + private void increment(BinaryNode node, int diff) { + if (node.left != null) { + //node.value += Math.abs(diff); + increment(node.left, diff); + } else if (node.right != null) { + //node.value += Math.abs(diff); + increment(node.right, diff); + } + } + /** * Utility methods. From 16dcd26e25b13239a388268c887c9afdcf4f5741 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 11 May 2015 23:41:20 +0530 Subject: [PATCH 036/417] code refactoring --- src/me/ramswaroop/trees/BinarySearchTree.java | 195 ++++++++++++++++ src/me/ramswaroop/trees/BinaryTree.java | 15 ++ src/me/ramswaroop/trees/NonRecursiveBST.java | 12 - src/me/ramswaroop/trees/RecursiveBST.java | 208 ------------------ 4 files changed, 210 insertions(+), 220 deletions(-) delete mode 100644 src/me/ramswaroop/trees/NonRecursiveBST.java delete mode 100644 src/me/ramswaroop/trees/RecursiveBST.java diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/trees/BinarySearchTree.java index 9df1e1f8..63527b72 100644 --- a/src/me/ramswaroop/trees/BinarySearchTree.java +++ b/src/me/ramswaroop/trees/BinarySearchTree.java @@ -1,5 +1,11 @@ package me.ramswaroop.trees; +import me.ramswaroop.common.BinaryNode; + +import java.util.NoSuchElementException; + +import static java.lang.System.out; + /** * Created by IntelliJ IDEA. * User: ramswaroop @@ -8,5 +14,194 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class BinarySearchTree> extends BinaryTree { + public static void main(String[] a) { + BinarySearchTree bst = new BinarySearchTree<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + bst.preOrder(); + out.println(""); + bst.inOrder(); + out.println(""); + bst.postOrder(); + out.println("\n" + bst.size()); + out.println(BinaryTree.isIdentical(bst.root.right, bst.root.right)); + out.println(bst.isIdentical(bst.root)); + out.println(bst.height()); + /*obj.delete(); + out.println("After deletion: "); + obj.postOrder();*/ + out.println("In Order: "); + bst.inOrder(); + /*out.println("\nAfter mirroring: "); + obj.mirror(); + obj.inOrder();*/ + out.println("\nRoot to leafs: "); + bst.rootToLeafPaths(); + out.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); + out.println("Min: " + bst.min().value); + out.println("BFS: "); + bst.breadthFirstTraversal(); + out.println("\nBFS using queue: "); + bst.breadthFirstTraversalUsingQueue(); + out.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); + out.println("Is BST: " + bst.isBST()); + out.print("Tree to list: "); + bst.treeToList(); + } + + + /** + * Inserts a node into the BST. + * + * @param value + */ + public void put(E value) { + put(root, value); + } + + public BinaryNode put(BinaryNode node, E value) { + BinaryNode newNode = new BinaryNode<>(value, null, null); + + if (node == null) { + return root = new BinaryNode<>(value, null, null); + } else { + if (value.compareTo(node.value) < 0) { + if (node.left == null) { + return node.left = newNode; + } else { + return put(node.left, value); + } + } else { + if (node.right == null) { + return node.right = newNode; + } else { + return put(node.right, value); + } + } + } + } + + + /** + * Returns the node with minimum value. + * + * @return + */ + public BinaryNode min() { + return min(root); + } + + public BinaryNode min(BinaryNode node) { + if (node == null) throw new NoSuchElementException(); + + if (node.left == null) { + return node; + } else { + return min(node.left); + } + } + + + /** + * Determines the LCA for a BST + *

+ * DEFINITION OF LCA: + * Let T be a rooted tree. The lowest + * common ancestor between two nodes n1 and + * n2 is defined as the lowest node in T that has + * both n1 and n2 as descendants (where we allow + * a node to be a descendant of itself). + */ + public void leastCommonAncestor() { + /*int value1, value2; + Scanner in = new Scanner(System.in); + out.println("Enter value 1: "); + value1 = (E) Integer.valueOf(in.nextLine()); + out.println("Enter value 1: "); + value2 = (E) in.nextLine(); + out.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ + } + + public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { + if (node == null || value1.compareTo(value2) > 0) throw new NoSuchElementException(); + + if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) { + return node; + } else if (value1.compareTo(node.value) > 0 && value2.compareTo(node.value) > 0) { + return leastCommonAncestor(node.right, value1, value2); + } else { + return leastCommonAncestor(node.left, value1, value2); + } + } + + + /** + * A recursive function that takes an ordered binary tree + * and rearranges the internal pointers to make a circular + * doubly linked list out of the tree nodes. The list should + * be arranged so that the nodes are in increasing order. + */ + public void treeToList() { + // print the list + printList(treeToList(root)); + } + + public BinaryNode treeToList(BinaryNode node) { + if (node == null) return null; + + BinaryNode aList = treeToList(node.left); + BinaryNode bList = treeToList(node.right); + + node.left = node; + node.right = node; + + // attach left child then root followed by right child (so that final list is in ascending order) + aList = addToList(aList, node); + aList = addToList(aList, bList); + + return aList; + } + + private BinaryNode addToList(BinaryNode aList, BinaryNode bList) { + + if (aList == null) return bList; + if (bList == null) return aList; + + // find the last node in each list + BinaryNode aListLast = aList.left; + BinaryNode bListLast = bList.left; + + // join end of one list to beginning of another + aListLast.right = bList; + bList.left = aListLast; + + // make circular + aListLast.left = bListLast; + bListLast.right = aList; + + return aList; + } + + + /** + * Utility methods. + */ + private void printList(BinaryNode node) { + BinaryNode current = node; + out.print("["); + if (current == null) { + out.println("]"); + return; + } + while (current.right != node) { + out.print(current.value + ","); + current = current.right; + } + out.println(current.value + "]"); + } } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 89c9d552..b577bf36 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -542,6 +542,21 @@ public boolean isBST(BinaryNode node, BinaryNode prev) { return left && right; } + + /** + * The diameter of a tree (sometimes called the width) is the number + * of nodes on the longest path between two leaves in the tree. + * + * @return the diameter of the tree. + */ + public int diameter() { + return diameter(root); + } + + public int diameter(BinaryNode node) { + return 1; + } + /** * Children Sum Invariant: For every node, the value must be equal to * sum of values in the left and right child. diff --git a/src/me/ramswaroop/trees/NonRecursiveBST.java b/src/me/ramswaroop/trees/NonRecursiveBST.java deleted file mode 100644 index cd9ceefe..00000000 --- a/src/me/ramswaroop/trees/NonRecursiveBST.java +++ /dev/null @@ -1,12 +0,0 @@ -package me.ramswaroop.trees; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 4/19/15 - * Time: 11:41 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class NonRecursiveBST> extends BinarySearchTree { - -} diff --git a/src/me/ramswaroop/trees/RecursiveBST.java b/src/me/ramswaroop/trees/RecursiveBST.java deleted file mode 100644 index b2813676..00000000 --- a/src/me/ramswaroop/trees/RecursiveBST.java +++ /dev/null @@ -1,208 +0,0 @@ -package me.ramswaroop.trees; - -import me.ramswaroop.common.BinaryNode; - -import java.util.NoSuchElementException; - -import static java.lang.System.out; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 3/24/15 - * Time: 3:02 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class RecursiveBST> extends BinarySearchTree { - - public static void main(String[] a) { - RecursiveBST bst = new RecursiveBST<>(); - bst.put(6); - bst.put(3); - bst.put(5); - bst.put(7); - bst.put(8); - bst.put(9); - bst.preOrder(); - out.println(""); - bst.inOrder(); - out.println(""); - bst.postOrder(); - out.println("\n" + bst.size()); - out.println(BinaryTree.isIdentical(bst.root.right, bst.root.right)); - out.println(bst.isIdentical(bst.root)); - out.println(bst.height()); - /*obj.delete(); - out.println("After deletion: "); - obj.postOrder();*/ - out.println("In Order: "); - bst.inOrder(); - /*out.println("\nAfter mirroring: "); - obj.mirror(); - obj.inOrder();*/ - out.println("\nRoot to leafs: "); - bst.rootToLeafPaths(); - out.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); - out.println("Min: " + bst.min().value); - out.println("BFS: "); - bst.breadthFirstTraversal(); - out.println("\nBFS using queue: "); - bst.breadthFirstTraversalUsingQueue(); - out.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); - out.println("Is BST: " + bst.isBST()); - out.print("Tree to list: "); - bst.treeToList(); - } - - - /** - * Inserts a node into the BST. - * - * @param value - */ - public void put(E value) { - put(root, value); - } - - public BinaryNode put(BinaryNode node, E value) { - BinaryNode newNode = new BinaryNode<>(value, null, null); - - if (node == null) { - return root = new BinaryNode<>(value, null, null); - } else { - if (value.compareTo(node.value) < 0) { - if (node.left == null) { - return node.left = newNode; - } else { - return put(node.left, value); - } - } else { - if (node.right == null) { - return node.right = newNode; - } else { - return put(node.right, value); - } - } - } - } - - - /** - * Returns the node with minimum value. - * - * @return - */ - public BinaryNode min() { - return min(root); - } - - public BinaryNode min(BinaryNode node) { - if (node == null) throw new NoSuchElementException(); - - if (node.left == null) { - return node; - } else { - return min(node.left); - } - } - - - /** - * Determines the LCA for a BST - *

- * DEFINITION OF LCA: - * Let T be a rooted tree. The lowest - * common ancestor between two nodes n1 and - * n2 is defined as the lowest node in T that has - * both n1 and n2 as descendants (where we allow - * a node to be a descendant of itself). - */ - public void leastCommonAncestor() { - /*int value1, value2; - Scanner in = new Scanner(System.in); - out.println("Enter value 1: "); - value1 = (E) Integer.valueOf(in.nextLine()); - out.println("Enter value 1: "); - value2 = (E) in.nextLine(); - out.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ - } - - public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { - if (node == null || value1.compareTo(value2) > 0) throw new NoSuchElementException(); - - if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) { - return node; - } else if (value1.compareTo(node.value) > 0 && value2.compareTo(node.value) > 0) { - return leastCommonAncestor(node.right, value1, value2); - } else { - return leastCommonAncestor(node.left, value1, value2); - } - } - - - /** - * A recursive function that takes an ordered binary tree - * and rearranges the internal pointers to make a circular - * doubly linked list out of the tree nodes. The list should - * be arranged so that the nodes are in increasing order. - */ - public void treeToList() { - // print the list - printList(treeToList(root)); - } - - public BinaryNode treeToList(BinaryNode node) { - if (node == null) return null; - - BinaryNode aList = treeToList(node.left); - BinaryNode bList = treeToList(node.right); - - node.left = node; - node.right = node; - - // attach left child then root followed by right child (so that final list is in ascending order) - aList = addToList(aList, node); - aList = addToList(aList, bList); - - return aList; - } - - private BinaryNode addToList(BinaryNode aList, BinaryNode bList) { - - if (aList == null) return bList; - if (bList == null) return aList; - - // find the last node in each list - BinaryNode aListLast = aList.left; - BinaryNode bListLast = bList.left; - - // join end of one list to beginning of another - aListLast.right = bList; - bList.left = aListLast; - - // make circular - aListLast.left = bListLast; - bListLast.right = aList; - - return aList; - } - - - /** - * Utility methods. - */ - - private void printList(BinaryNode node) { - BinaryNode current = node; - out.print("["); - if (current == null) { - out.println("]"); - return; - } - while (current.right != node) { - out.print(current.value + ","); - current = current.right; - } - out.println(current.value + "]"); - } -} From 3530f41333e986183947743dc1ac98e276338eb8 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 13 May 2015 17:37:15 +0530 Subject: [PATCH 037/417] height balancing done --- src/me/ramswaroop/trees/BinarySearchTree.java | 5 ++-- src/me/ramswaroop/trees/BinaryTree.java | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/trees/BinarySearchTree.java index 63527b72..89a6a1b2 100644 --- a/src/me/ramswaroop/trees/BinarySearchTree.java +++ b/src/me/ramswaroop/trees/BinarySearchTree.java @@ -49,8 +49,9 @@ public static void main(String[] a) { bst.breadthFirstTraversalUsingQueue(); out.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); out.println("Is BST: " + bst.isBST()); - out.print("Tree to list: "); - bst.treeToList(); + /*out.print("Tree to list: "); + bst.treeToList();*/ + out.print("\nIs height balanced: " + bst.isHeightBalanced()); } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index b577bf36..6d4b981a 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -47,6 +47,7 @@ public static void main(String[] a) { binaryTree.toChildrenSum(); out.print("\nBreadth-first Traversal after to children sum: "); binaryTree.breadthFirstTraversal(); + out.print("\nIs height balanced: " + binaryTree.isHeightBalanced()); } /** @@ -557,6 +558,28 @@ public int diameter(BinaryNode node) { return 1; } + /** + * An empty tree is height-balanced. A non-empty binary tree T is balanced if: + * 1) Left subtree of T is balanced + * 2) Right subtree of T is balanced + * 3) The difference between heights of left subtree and right subtree is not more than 1. + * + * @return True if tree is height balanced otherwise false. + */ + public boolean isHeightBalanced() { + return isHeightBalanced(root); + } + + public boolean isHeightBalanced(BinaryNode node) { + if (node == null) return true; + + if (Math.abs(height(node.left) - height(node.right)) > 1) { + return false; + } + + return isHeightBalanced(node.left) && isHeightBalanced(node.right); + } + /** * Children Sum Invariant: For every node, the value must be equal to * sum of values in the left and right child. From e4558fe56bec6a7038f0034723e44b976b5d5395 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 13 May 2015 22:43:47 +0530 Subject: [PATCH 038/417] tree diameter done --- src/me/ramswaroop/trees/BinarySearchTree.java | 18 +++++++++++++ src/me/ramswaroop/trees/BinaryTree.java | 25 ++++++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/trees/BinarySearchTree.java index 89a6a1b2..3c2d5eb8 100644 --- a/src/me/ramswaroop/trees/BinarySearchTree.java +++ b/src/me/ramswaroop/trees/BinarySearchTree.java @@ -22,6 +22,23 @@ public static void main(String[] a) { bst.put(7); bst.put(8); bst.put(9); + /*bst.put(12); + bst.put(10); + bst.put(16); + bst.put(14); + bst.put(25); + bst.put(15); + bst.put(20); + bst.put(35); + bst.put(23); + bst.put(22); + bst.put(21); + bst.put(45); + bst.put(40); + bst.put(56); + bst.put(65); + bst.put(75); + bst.put(85);*/ bst.preOrder(); out.println(""); bst.inOrder(); @@ -52,6 +69,7 @@ public static void main(String[] a) { /*out.print("Tree to list: "); bst.treeToList();*/ out.print("\nIs height balanced: " + bst.isHeightBalanced()); + out.print("\nDiameter: " + bst.diameter()); } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 6d4b981a..bbf66067 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -44,10 +44,11 @@ public static void main(String[] a) { binaryTree.inOrder(); out.print("\nIs BST: " + binaryTree.isBST()); out.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); - binaryTree.toChildrenSum(); + /*binaryTree.toChildrenSum(); out.print("\nBreadth-first Traversal after to children sum: "); - binaryTree.breadthFirstTraversal(); + binaryTree.breadthFirstTraversal();*/ out.print("\nIs height balanced: " + binaryTree.isHeightBalanced()); + out.print("\nDiameter: " + binaryTree.diameter()); } /** @@ -79,6 +80,10 @@ public BinaryNode put(BinaryNode node, E value) { return node; } + /** + * Traversals using recursions. + */ + /** * Prints the pre-order traversal of the tree. @@ -130,6 +135,13 @@ public void postOrder(BinaryNode node) { out.print(node.value); } + /** + * Traversals without recursions. + */ + + public void inOrder(BinaryNode node, Stack> stack) { + + } /** * Prints the node of the tree breadth-wise. @@ -555,9 +567,16 @@ public int diameter() { } public int diameter(BinaryNode node) { - return 1; + if (node == null) return 0; + + // diameter of current node + int diameter = height(node.left) + height(node.right) + 1; + + // return max diameters of current node, left sub-tree and right sub-tree + return Math.max(diameter, Math.max(diameter(node.left), diameter(node.right))); } + /** * An empty tree is height-balanced. A non-empty binary tree T is balanced if: * 1) Left subtree of T is balanced From 31f688e2ab4de7d16a85a560d00901f9a7447717 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 14 May 2015 14:12:00 +0530 Subject: [PATCH 039/417] inorder traversal using explicit stack --- src/me/ramswaroop/trees/BinarySearchTree.java | 6 +-- src/me/ramswaroop/trees/BinaryTree.java | 42 ++++++++++++++----- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/trees/BinarySearchTree.java index 3c2d5eb8..33210f64 100644 --- a/src/me/ramswaroop/trees/BinarySearchTree.java +++ b/src/me/ramswaroop/trees/BinarySearchTree.java @@ -51,7 +51,7 @@ public static void main(String[] a) { /*obj.delete(); out.println("After deletion: "); obj.postOrder();*/ - out.println("In Order: "); + out.print("\nIn Order: "); bst.inOrder(); /*out.println("\nAfter mirroring: "); obj.mirror(); @@ -60,9 +60,9 @@ public static void main(String[] a) { bst.rootToLeafPaths(); out.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); out.println("Min: " + bst.min().value); - out.println("BFS: "); + out.println("BFT: "); bst.breadthFirstTraversal(); - out.println("\nBFS using queue: "); + out.println("\nBFT using queue: "); bst.breadthFirstTraversalUsingQueue(); out.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); out.println("Is BST: " + bst.isBST()); diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index bbf66067..27ee3a28 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -23,19 +23,12 @@ public class BinaryTree> extends Tree { public static void main(String[] a) { BinaryTree binaryTree = new BinaryTree<>(); - /*binaryTree.put(6); + binaryTree.put(6); binaryTree.put(3); binaryTree.put(9); binaryTree.put(2); binaryTree.put(4); - binaryTree.put(5);*/ - binaryTree.put(10); - binaryTree.put(8); - binaryTree.put(1); - binaryTree.put(3); binaryTree.put(5); - binaryTree.put(1); - binaryTree.put(1); out.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); out.print("\nSpiral Traversal: "); @@ -106,7 +99,9 @@ public void preOrder(BinaryNode node) { * Prints the in-order traversal of the tree. */ public void inOrder() { - inOrder(root); + //inOrder(root); + //inOrderUsingStack(root); + inOrderWithoutStackAndRecursion(root); } public void inOrder(BinaryNode node) { @@ -139,7 +134,34 @@ public void postOrder(BinaryNode node) { * Traversals without recursions. */ - public void inOrder(BinaryNode node, Stack> stack) { + /** + * In-order traversal of tree using one stack and without recursion. + * + * @param node + */ + public void inOrderUsingStack(BinaryNode node) { + if (node == null) return; + + Stack> stack = new LinkedStack<>(); + + BinaryNode curr = node; + stack.push(curr); + + while (!stack.isEmpty()) { + + while (curr != null) { + curr = curr.left; + if (curr != null) stack.push(curr); + } + + BinaryNode top = stack.pop(); + out.print(top.value); + curr = top.right; + if (curr != null) stack.push(curr); + } + } + + public void inOrderWithoutStackAndRecursion(BinaryNode node) { } From 7147d61c392d92e023fdedd8314f4004ff274fd5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 17 May 2015 00:46:16 +0530 Subject: [PATCH 040/417] inorder traversal using threaded binary tree (moris traversal) --- src/me/ramswaroop/trees/BinaryTree.java | 65 ++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 27ee3a28..a453cdf0 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -35,6 +35,8 @@ public static void main(String[] a) { binaryTree.spiralTraversal(); out.print("\nIn order traversal: "); binaryTree.inOrder(); + out.print("\nIn order traversal without stack: "); + binaryTree.inOrderWithoutStackAndRecursion(binaryTree.root); out.print("\nIs BST: " + binaryTree.isBST()); out.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); /*binaryTree.toChildrenSum(); @@ -99,9 +101,7 @@ public void preOrder(BinaryNode node) { * Prints the in-order traversal of the tree. */ public void inOrder() { - //inOrder(root); - //inOrderUsingStack(root); - inOrderWithoutStackAndRecursion(root); + inOrder(root); } public void inOrder(BinaryNode node) { @@ -130,6 +130,7 @@ public void postOrder(BinaryNode node) { out.print(node.value); } + /** * Traversals without recursions. */ @@ -144,27 +145,75 @@ public void inOrderUsingStack(BinaryNode node) { Stack> stack = new LinkedStack<>(); - BinaryNode curr = node; - stack.push(curr); + BinaryNode curr = node; // set root node as current node + stack.push(curr); // push current node while (!stack.isEmpty()) { while (curr != null) { curr = curr.left; - if (curr != null) stack.push(curr); + if (curr != null) stack.push(curr); // push all left nodes of the current node } BinaryNode top = stack.pop(); - out.print(top.value); + out.print(top.value); // print top of stack curr = top.right; - if (curr != null) stack.push(curr); + if (curr != null) stack.push(curr); // push right child of top node } } + /** + * Using Morris Traversal, we can traverse the tree without using stack and + * recursion. The idea of Morris Traversal is based on Threaded Binary Tree. + * In this traversal, we first create links to Inorder successor and print the + * data using these links, and finally revert the changes to restore original tree. + *

+ * A binary tree is THREADED by making all right child pointers that would normally + * be null point to the inorder successor of the node (if it exists), and all left + * child pointers that would normally be null point to the inorder predecessor of + * the node. + *

+ * PSEUDOCODE: + * 1. Initialize current as root + * 2. While current is not NULL + * If current does not have left child + * a) Print current’s data + * b) Go to the right, i.e., current = current->right + * Else + * a) Make current as right child of the rightmost node in current's left subtree + * b) Go to this left child, i.e., current = current->left + * + * @param node + */ public void inOrderWithoutStackAndRecursion(BinaryNode node) { + if (node == null) return; + + BinaryNode curr = node; + while (curr != null) { + // print the leftmost node + if (curr.left == null) { + printValue(curr); + curr = curr.right; + } else { // make current as right child of the rightmost node in current's left subtree + BinaryNode pre = curr.left; + + while (pre.right != curr && pre.right != null) { + pre = pre.right; + } + if (pre.right != curr) { + pre.right = curr; + curr = curr.left; + } else { + printValue(curr); + curr = curr.right; + pre.right = null; // revert to the original tree structure + } + } + } } + /** * Prints the node of the tree breadth-wise. *

From 445c4ea0352a2cb08cf6030d1e8b3f524f68fb4c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 17 May 2015 17:22:32 +0530 Subject: [PATCH 041/417] root to leaf sum done --- src/me/ramswaroop/trees/AVLTree.java | 2 +- src/me/ramswaroop/trees/BinaryTree.java | 43 +++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/trees/AVLTree.java b/src/me/ramswaroop/trees/AVLTree.java index d4c6bf7e..1ac6e505 100644 --- a/src/me/ramswaroop/trees/AVLTree.java +++ b/src/me/ramswaroop/trees/AVLTree.java @@ -7,6 +7,6 @@ * @date: 4/25/15 * @time: 10:25 AM */ -public class AVLTree> { +public class AVLTree> extends Tree { } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index a453cdf0..e382b0be 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -44,6 +44,7 @@ public static void main(String[] a) { binaryTree.breadthFirstTraversal();*/ out.print("\nIs height balanced: " + binaryTree.isHeightBalanced()); out.print("\nDiameter: " + binaryTree.diameter()); + out.print("\nRoot to Leaf Sum: " + binaryTree.rootToLeafPathsSum(binaryTree.root, new ArrayList(), 13)); } /** @@ -272,8 +273,7 @@ public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue node, int level) { @@ -302,7 +302,7 @@ public void spiralTraversal(BinaryNode node, int level) { } } - public void spiralTraversal(BinaryNode node) { + public void spiralTraversalUsingStacks(BinaryNode node) { Stack> stack1 = new LinkedStack<>(); // for nodes to be printed ltr Stack> stack2 = new LinkedStack<>(); // for nodes to be printed rtl @@ -351,6 +351,13 @@ public void spiralTraversal(BinaryNode node) { } + public void constructTreeWithInOrderAndPreOrder(List> inOrder, List> preOrder) { + for (int i = 0; i < preOrder.size(); i++) { + + } + } + + /** * Deletes a particular node from the tree. * @@ -543,6 +550,36 @@ public void rootToLeafPaths(BinaryNode node, List pathList) { } } + + /** + * Given a binary tree and a number, return true if the tree has a root-to-leaf + * path such that adding up all the values along the path equals the given number. + * Return false if no such path can be found. + * + * @param node + * @param pathList + * @param pathSum + * @return + */ + public boolean rootToLeafPathsSum(BinaryNode node, List pathList, int pathSum) { + int sum = 0; + + if (node != null) pathList.add(node.value); + + // if its either a leaf node or null then path is complete, add all in the list + if (node == null || (node.left == null && node.right == null)) { + for (int i = 0; i < pathList.size(); i++) { + sum += Integer.parseInt(pathList.get(i).toString()); + } + return sum == pathSum; + } else { + // do the same for subtrees + return rootToLeafPathsSum(node.left, new ArrayList<>(pathList), pathSum) || + rootToLeafPathsSum(node.right, new ArrayList<>(pathList), pathSum); + } + } + + /** * Returns the number of leaf nodes in a binary tree. * From b7f6f4cfbcbe498df72d27d00853112748afffc1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 17 May 2015 18:23:57 +0530 Subject: [PATCH 042/417] double tree done --- src/me/ramswaroop/trees/BinaryTree.java | 30 +++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index e382b0be..59ebfdca 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -26,9 +26,9 @@ public static void main(String[] a) { binaryTree.put(6); binaryTree.put(3); binaryTree.put(9); - binaryTree.put(2); + /*binaryTree.put(2); binaryTree.put(4); - binaryTree.put(5); + binaryTree.put(5);*/ out.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); out.print("\nSpiral Traversal: "); @@ -45,6 +45,11 @@ public static void main(String[] a) { out.print("\nIs height balanced: " + binaryTree.isHeightBalanced()); out.print("\nDiameter: " + binaryTree.diameter()); out.print("\nRoot to Leaf Sum: " + binaryTree.rootToLeafPathsSum(binaryTree.root, new ArrayList(), 13)); + out.print("\nBFS after Double tree: "); + binaryTree.doubleTree(); + binaryTree.breadthFirstTraversalUsingQueue(); + out.print("\nIn order traversal: "); + binaryTree.inOrder(); } /** @@ -784,6 +789,27 @@ private void increment(BinaryNode node, int diff) { } + /** + * Converts a given tree to its Double tree. To create a Double tree + * of the given tree, create a new duplicate for each node, and insert + * the duplicate as the left child of the original node. + */ + public void doubleTree() { + doubleTree(root); + } + + public void doubleTree(BinaryNode node) { + if (node == null) return; + + BinaryNode newNode = new BinaryNode<>(node.value, node.left, null); + + node.left = newNode; + + doubleTree(newNode.left); + doubleTree(node.right); + } + + /** * Utility methods. */ From c99bee4380f429ab6724b68f1b29e725ad81c379 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 18 May 2015 22:18:56 +0530 Subject: [PATCH 043/417] tree width done --- src/me/ramswaroop/trees/BinaryTree.java | 29 ++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 59ebfdca..127266e4 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -26,9 +26,10 @@ public static void main(String[] a) { binaryTree.put(6); binaryTree.put(3); binaryTree.put(9); - /*binaryTree.put(2); - binaryTree.put(4); - binaryTree.put(5);*/ + binaryTree.put(2); + /*binaryTree.put(4); + binaryTree.put(5); + binaryTree.put(7);*/ out.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); out.print("\nSpiral Traversal: "); @@ -37,6 +38,7 @@ public static void main(String[] a) { binaryTree.inOrder(); out.print("\nIn order traversal without stack: "); binaryTree.inOrderWithoutStackAndRecursion(binaryTree.root); + out.print("\nWidth: " + binaryTree.width()); out.print("\nIs BST: " + binaryTree.isBST()); out.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); /*binaryTree.toChildrenSum(); @@ -690,6 +692,27 @@ public int diameter(BinaryNode node) { } + /** + * Width is the number of nodes in a particular level. + * + * @return maximum width of the tree. + */ + public int width() { + return width(root, 0); + } + + public int width(BinaryNode node, int width) { + if (node == null) return 0; + + if (node.left == null && node.right == null) return 1; // for single/leaf node + + int level_width = width(node.left, width) + width(node.right, width); + + if (level_width > width) width = level_width; + + return width; + } + /** * An empty tree is height-balanced. A non-empty binary tree T is balanced if: * 1) Left subtree of T is balanced From 8a43459460267af0a5e15e29dde2edd48250069c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 18 May 2015 23:04:23 +0530 Subject: [PATCH 044/417] arrays: pair sum --- src/me/ramswaroop/arrays/PairSum.java | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/me/ramswaroop/arrays/PairSum.java diff --git a/src/me/ramswaroop/arrays/PairSum.java b/src/me/ramswaroop/arrays/PairSum.java new file mode 100644 index 00000000..9fd4117c --- /dev/null +++ b/src/me/ramswaroop/arrays/PairSum.java @@ -0,0 +1,41 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/18/15 + * @time: 10:24 PM + */ + +import java.util.Arrays; + +/** + * Given an array ar[] of n numbers and + * another number x, determine whether or not there + * exists two elements in ar[] whose sum is exactly x. + */ +public class PairSum { + + static boolean pairSum(int ar[], int x) { + Arrays.sort(ar); + + int len = ar.length; + + for (int i = 0, j = len - 1; i < j; ) { + if (ar[i] + ar[j] == x) { + return true; + } else if (ar[i] + ar[j] < x) { // approach towards larger elements + i++; + } else { // approach towards smaller elements + j--; + } + } + + return false; + } + + public static void main(String a[]) { + System.out.print(pairSum(new int[]{3, 4, 6, 1, 1}, 9)); + } +} From f6463fd3a8fb4bc5a6128ca9fd31ab87f9c47876 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 20 May 2015 18:23:14 +0530 Subject: [PATCH 045/417] arrays: pair sum done using hashmap --- src/me/ramswaroop/arrays/MajorityElement.java | 19 ++++++++++++++ src/me/ramswaroop/arrays/PairSum.java | 25 ++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/arrays/MajorityElement.java diff --git a/src/me/ramswaroop/arrays/MajorityElement.java b/src/me/ramswaroop/arrays/MajorityElement.java new file mode 100644 index 00000000..8afe3602 --- /dev/null +++ b/src/me/ramswaroop/arrays/MajorityElement.java @@ -0,0 +1,19 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/20/15 + * @time: 2:36 PM + */ +public class MajorityElement { + + public void majorityElement(int ar[]) { + + } + + public static void main(String a[]) { + + } +} diff --git a/src/me/ramswaroop/arrays/PairSum.java b/src/me/ramswaroop/arrays/PairSum.java index 9fd4117c..31ec268c 100644 --- a/src/me/ramswaroop/arrays/PairSum.java +++ b/src/me/ramswaroop/arrays/PairSum.java @@ -9,6 +9,8 @@ */ import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; /** * Given an array ar[] of n numbers and @@ -17,6 +19,11 @@ */ public class PairSum { + /** + * @param ar + * @param x + * @return + */ static boolean pairSum(int ar[], int x) { Arrays.sort(ar); @@ -31,11 +38,27 @@ static boolean pairSum(int ar[], int x) { j--; } } + return false; + } + /** + * @param ar + * @param x + * @param map + * @return + */ + static boolean pairSum(int ar[], int x, Map map) { + for (int i = 0; i < ar.length; i++) { + if (map.containsKey(x - ar[i])) { + return true; + } + map.put(ar[i], 1); + } return false; } public static void main(String a[]) { - System.out.print(pairSum(new int[]{3, 4, 6, 1, 1}, 9)); + System.out.println(pairSum(new int[]{-3, 4, -6, 1, 1}, -2)); + System.out.println(pairSum(new int[]{-3, 4, -6, 1, 1}, -2, new HashMap())); } } From 4923d6aacfff1116dd9c61ffd524d996b5b77aa3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 20 May 2015 23:05:45 +0530 Subject: [PATCH 046/417] arrays: majority element using moore's algorithm --- src/me/ramswaroop/arrays/MajorityElement.java | 53 ++++++++++++++++++- src/me/ramswaroop/arrays/PairSum.java | 6 +++ src/me/ramswaroop/trees/BinaryTree.java | 1 + 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/MajorityElement.java b/src/me/ramswaroop/arrays/MajorityElement.java index 8afe3602..6bdc7840 100644 --- a/src/me/ramswaroop/arrays/MajorityElement.java +++ b/src/me/ramswaroop/arrays/MajorityElement.java @@ -7,13 +7,62 @@ * @date: 5/20/15 * @time: 2:36 PM */ + + +/** + * The algorithm for finding a possible candidate + * works in O(n) which is known as Moore’s Voting Algorithm. + * Basic idea of the algorithm is if we cancel out each + * occurrence of an element e with all the other elements + * that are different from e then e will exist till end + * if it is a majority element. + *

+ * Time Complexity: O(n) + * Auxiliary Space : O(1) + */ public class MajorityElement { - public void majorityElement(int ar[]) { + /** + * Uses Moore’s Voting Algorithm to + * get a candidate for majority element. + * + * @param a + * @return + */ + public static int findCandidate(int a[]) { + int candidate = a[0], count = 1; + for (int i = 1; i < a.length - 1; i++) { + if (candidate == a[i]) { + count++; + } else { + count--; + } + if (count == 0) { + candidate = a[i]; + count = 1; + } + } + return candidate; + } + + public static void majorityElement(int a[]) { + int candidate = findCandidate(a), + count = 0; + // check if the candidate is really a majority element + for (int i = 0; i < a.length; i++) { + if (candidate == a[i]) { + count++; + } + } + if (count > a.length / 2) { + System.out.print(candidate); + } else { + System.out.print("NONE"); + } } public static void main(String a[]) { - + majorityElement(new int[]{1, 6, 2, 2, 2, 1, 2, 2, 7, 2}); } } diff --git a/src/me/ramswaroop/arrays/PairSum.java b/src/me/ramswaroop/arrays/PairSum.java index 31ec268c..380aaad8 100644 --- a/src/me/ramswaroop/arrays/PairSum.java +++ b/src/me/ramswaroop/arrays/PairSum.java @@ -20,6 +20,10 @@ public class PairSum { /** + * Using sorting. If we use Merge Sort or Heap Sort + * then (-)(nlogn) in worst case. If we use Quick Sort + * then O(n^2) in worst case. + * * @param ar * @param x * @return @@ -42,6 +46,8 @@ static boolean pairSum(int ar[], int x) { } /** + * Using hashmap in O(n) time + * * @param ar * @param x * @param map diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 127266e4..483c8245 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -235,6 +235,7 @@ public void breadthFirstTraversal() { breadthFirstTraversal(root, 0); } + // todo need to correct, failing in some cases public void breadthFirstTraversal(BinaryNode node, int level) { if (node == null) return; From 00823975030cad7eb118bd285d619d739eed0d3b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 20 May 2015 23:24:33 +0530 Subject: [PATCH 047/417] arrays: minor fix in majority element using moore's algorithm --- src/me/ramswaroop/arrays/MajorityElement.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/MajorityElement.java b/src/me/ramswaroop/arrays/MajorityElement.java index 6bdc7840..1e1dc32a 100644 --- a/src/me/ramswaroop/arrays/MajorityElement.java +++ b/src/me/ramswaroop/arrays/MajorityElement.java @@ -31,7 +31,7 @@ public class MajorityElement { */ public static int findCandidate(int a[]) { int candidate = a[0], count = 1; - for (int i = 1; i < a.length - 1; i++) { + for (int i = 1; i < a.length; i++) { if (candidate == a[i]) { count++; } else { From 123f50c58e278fe1ea2944bf127ff01c15aa60d1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 20 May 2015 23:37:43 +0530 Subject: [PATCH 048/417] arrays: number occurring odd no of times --- .../arrays/NumberOccurringOddTimes.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/me/ramswaroop/arrays/NumberOccurringOddTimes.java diff --git a/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java b/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java new file mode 100644 index 00000000..c8e3fc85 --- /dev/null +++ b/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java @@ -0,0 +1,29 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/20/15 + * @time: 11:09 PM + */ + +/** + * Given an array of positive integers. All numbers occur + * even number of times except one number which occurs odd + * number of times. Find the number in O(n) time & constant space. + */ +public class NumberOccurringOddTimes { + + public static int numberOccurringOddTimes(int a[]) { + int res = a[0]; + for (int i = 1; i < a.length; i++) { + res ^= a[i]; + } + return res; + } + + public static void main(String a[]) { + System.out.print(numberOccurringOddTimes(new int[]{2, 3, 3, 3, 1, 2, 1})); + } +} From 13955a291dd8310193a056145833917dd754e256 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 28 May 2015 23:23:10 +0530 Subject: [PATCH 049/417] missing no done --- src/me/ramswaroop/arrays/MissingNumber.java | 55 +++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MissingNumber.java diff --git a/src/me/ramswaroop/arrays/MissingNumber.java b/src/me/ramswaroop/arrays/MissingNumber.java new file mode 100644 index 00000000..504263f2 --- /dev/null +++ b/src/me/ramswaroop/arrays/MissingNumber.java @@ -0,0 +1,55 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/28/15 + * @time: 4:34 PM + */ + +/** + * You are given a list of n-1 integers and these integers are in the + * range of 1 to n. There are no duplicates in list. One of the integers + * is missing in the list. Write an efficient code to find the missing integer. + */ +public class MissingNumber { + + public static int missingNumber(int a[], int n) { + int sum = n * (n + 1) / 2; + int arraySum = 0; + + for (int i = 0; i < a.length; i++) { + arraySum += a[i]; + } + return sum - arraySum; + } + + /** + * Using XOR: + * 1) XOR all the array elements, let the result of XOR be X1. + * 2) XOR all numbers from 1 to n, let XOR be X2. + * 3) XOR of X1 and X2 gives the missing number. + * + * @param a + * @param n + * @return + */ + public static int missingNumberUsingXOR(int a[], int n) { + int nXOR = 0, arrayXOR = 0; + + for (int i = 1; i <= n; i++) { + nXOR ^= i; + } + + for (int i = 0; i < a.length; i++) { + arrayXOR ^= a[i]; + } + return nXOR ^ arrayXOR; + } + + public static void main(String a[]) { + System.out.println("Missing No: " + missingNumber(new int[]{2, 3, 1, 4, 6, 7, 8}, 8)); + System.out.println("Missing No using XOR: " + missingNumberUsingXOR(new int[]{2, 3, 1, 4, 6, 7, 8}, 8)); + } +} From e25236dc5177f43f547ef7b7ca5061f9755d5950 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 1 Jun 2015 12:58:15 +0530 Subject: [PATCH 050/417] binary search done --- src/me/ramswaroop/common/Search.java | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/me/ramswaroop/common/Search.java diff --git a/src/me/ramswaroop/common/Search.java b/src/me/ramswaroop/common/Search.java new file mode 100644 index 00000000..25740a27 --- /dev/null +++ b/src/me/ramswaroop/common/Search.java @@ -0,0 +1,45 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/31/15 + * @time: 10:45 PM + */ +public class Search { + + /** + * Searches an item in a sorted array in O(log n) time. + * + * @param a + * @param n + * @return + */ + public static int binarySearch(int a[], int n) { + return binarySearch(a, n, 0, a.length - 1); + } + + public static int binarySearch(int a[], int n, int low, int high) { + int mid = (low + high) / 2; + + if (high < low) { + return -1; + } else if (n == a[mid]) { + return mid; + } else if (n < a[mid]) { + return binarySearch(a, n, 0, mid - 1); + } else { + return binarySearch(a, n, mid + 1, high); + } + } + + /** + * Driver for testing. + * + * @param a + */ + public static void main(String a[]) { + System.out.print(binarySearch(new int[]{2, 3, 4, 5, 6}, 10)); + } +} From 4553332ad2b3cec68797153d636a8173c979a29d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 1 Jun 2015 22:03:34 +0530 Subject: [PATCH 051/417] binary search and pivoted binary search done --- .../arrays/PivotedBinarySearch.java | 48 +++++++++++++++++++ src/me/ramswaroop/common/Search.java | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/arrays/PivotedBinarySearch.java diff --git a/src/me/ramswaroop/arrays/PivotedBinarySearch.java b/src/me/ramswaroop/arrays/PivotedBinarySearch.java new file mode 100644 index 00000000..edb79772 --- /dev/null +++ b/src/me/ramswaroop/arrays/PivotedBinarySearch.java @@ -0,0 +1,48 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.common.Search; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/31/15 + * @time: 10:44 PM + */ +public class PivotedBinarySearch { + + public static int pivotedBinarySearch(int a[], int n) { + int pivot = findPivot(a, 0, a.length - 1); + + if (pivot == -1 || a[pivot] == n) { + return pivot; + } else if (n <= a[0]) { + return Search.binarySearch(a, n, pivot + 1, a.length - 1); + } else { + return Search.binarySearch(a, n, 0, pivot - 1); + } + } + + public static int findPivot(int a[], int low, int high) { + if (low > high) return -1; + if (low == high) return low; + + int mid = (low + high) / 2; + + if (a[mid] > a[mid + 1] && a[mid] > a[mid - 1]) { + return mid; + } else if (a[mid] > a[mid - 1] && a[mid] < a[mid + 1]) { + return findPivot(a, mid + 1, a.length - 1); + } else { + return findPivot(a, 0, mid - 1); + } + } + + public static void main(String a[]) { + System.out.println("Pivot: " + findPivot(new int[]{1, 2, 3, 4, 5}, 0, 3)); + System.out.println("Index: " + pivotedBinarySearch(new int[]{1, 2, 3, 4, 5}, 4)); + + System.out.println("Pivot: " + findPivot(new int[]{5}, 0, 0)); + System.out.println("Index: " + pivotedBinarySearch(new int[]{5}, 5)); + } +} diff --git a/src/me/ramswaroop/common/Search.java b/src/me/ramswaroop/common/Search.java index 25740a27..a2e08def 100644 --- a/src/me/ramswaroop/common/Search.java +++ b/src/me/ramswaroop/common/Search.java @@ -40,6 +40,6 @@ public static int binarySearch(int a[], int n, int low, int high) { * @param a */ public static void main(String a[]) { - System.out.print(binarySearch(new int[]{2, 3, 4, 5, 6}, 10)); + System.out.println(binarySearch(new int[]{0, 2}, 2)); } } From 26d3b6d1bb2a3796f2f41f7b91d5e0a10f2f50d3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 2 Jun 2015 17:01:26 +0530 Subject: [PATCH 052/417] is power of 2 done --- src/me/ramswaroop/bits/CountSetBits.java | 4 ++ src/me/ramswaroop/bits/PowerOf2.java | 40 +++++++++++++++ .../practice/RightShiftOperator.java | 50 +++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 src/me/ramswaroop/bits/PowerOf2.java create mode 100644 src/me/ramswaroop/practice/RightShiftOperator.java diff --git a/src/me/ramswaroop/bits/CountSetBits.java b/src/me/ramswaroop/bits/CountSetBits.java index 9502bc4c..162c8bdc 100644 --- a/src/me/ramswaroop/bits/CountSetBits.java +++ b/src/me/ramswaroop/bits/CountSetBits.java @@ -48,6 +48,10 @@ public static void main(String[] a) { long n = Long.parseLong(in.nextLine()); System.out.println(countSetBits(n)); + System.out.println(Integer.toBinaryString((int) -n)); + System.out.println(countSetBits((int) -n)); + + } } diff --git a/src/me/ramswaroop/bits/PowerOf2.java b/src/me/ramswaroop/bits/PowerOf2.java new file mode 100644 index 00000000..94b3c7dc --- /dev/null +++ b/src/me/ramswaroop/bits/PowerOf2.java @@ -0,0 +1,40 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/2/15 + * @time: 12:18 PM + */ +public class PowerOf2 { + + /** + * Power of 2 no. always has only one set bit. + * + * @param n + * @return + */ + public static boolean isPowerOf2ByCountingSetBits(long n) { + return CountSetBits.countSetBits(n) == 1; + } + + /** + * AND operation of power of 2 no.s and the no. minus 1 is always 0. + * ex: 100 & 011 is 000 + * + * @param n + * @return + */ + public static boolean isPowerOf2(long n) { + return (n & (n - 1)) == 0; + } + + public static void main(String a[]) { + System.out.println(isPowerOf2ByCountingSetBits(18)); + System.out.println(isPowerOf2(18)); + + System.out.println(isPowerOf2ByCountingSetBits(16)); + System.out.println(isPowerOf2(16)); + } +} diff --git a/src/me/ramswaroop/practice/RightShiftOperator.java b/src/me/ramswaroop/practice/RightShiftOperator.java new file mode 100644 index 00000000..08d72ab3 --- /dev/null +++ b/src/me/ramswaroop/practice/RightShiftOperator.java @@ -0,0 +1,50 @@ +package me.ramswaroop.practice; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/2/15 + * @time: 3:26 PM + */ + +/** + * {@code >>} shifts bits to right filling left bits with the left most bit (most significant bit) + * {@code >>>} shifts bits to the right filling left bits with 0 + */ +public class RightShiftOperator { + + public static void main(String a[]) { + int n = -4; + System.out.printf("n: %32d\n", n); + System.out.printf("n: %32s\n", Integer.toBinaryString(n)); + System.out.printf("n>>1: %32s\n", Integer.toBinaryString(n >> 1)); + System.out.printf("n>>1: %32d\n", n >> 1); + System.out.printf("n>>>1: %32s\n", Integer.toBinaryString(n >>> 1)); + System.out.printf("n>>>1: %32d\n", n >>> 1); + + System.out.println("======================================="); + + n = -235034334; + System.out.printf("n: %32d\n", n); + System.out.printf("n: %32s\n", Integer.toBinaryString(n)); + System.out.printf("n>>1: %32s\n", Integer.toBinaryString(n >> 1)); + System.out.printf("n>>1: %32d\n", n >> 1); + System.out.printf("n>>>1: %32s\n", Integer.toBinaryString(n >>> 1)); + System.out.printf("n>>>1: %32d\n", n >>> 1); + System.out.printf("n>>2: %32s\n", Integer.toBinaryString(n >> 2)); + System.out.printf("n>>>2: %32s\n", Integer.toBinaryString(n >>> 2)); + + System.out.println("======================================="); + + n = 235034334; + System.out.printf("n: %32d\n", n); + System.out.printf("n: %32s\n", Integer.toBinaryString(n)); + System.out.printf("n>>1: %32s\n", Integer.toBinaryString(n >> 1)); + System.out.printf("n>>1: %32d\n", n >> 1); + System.out.printf("n>>>1: %32s\n", Integer.toBinaryString(n >>> 1)); + System.out.printf("n>>>1: %32d\n", n >>> 1); + System.out.printf("n>>2: %32s\n", Integer.toBinaryString(n >> 2)); + System.out.printf("n>>>2: %32s\n", Integer.toBinaryString(n >>> 2)); + } +} From b59c9c4c203f157b3b31613dd860cff43a3f235b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 3 Jun 2015 15:25:52 +0530 Subject: [PATCH 053/417] power of 2 and multiple of 3 done --- src/me/ramswaroop/bits/MultipleOf3.java | 51 ++++++++++++++++++++++++ src/me/ramswaroop/bits/NextPowerOf2.java | 44 ++++++++++++++++++++ src/me/ramswaroop/bits/PowerOf2.java | 14 +++++-- 3 files changed, 105 insertions(+), 4 deletions(-) create mode 100644 src/me/ramswaroop/bits/MultipleOf3.java create mode 100644 src/me/ramswaroop/bits/NextPowerOf2.java diff --git a/src/me/ramswaroop/bits/MultipleOf3.java b/src/me/ramswaroop/bits/MultipleOf3.java new file mode 100644 index 00000000..87fa1849 --- /dev/null +++ b/src/me/ramswaroop/bits/MultipleOf3.java @@ -0,0 +1,51 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/3/15 + * @time: 1:18 PM + */ +public class MultipleOf3 { + + /** + * 1) Get count of all set bits at odd positions (For 23 it’s 3). + * 2) Get count of all set bits at even positions (For 23 it’s 1). + * 3) If difference of above two counts is a multiple of 3 then number is also a multiple of 3. + *

+ * NOTE: Binary representation of 23 is 00..10111 + * + * @param n + * @return + */ + public static boolean isMultipleOf3(long n) { + int oddCount = 0, evenCount = 0; + + n = Math.abs(n); + + if (n == 0) return true; + if (n == 1) return false; + + while (n > 0) { + if ((n & 1) == 1) oddCount++; + n >>= 1; + + if ((n & 1) == 1) evenCount++; + n >>= 1; + } + + return isMultipleOf3(oddCount - evenCount); + + } + + public static void main(String a[]) { + System.out.println(isMultipleOf3(0)); + System.out.println(isMultipleOf3(1)); + System.out.println(isMultipleOf3(2)); + System.out.println(isMultipleOf3(3)); + System.out.println(isMultipleOf3(18)); + System.out.println(isMultipleOf3(-18)); // works for -ve numbers as well + System.out.println(isMultipleOf3(-17)); + } +} diff --git a/src/me/ramswaroop/bits/NextPowerOf2.java b/src/me/ramswaroop/bits/NextPowerOf2.java new file mode 100644 index 00000000..d8209009 --- /dev/null +++ b/src/me/ramswaroop/bits/NextPowerOf2.java @@ -0,0 +1,44 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/2/15 + * @time: 5:08 PM + */ +public class NextPowerOf2 { + + /** + * Finds the left most set bit position and returns + * 2 to the power of that position plus 1 + * + * @param n + * @return + */ + public static long nextPowerOf2(long n) { + if (PowerOf2.isPowerOf2(n)) { + return n; + } + + int c = 0; + for (int i = 0; i < 64; i++) { + if ((n & 1) == 1) { + c = i; + } + n >>= 1; + } + + return (c == 0) ? 1 : (long) Math.pow(2, (c + 1)); // check added for input 0 + } + + public static void main(String a[]) { + System.out.println(nextPowerOf2(2)); + System.out.println(nextPowerOf2(3)); + System.out.println(nextPowerOf2(18)); + System.out.println(nextPowerOf2(6)); + System.out.println(nextPowerOf2(7)); + System.out.println(nextPowerOf2(1)); + System.out.println(nextPowerOf2(0)); + } +} diff --git a/src/me/ramswaroop/bits/PowerOf2.java b/src/me/ramswaroop/bits/PowerOf2.java index 94b3c7dc..2efdf3ce 100644 --- a/src/me/ramswaroop/bits/PowerOf2.java +++ b/src/me/ramswaroop/bits/PowerOf2.java @@ -15,7 +15,7 @@ public class PowerOf2 { * @param n * @return */ - public static boolean isPowerOf2ByCountingSetBits(long n) { + public static boolean isPowerOf2(long n) { return CountSetBits.countSetBits(n) == 1; } @@ -26,15 +26,21 @@ public static boolean isPowerOf2ByCountingSetBits(long n) { * @param n * @return */ - public static boolean isPowerOf2(long n) { + public static boolean isPowerOf2UsingANDoperator(long n) { return (n & (n - 1)) == 0; } public static void main(String a[]) { - System.out.println(isPowerOf2ByCountingSetBits(18)); System.out.println(isPowerOf2(18)); + System.out.println(isPowerOf2UsingANDoperator(18)); - System.out.println(isPowerOf2ByCountingSetBits(16)); System.out.println(isPowerOf2(16)); + System.out.println(isPowerOf2UsingANDoperator(16)); + + System.out.println(isPowerOf2(0)); // works for 0 + System.out.println(isPowerOf2UsingANDoperator(0)); // doesn't work for 0 + + System.out.println(isPowerOf2(-2)); // doesn't work for -ve no.s + System.out.println(isPowerOf2UsingANDoperator(-2)); // doesn't work for -ve no.s } } From 933d23978c3f94bef8724cfa65425efb41435596 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 3 Jun 2015 15:47:20 +0530 Subject: [PATCH 054/417] old school method added to multiple of 3 --- src/me/ramswaroop/bits/MultipleOf3.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/me/ramswaroop/bits/MultipleOf3.java b/src/me/ramswaroop/bits/MultipleOf3.java index 87fa1849..934212dc 100644 --- a/src/me/ramswaroop/bits/MultipleOf3.java +++ b/src/me/ramswaroop/bits/MultipleOf3.java @@ -49,3 +49,12 @@ public static void main(String a[]) { System.out.println(isMultipleOf3(-17)); } } + +/** + * Old School Method: + * + * If sum of digits in a number is multiple of 3 then number is multiple of + * 3 e.g., for 612 sum of digits is 9 so it’s a multiple of 3. But this solution + * is not efficient. You have to get all decimal digits one by one, add them and then check if sum is multiple of 3. + * + */ \ No newline at end of file From 825af8f0b78276d0f093885c7e74df607be24558 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 3 Jun 2015 18:45:18 +0530 Subject: [PATCH 055/417] parity done --- src/me/ramswaroop/bits/Parity.java | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/me/ramswaroop/bits/Parity.java diff --git a/src/me/ramswaroop/bits/Parity.java b/src/me/ramswaroop/bits/Parity.java new file mode 100644 index 00000000..2c48904f --- /dev/null +++ b/src/me/ramswaroop/bits/Parity.java @@ -0,0 +1,70 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/3/15 + * @time: 3:50 PM + */ + +/** + * PARITY: Parity of a number refers to whether it + * contains an odd or even number of 1-bits. The number + * has “odd parity”, if it contains odd number of 1-bits + * and is “even parity” if it contains even number of 1-bits. + */ +public class Parity { + + /** + * Uses BRIAN KERNIGAN'S bit counting. The time complexity is + * proportional to the number of bits set. + * {@see http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity} + * + * @param n + * @return + */ + public static boolean isEvenParity(long n) { + boolean parity = true; + + while (n > 0) { + parity = !parity; + n = n & (n - 1); + } + return parity; + } + + + /** + * Old school method + * + * @param n + * @return true if {@param n} has even number of 1-bits + */ + public static boolean isEvenParityByCountingSetBits(long n) { + int setBitsCount = 0; + + while (n > 0) { + if ((n & 1) == 1) setBitsCount++; + n >>= 1; + } + + return setBitsCount % 2 == 0; + } + + public static void main(String a[]) { + System.out.println(isEvenParity(0)); + System.out.println(isEvenParity(1)); + System.out.println(isEvenParity(5)); + System.out.println(isEvenParity(6)); + System.out.println(isEvenParity(7)); + System.out.println(isEvenParity(12)); + System.out.println("=========================="); + System.out.println(isEvenParityByCountingSetBits(0)); + System.out.println(isEvenParityByCountingSetBits(1)); + System.out.println(isEvenParityByCountingSetBits(5)); + System.out.println(isEvenParityByCountingSetBits(6)); + System.out.println(isEvenParityByCountingSetBits(7)); + System.out.println(isEvenParityByCountingSetBits(12)); + } +} From bfb8ae9cc36388964e1737d86ae966820a67ac03 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 3 Jun 2015 23:45:23 +0530 Subject: [PATCH 056/417] multiply without using operators done --- src/me/ramswaroop/bits/CountSetBits.java | 4 +-- src/me/ramswaroop/bits/Multiply.java | 42 ++++++++++++++++++++++++ src/me/ramswaroop/bits/NextPowerOf2.java | 2 +- src/me/ramswaroop/bits/Parity.java | 1 + 4 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/bits/Multiply.java diff --git a/src/me/ramswaroop/bits/CountSetBits.java b/src/me/ramswaroop/bits/CountSetBits.java index 162c8bdc..726a96dc 100644 --- a/src/me/ramswaroop/bits/CountSetBits.java +++ b/src/me/ramswaroop/bits/CountSetBits.java @@ -12,7 +12,7 @@ public class CountSetBits { /** - * Unoptimized version + * Unoptimized version. * * @param number * @return @@ -29,7 +29,7 @@ static int countSetBits(int number) { } /** - * Optimized version + * Optimized version. * * @param n * @return diff --git a/src/me/ramswaroop/bits/Multiply.java b/src/me/ramswaroop/bits/Multiply.java new file mode 100644 index 00000000..e91967bf --- /dev/null +++ b/src/me/ramswaroop/bits/Multiply.java @@ -0,0 +1,42 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/3/15 + * @time: 11:35 PM + */ +public class Multiply { + + /** + * Multiplies a number with 8 by performing 3 left shifts. + * + * @param n + * @return + */ + public static long multiplyBy8(long n) { + return (n << 3); + } + + /** + * 3 left shifts gives us 8n but we want 7n, so we subtract + * 1n from it. Similarly we can do any multiplication by shifting + * and then adding/subtracting. + * + * @param n + * @return + */ + public static long multiplyBy7(long n) { + return (n << 3) - n; + } + + public static void main(String a[]) { + System.out.println(multiplyBy7(4)); + System.out.println(multiplyBy7(6)); + System.out.println(multiplyBy7(7)); + System.out.println(multiplyBy8(4)); + System.out.println(multiplyBy8(6)); + System.out.println(multiplyBy8(7)); + } +} diff --git a/src/me/ramswaroop/bits/NextPowerOf2.java b/src/me/ramswaroop/bits/NextPowerOf2.java index d8209009..e689cbe3 100644 --- a/src/me/ramswaroop/bits/NextPowerOf2.java +++ b/src/me/ramswaroop/bits/NextPowerOf2.java @@ -11,7 +11,7 @@ public class NextPowerOf2 { /** * Finds the left most set bit position and returns - * 2 to the power of that position plus 1 + * 2 to the power of that position plus 1. * * @param n * @return diff --git a/src/me/ramswaroop/bits/Parity.java b/src/me/ramswaroop/bits/Parity.java index 2c48904f..4c90643d 100644 --- a/src/me/ramswaroop/bits/Parity.java +++ b/src/me/ramswaroop/bits/Parity.java @@ -20,6 +20,7 @@ public class Parity { * Uses BRIAN KERNIGAN'S bit counting. The time complexity is * proportional to the number of bits set. * {@see http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity} + * {@see http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive} * * @param n * @return From 74a9395b0e0f848d7fd5e8e7e6f6cd1ce56706cb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 12:31:28 +0530 Subject: [PATCH 057/417] added comments --- src/me/ramswaroop/bits/CountSetBits.java | 8 +++++++- src/me/ramswaroop/bits/Multiply.java | 7 +++++++ src/me/ramswaroop/bits/Parity.java | 5 +++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/bits/CountSetBits.java b/src/me/ramswaroop/bits/CountSetBits.java index 726a96dc..70a737ac 100644 --- a/src/me/ramswaroop/bits/CountSetBits.java +++ b/src/me/ramswaroop/bits/CountSetBits.java @@ -31,13 +31,19 @@ static int countSetBits(int number) { /** * Optimized version. * + * Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset + * in each iteration. The time complexity is proportional to the number of bits set. + * + * {@see http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity} + * {@see http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive} + * * @param n * @return */ static int countSetBits(long n) { int count = 0; while (n > 0) { - n &= n - 1; + n &= n - 1; // right most set bit in n is unset count++; } return count; diff --git a/src/me/ramswaroop/bits/Multiply.java b/src/me/ramswaroop/bits/Multiply.java index e91967bf..7422080b 100644 --- a/src/me/ramswaroop/bits/Multiply.java +++ b/src/me/ramswaroop/bits/Multiply.java @@ -7,6 +7,13 @@ * @date: 6/3/15 * @time: 11:35 PM */ + +/** + * Time Complexity: O(1) + * Space Complexity: O(1) + *

+ * Note: Works only for positive integers. + */ public class Multiply { /** diff --git a/src/me/ramswaroop/bits/Parity.java b/src/me/ramswaroop/bits/Parity.java index 4c90643d..7c1e0ace 100644 --- a/src/me/ramswaroop/bits/Parity.java +++ b/src/me/ramswaroop/bits/Parity.java @@ -17,8 +17,9 @@ public class Parity { /** - * Uses BRIAN KERNIGAN'S bit counting. The time complexity is - * proportional to the number of bits set. + * Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset + * in each iteration. The time complexity is proportional to the number of bits set. + * * {@see http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity} * {@see http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive} * From 4f0f7a7404296e6f54c626434e3f2741e09682b4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 13:10:04 +0530 Subject: [PATCH 058/417] handles case when n = 0 --- src/me/ramswaroop/bits/PowerOf2.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/PowerOf2.java b/src/me/ramswaroop/bits/PowerOf2.java index 2efdf3ce..32a2af92 100644 --- a/src/me/ramswaroop/bits/PowerOf2.java +++ b/src/me/ramswaroop/bits/PowerOf2.java @@ -27,7 +27,7 @@ public static boolean isPowerOf2(long n) { * @return */ public static boolean isPowerOf2UsingANDoperator(long n) { - return (n & (n - 1)) == 0; + return n != 0 && (n & (n - 1)) == 0; // n != 0 check added for input 0 } public static void main(String a[]) { @@ -38,7 +38,7 @@ public static void main(String a[]) { System.out.println(isPowerOf2UsingANDoperator(16)); System.out.println(isPowerOf2(0)); // works for 0 - System.out.println(isPowerOf2UsingANDoperator(0)); // doesn't work for 0 + System.out.println(isPowerOf2UsingANDoperator(0)); // works for 0 System.out.println(isPowerOf2(-2)); // doesn't work for -ve no.s System.out.println(isPowerOf2UsingANDoperator(-2)); // doesn't work for -ve no.s From 8f027c4164cffd25e6894e9c58efbb2edf164dfb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 15:14:41 +0530 Subject: [PATCH 059/417] next power of 2 done (in 3 ways) --- src/me/ramswaroop/bits/NextPowerOf2.java | 70 ++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/bits/NextPowerOf2.java b/src/me/ramswaroop/bits/NextPowerOf2.java index e689cbe3..2ed695c5 100644 --- a/src/me/ramswaroop/bits/NextPowerOf2.java +++ b/src/me/ramswaroop/bits/NextPowerOf2.java @@ -9,30 +9,72 @@ */ public class NextPowerOf2 { + /** - * Finds the left most set bit position and returns - * 2 to the power of that position plus 1. + * Left shifts 1 number of times equal to the + * leftmost set bit position in n. * * @param n * @return */ public static long nextPowerOf2(long n) { + // if n is already a power of 2 then return n + if (n != 0 && ((n & (n - 1)) == 0)) return n; + + long p = 1; + while (p < n) { + p <<= 1; + } + return p; + } + + /** + * Finds the leftmost set bit position and + * left shifts 1 that many times. + * + * @param n + * @return + */ + public static long nextPowerOf2_V2(long n) { + // if n is already a power of 2 then return n + if (n != 0 && ((n & (n - 1)) == 0)) return n; + + long c = 0; + // finds the position of the leftmost set bit + while (n > 0) { + n >>= 1; + c++; + } + + return 1 << c; + } + + /** + * Finds the leftmost set bit position and + * left shifts 1 that many times. + * + * @param n + * @return + */ + public static long nextPowerOf2_V1(long n) { if (PowerOf2.isPowerOf2(n)) { return n; } int c = 0; - for (int i = 0; i < 64; i++) { + // finds the position of leftmost set bit + for (int i = 1; i <= 64; i++) { if ((n & 1) == 1) { c = i; } n >>= 1; } - return (c == 0) ? 1 : (long) Math.pow(2, (c + 1)); // check added for input 0 + return 1 << c; } public static void main(String a[]) { + System.out.println(nextPowerOf2(2)); System.out.println(nextPowerOf2(3)); System.out.println(nextPowerOf2(18)); @@ -40,5 +82,25 @@ public static void main(String a[]) { System.out.println(nextPowerOf2(7)); System.out.println(nextPowerOf2(1)); System.out.println(nextPowerOf2(0)); + + System.out.println("================="); + + System.out.println(nextPowerOf2_V2(2)); + System.out.println(nextPowerOf2_V2(3)); + System.out.println(nextPowerOf2_V2(18)); + System.out.println(nextPowerOf2_V2(6)); + System.out.println(nextPowerOf2_V2(7)); + System.out.println(nextPowerOf2_V2(1)); + System.out.println(nextPowerOf2_V2(0)); + + System.out.println("================="); + + System.out.println(nextPowerOf2_V1(2)); + System.out.println(nextPowerOf2_V1(3)); + System.out.println(nextPowerOf2_V1(18)); + System.out.println(nextPowerOf2_V1(6)); + System.out.println(nextPowerOf2_V1(7)); + System.out.println(nextPowerOf2_V1(1)); + System.out.println(nextPowerOf2_V1(0)); } } From 39aa7a3e54b0d51d8e59db2e719d4e6835d8124a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 15:56:16 +0530 Subject: [PATCH 060/417] rightmost set bit done --- src/me/ramswaroop/bits/RightmostSetBit.java | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/me/ramswaroop/bits/RightmostSetBit.java diff --git a/src/me/ramswaroop/bits/RightmostSetBit.java b/src/me/ramswaroop/bits/RightmostSetBit.java new file mode 100644 index 00000000..12b1d6e5 --- /dev/null +++ b/src/me/ramswaroop/bits/RightmostSetBit.java @@ -0,0 +1,32 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/3/15 + * @time: 11:56 PM + */ +public class RightmostSetBit { + + public static int getRightmostSetBitPosition(long n) { + int position = 0; + while (n > 0) { + position++; + if ((n & 1) == 1) { + break; + } + n >>= 1; + } + return position; + } + + public static void main(String a[]) { + System.out.println(getRightmostSetBitPosition(0)); + System.out.println(getRightmostSetBitPosition(1)); + System.out.println(getRightmostSetBitPosition(2)); + System.out.println(getRightmostSetBitPosition(5)); + System.out.println(getRightmostSetBitPosition(18)); + System.out.println(getRightmostSetBitPosition(19)); + } +} From 91e45f32d81f71b5f09c2070c0c7526bda4e12a6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 23:20:19 +0530 Subject: [PATCH 061/417] sub bit number problem done --- src/me/ramswaroop/bits/SubBit.java | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/me/ramswaroop/bits/SubBit.java diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java new file mode 100644 index 00000000..ffe7aaa1 --- /dev/null +++ b/src/me/ramswaroop/bits/SubBit.java @@ -0,0 +1,30 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/4/15 + * @time: 10:54 PM + */ +public class SubBit { + + /** + * Returns the number formed with the bits from {@param start} + * and {@param end} of {@param num} (both inclusive). + * + * @param num + * @param start + * @param end + * @return + */ + public static int getSubBit(int num, int start, int end) { + num <<= (32 - end); + num >>>= (start - end + 31); + return num; + } + + public static void main(String a[]) { + System.out.println(getSubBit(15, 1, 2)); + } +} From 0977f08ae2efa5ed0ffac8d8610c30d00b3863a2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 23:31:37 +0530 Subject: [PATCH 062/417] sub bit - comments added --- src/me/ramswaroop/bits/SubBit.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java index ffe7aaa1..c2d6e111 100644 --- a/src/me/ramswaroop/bits/SubBit.java +++ b/src/me/ramswaroop/bits/SubBit.java @@ -18,13 +18,13 @@ public class SubBit { * @param end * @return */ - public static int getSubBit(int num, int start, int end) { + public static int getSubBits(int num, int start, int end) { num <<= (32 - end); - num >>>= (start - end + 31); + num >>>= (start - end + 31); // more intuitive (start - 1 + 32 - end) return num; } public static void main(String a[]) { - System.out.println(getSubBit(15, 1, 2)); + System.out.println(getSubBits(15, 1, 2)); } } From ecd947532d5c29cbbdcfc607edc40de65536525b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 4 Jun 2015 23:35:25 +0530 Subject: [PATCH 063/417] code shortened/improved --- src/me/ramswaroop/bits/SubBit.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java index c2d6e111..bcd4924f 100644 --- a/src/me/ramswaroop/bits/SubBit.java +++ b/src/me/ramswaroop/bits/SubBit.java @@ -19,12 +19,11 @@ public class SubBit { * @return */ public static int getSubBits(int num, int start, int end) { - num <<= (32 - end); - num >>>= (start - end + 31); // more intuitive (start - 1 + 32 - end) + num = num << (32 - end) >>> (start - end + 31); // more intuitive (start - 1 + 32 - end) return num; } public static void main(String a[]) { - System.out.println(getSubBits(15, 1, 2)); + System.out.println(getSubBits(5, 1, 2)); } } From 47dbe8132b2c04b97027e4d2a50e2e8b5e59942a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 5 Jun 2015 00:37:33 +0530 Subject: [PATCH 064/417] sub bits comments added --- src/me/ramswaroop/bits/SubBit.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java index bcd4924f..188a5bf5 100644 --- a/src/me/ramswaroop/bits/SubBit.java +++ b/src/me/ramswaroop/bits/SubBit.java @@ -14,8 +14,8 @@ public class SubBit { * and {@param end} of {@param num} (both inclusive). * * @param num - * @param start - * @param end + * @param start > 0 + * @param end > 0 * @return */ public static int getSubBits(int num, int start, int end) { From a99231d788a6e2c87796e2f3e3b097a91ec048c5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 5 Jun 2015 10:06:30 +0530 Subject: [PATCH 065/417] code shortened/improved --- src/me/ramswaroop/bits/SubBit.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java index 188a5bf5..39eadd81 100644 --- a/src/me/ramswaroop/bits/SubBit.java +++ b/src/me/ramswaroop/bits/SubBit.java @@ -19,8 +19,7 @@ public class SubBit { * @return */ public static int getSubBits(int num, int start, int end) { - num = num << (32 - end) >>> (start - end + 31); // more intuitive (start - 1 + 32 - end) - return num; + return num << (32 - end) >>> (start - end + 31); // more intuitive (start - 1 + 32 - end) } public static void main(String a[]) { From bec9d2dfe9991456cd1747707c478c4a4750af69 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 5 Jun 2015 11:57:22 +0530 Subject: [PATCH 066/417] integer overflow done --- src/me/ramswaroop/bits/IntegerOverflow.java | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/me/ramswaroop/bits/IntegerOverflow.java diff --git a/src/me/ramswaroop/bits/IntegerOverflow.java b/src/me/ramswaroop/bits/IntegerOverflow.java new file mode 100644 index 00000000..48e71f59 --- /dev/null +++ b/src/me/ramswaroop/bits/IntegerOverflow.java @@ -0,0 +1,58 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/4/15 + * @time: 4:28 PM + */ +public class IntegerOverflow { + + /** + * Adds {@param a} and {@param b} and if the result can't + * be stored as an integer it throws an exception + * + * @param a + * @param b + * @return + */ + public static int add(int a, int b) throws Exception { + + if (a > Integer.MAX_VALUE - b) { + throw new Exception("Integer Overflow"); + } else { + return a + b; + } + } + + /** + * Adds {@param a} and {@param b} and if the result can't + * be stored as an integer it throws an exception + * + * @param a + * @param b + * @return + */ + public static int add_V1(int a, int b) throws Exception { + + if ((a > 0 && b > 0 && a + b < 0) || (a < 0 && b < 0 && a + b > 0)) { + throw new Exception("Integer Overflow"); + } else { + return a + b; + } + } + + public static void main(String a[]) { + try { + System.out.println(add(2, 3)); + System.out.println(add(2147483647, 999999999)); + System.out.println(add(-2147483647, -999999999)); + System.out.println(add_V1(2, 3)); + System.out.println(add_V1(2147483647, 999999999)); + System.out.println(add_V1(-2147483647, -999999999)); + } catch (Exception e) { + e.printStackTrace(); + } + } +} From 2ea91cd58c84019885deda655c44b5b5d759057d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 5 Jun 2015 12:00:30 +0530 Subject: [PATCH 067/417] added comments --- src/me/ramswaroop/bits/SubBit.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java index 39eadd81..0bb1df91 100644 --- a/src/me/ramswaroop/bits/SubBit.java +++ b/src/me/ramswaroop/bits/SubBit.java @@ -14,8 +14,8 @@ public class SubBit { * and {@param end} of {@param num} (both inclusive). * * @param num - * @param start > 0 - * @param end > 0 + * @param start > 0 and <= 32 + * @param end > 0 and <= 32 * @return */ public static int getSubBits(int num, int start, int end) { From 16b06750aa7fcb901dedef0144ed12088d611b68 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 5 Jun 2015 15:25:12 +0530 Subject: [PATCH 068/417] little and big endian done --- .../ramswaroop/bits/LittleAndBigEndian.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/me/ramswaroop/bits/LittleAndBigEndian.java diff --git a/src/me/ramswaroop/bits/LittleAndBigEndian.java b/src/me/ramswaroop/bits/LittleAndBigEndian.java new file mode 100644 index 00000000..35d2452f --- /dev/null +++ b/src/me/ramswaroop/bits/LittleAndBigEndian.java @@ -0,0 +1,22 @@ +package me.ramswaroop.bits; + +import java.nio.ByteOrder; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/5/15 + * @time: 3:10 PM + * @link http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html + */ +public class LittleAndBigEndian { + + public static boolean isLittleEndian() { + return ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); + } + + public static void main(String a[]) { + System.out.println(isLittleEndian()); + } +} From 76b9be1059284343da9173d5f6bb1517d60e13b9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 5 Jun 2015 16:28:29 +0530 Subject: [PATCH 069/417] flipping/inverting bits done --- src/me/ramswaroop/bits/FlippingBits.java | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/me/ramswaroop/bits/FlippingBits.java diff --git a/src/me/ramswaroop/bits/FlippingBits.java b/src/me/ramswaroop/bits/FlippingBits.java new file mode 100644 index 00000000..2b5cf332 --- /dev/null +++ b/src/me/ramswaroop/bits/FlippingBits.java @@ -0,0 +1,49 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/5/15 + * @time: 3:50 PM + */ +public class FlippingBits { + + /** + * Returns the number by flipping/inverting its bits using + * XOR operation with 1......11 (size of int i.e, 32 1's). + * + * @param n + * @return + */ + public static int getNumberByFlippingBits(int n) { + return n ^ 0xffffffff; // equivalent to 11....1 (32 times) in binary + } + + /** + * Returns the number by flipping/inverting its bits using + * the NOT operator. + * + * @param n + * @return + */ + public static int getNumberByFlippingBits_V1(int n) { + return ~n; + } + + public static void main(String a[]) { + System.out.println(getNumberByFlippingBits(5)); + System.out.println(getNumberByFlippingBits_V1(5)); + } +} + +/** + * EXPLANATION: + * + * For input: 5 + * + * Binary: 000.....101 + * Inverted: 111.....010 (which is the 2's compliment of -6) + * + * Therefore, result is -6. + */ From dfe893b5b7b6923fddedc991897b6863009efaad Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 6 Jun 2015 23:25:11 +0530 Subject: [PATCH 070/417] reverse bits done in (1 method) --- src/me/ramswaroop/bits/ReverseBits.java | 40 +++++++++++++++++++++++++ src/me/ramswaroop/bits/SubBit.java | 6 ++-- 2 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/bits/ReverseBits.java diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java new file mode 100644 index 00000000..6cbf44cf --- /dev/null +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -0,0 +1,40 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/5/15 + * @time: 4:26 PM + * @link http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c + * @link http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious + */ +public class ReverseBits { + + public static int getNumberByReversingBits(int n) { + System.out.println(Integer.toBinaryString(n)); + + int m; + // assume 32-bit number + m = 0x55555555; // 1-bit swap + n = ((n & m) << 1) | ((n & ~m) >> 1); + + m = 0x33333333; // 2-bits swap + n = ((n & m) << 2) | ((n & ~m) >> 2); + + m = 0x0f0f0f0f; // 4-bits swap + n = ((n & m) << 4) | ((n & ~m) >> 4); + + m = 0x00ff00ff; // 8-bits swap + n = ((n & m) << 8) | ((n & ~m) >> 8); + + n = (n << 16) | (n >> 16); // 16-bits swap + + System.out.println(Integer.toBinaryString(n)); + return n; + } + + public static void main(String a[]) { + System.out.println(getNumberByReversingBits(7)); + } +} diff --git a/src/me/ramswaroop/bits/SubBit.java b/src/me/ramswaroop/bits/SubBit.java index 0bb1df91..2d954c2d 100644 --- a/src/me/ramswaroop/bits/SubBit.java +++ b/src/me/ramswaroop/bits/SubBit.java @@ -15,14 +15,14 @@ public class SubBit { * * @param num * @param start > 0 and <= 32 - * @param end > 0 and <= 32 + * @param end > 0 and <= 32 * @return */ - public static int getSubBits(int num, int start, int end) { + public static int getNumberFromSubBits(int num, int start, int end) { return num << (32 - end) >>> (start - end + 31); // more intuitive (start - 1 + 32 - end) } public static void main(String a[]) { - System.out.println(getSubBits(5, 1, 2)); + System.out.println(getNumberFromSubBits(5, 1, 2)); } } From ffa2a73d496f1e6cfe687d6d4456011c44ba5271 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 7 Jun 2015 13:43:39 +0530 Subject: [PATCH 071/417] reverse bits done in an obvious way --- src/me/ramswaroop/bits/ReverseBits.java | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index 6cbf44cf..16d8e9cf 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -34,7 +34,34 @@ public static int getNumberByReversingBits(int n) { return n; } + /** + * Checks for set bits in {@param n} and sets them + * from the left end in {@code reverseNum}. + *

+ * Time Complexity: O(log n) + * Space Complexity: O(1) + * + * @param n + * @return + */ + public static int getNumberByReversingBits_V1(int n) { + System.out.println(Integer.toBinaryString(n)); + + int reverseNum = 0, i = 0; + while (n > 0) { + if ((n & 1) == 1) { + reverseNum |= 1 << 31 - i; + } + n >>= 1; + i++; + } + System.out.println(Integer.toBinaryString(reverseNum)); + + return reverseNum; + } + public static void main(String a[]) { System.out.println(getNumberByReversingBits(7)); + System.out.println(getNumberByReversingBits_V1(7)); } } From b77bdd6ac595cc20968bf1899f0493cbdac4191a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 7 Jun 2015 13:49:47 +0530 Subject: [PATCH 072/417] fix in reverse bits --- src/me/ramswaroop/bits/ReverseBits.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index 16d8e9cf..9d4c4d01 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -12,25 +12,23 @@ public class ReverseBits { public static int getNumberByReversingBits(int n) { - System.out.println(Integer.toBinaryString(n)); int m; // assume 32-bit number m = 0x55555555; // 1-bit swap - n = ((n & m) << 1) | ((n & ~m) >> 1); + n = ((n & m) << 1) | ((n & ~m) >>> 1); m = 0x33333333; // 2-bits swap - n = ((n & m) << 2) | ((n & ~m) >> 2); + n = ((n & m) << 2) | ((n & ~m) >>> 2); m = 0x0f0f0f0f; // 4-bits swap - n = ((n & m) << 4) | ((n & ~m) >> 4); + n = ((n & m) << 4) | ((n & ~m) >>> 4); m = 0x00ff00ff; // 8-bits swap - n = ((n & m) << 8) | ((n & ~m) >> 8); + n = ((n & m) << 8) | ((n & ~m) >>> 8); - n = (n << 16) | (n >> 16); // 16-bits swap + n = (n << 16) | (n >>> 16); // 16-bits swap - System.out.println(Integer.toBinaryString(n)); return n; } @@ -45,7 +43,6 @@ public static int getNumberByReversingBits(int n) { * @return */ public static int getNumberByReversingBits_V1(int n) { - System.out.println(Integer.toBinaryString(n)); int reverseNum = 0, i = 0; while (n > 0) { @@ -55,13 +52,12 @@ public static int getNumberByReversingBits_V1(int n) { n >>= 1; i++; } - System.out.println(Integer.toBinaryString(reverseNum)); return reverseNum; } public static void main(String a[]) { - System.out.println(getNumberByReversingBits(7)); - System.out.println(getNumberByReversingBits_V1(7)); + System.out.println(getNumberByReversingBits(79876)); + System.out.println(getNumberByReversingBits_V1(79876)); } } From 1c28b442eea5e680969f101b4f8fa20b372419a7 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 7 Jun 2015 13:57:51 +0530 Subject: [PATCH 073/417] bit required to change to convert a to b: done --- src/me/ramswaroop/bits/ConvertAToB.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/me/ramswaroop/bits/ConvertAToB.java diff --git a/src/me/ramswaroop/bits/ConvertAToB.java b/src/me/ramswaroop/bits/ConvertAToB.java new file mode 100644 index 00000000..4b7cbec0 --- /dev/null +++ b/src/me/ramswaroop/bits/ConvertAToB.java @@ -0,0 +1,21 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/7/15 + * @time: 1:53 PM + */ +public class ConvertAToB { + + public static int getBitsToConvertAToB(int a, int b) { + return CountSetBits.countSetBits(a ^ b); + } + + public static void main(String a[]) { + System.out.println(getBitsToConvertAToB(3, 4)); + System.out.println(getBitsToConvertAToB(3, 5)); + System.out.println(getBitsToConvertAToB(5, 3)); + } +} From 0813cec6172eeaa2506ed84b3c808053e8e3d0a6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 8 Jun 2015 14:35:32 +0530 Subject: [PATCH 074/417] tree: delete node done --- src/me/ramswaroop/bits/ConvertAToB.java | 8 +++++++ src/me/ramswaroop/trees/BinaryTree.java | 31 ++++++++++++++----------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/src/me/ramswaroop/bits/ConvertAToB.java b/src/me/ramswaroop/bits/ConvertAToB.java index 4b7cbec0..86b50931 100644 --- a/src/me/ramswaroop/bits/ConvertAToB.java +++ b/src/me/ramswaroop/bits/ConvertAToB.java @@ -9,6 +9,14 @@ */ public class ConvertAToB { + /** + * Returns the number of bits required to be + * flipped to convert {@param a} to {@param b}. + * + * @param a + * @param b + * @return + */ public static int getBitsToConvertAToB(int a, int b) { return CountSetBits.countSetBits(a ^ b); } diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 483c8245..a4daed30 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -52,6 +52,9 @@ public static void main(String[] a) { binaryTree.breadthFirstTraversalUsingQueue(); out.print("\nIn order traversal: "); binaryTree.inOrder(); + binaryTree.deleteChildrens(binaryTree.root); + out.print("\nIn order traversal after deleteChildrens: "); + binaryTree.inOrder(); } /** @@ -367,7 +370,15 @@ public void constructTreeWithInOrderAndPreOrder(List> inOrder, Lis /** - * Deletes a particular node from the tree. + * Deletes the entire tree. + */ + public void delete() { + root = null; + } + + /** + * Deletes a particular node from the tree + * and rearranges the remaining nodes. * * @param value */ @@ -376,22 +387,16 @@ public void delete(E value) { } /** - * TODO - * Deletes the entire tree. + * Deletes all child nodes of {@param node}. + * + * @param node */ - public void delete() { - delete(root); - root = null; - } - - public void delete(BinaryNode node) { + public void deleteChildrens(BinaryNode node) { if (node == null) { return; } - // first delete the child nodes - delete(node.left); - delete(node.right); - node = null; // delete node + node.left = null; + node.right = null; } From cc0080772fdddab02a5fde5619730fa7d2ddb6c9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 8 Jun 2015 16:16:00 +0530 Subject: [PATCH 075/417] two non-repeating elements done --- src/me/ramswaroop/bits/CountSetBits.java | 4 +- src/me/ramswaroop/bits/ReverseBits.java | 4 +- .../bits/TwoNonRepeatingElements.java | 57 +++++++++++++++++++ src/me/ramswaroop/trees/BinaryTree.java | 5 +- 4 files changed, 62 insertions(+), 8 deletions(-) create mode 100644 src/me/ramswaroop/bits/TwoNonRepeatingElements.java diff --git a/src/me/ramswaroop/bits/CountSetBits.java b/src/me/ramswaroop/bits/CountSetBits.java index 70a737ac..c1f607b1 100644 --- a/src/me/ramswaroop/bits/CountSetBits.java +++ b/src/me/ramswaroop/bits/CountSetBits.java @@ -34,8 +34,8 @@ static int countSetBits(int number) { * Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset * in each iteration. The time complexity is proportional to the number of bits set. * - * {@see http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity} - * {@see http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive} + * @link http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity + * @link http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive * * @param n * @return diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index 9d4c4d01..6ff2dcc7 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -6,8 +6,8 @@ * @author: ramswaroop * @date: 6/5/15 * @time: 4:26 PM - * @link http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c - * @link http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious + * @link: http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c + * @link: http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious */ public class ReverseBits { diff --git a/src/me/ramswaroop/bits/TwoNonRepeatingElements.java b/src/me/ramswaroop/bits/TwoNonRepeatingElements.java new file mode 100644 index 00000000..3aca1ebf --- /dev/null +++ b/src/me/ramswaroop/bits/TwoNonRepeatingElements.java @@ -0,0 +1,57 @@ +package me.ramswaroop.bits; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/7/15 + * @time: 2:46 PM + * @link: http://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/ + */ +public class TwoNonRepeatingElements { + + /** + * Finds the 2 non-repeating elements in an array of + * repeating elements (all elements repeated twice + * except 2 elements). + * + * @param a + * @return + */ + public static int[] getTwoNonRepeatingElementsInArray(int a[]) { + int xor = 0, setBit, x = 0, y = 0; + for (int i = 0; i < a.length; i++) { + xor ^= a[i]; // XOR all array elements + } + setBit = xor & ~(xor - 1); // get the rightmost set bit in XOR + for (int i = 0; i < a.length; i++) { + if ((a[i] & setBit) == 0) { + x ^= a[i]; // one non-repeating element + } else { + y ^= a[i]; // other non-repeating element + } + } + return new int[]{x, y}; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getTwoNonRepeatingElementsInArray(new int[]{2, 3, 4, 2, 3, 4, 5, 6}))); + } +} + +/** + * EXPLANATION: + * Consider input arr[] = {2, 4, 7, 9, 2, 4} + * 1) Get the XOR of all the elements. + * xor = 2^4^7^9^2^4 = 14 (1110) + * 2) Get a number which has only one set bit of the xor. + * Since we can easily get the rightmost set bit, let us use it. + * set_bit_no = xor & ~(xor-1) = (1110) & ~(1101) = 0010 + * Now set_bit_no will have only set as rightmost set bit of xor. + * 3) Now divide the elements in two sets and do xor of + * elements in each set, and we get the non-repeating + * elements 7 and 9. Please see implementation for this + * step. + */ diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index a4daed30..9a428558 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -758,9 +758,6 @@ public boolean isChildrenSum(BinaryNode node) { E leftChildValue = (E) (node.left == null ? 0 : node.left.value); E rightChildValue = (E) (node.right == null ? 0 : node.right.value); - boolean left = isChildrenSum(node.left); - boolean right = isChildrenSum(node.right); - if (!node.value.toString().equals( String.valueOf(Integer.parseInt(leftChildValue.toString()) + Integer.parseInt(rightChildValue.toString())) @@ -768,7 +765,7 @@ public boolean isChildrenSum(BinaryNode node) { return false; } - return left && right; + return isChildrenSum(node.left) && isChildrenSum(node.right); } /** From 3f11d73ea190bf7dfee9e536a5b7332c15f67f70 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 8 Jun 2015 17:33:47 +0530 Subject: [PATCH 076/417] rotate bits done --- src/me/ramswaroop/bits/RotateBits.java | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/me/ramswaroop/bits/RotateBits.java diff --git a/src/me/ramswaroop/bits/RotateBits.java b/src/me/ramswaroop/bits/RotateBits.java new file mode 100644 index 00000000..92cde5fc --- /dev/null +++ b/src/me/ramswaroop/bits/RotateBits.java @@ -0,0 +1,34 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/8/15 + * @time: 5:12 PM + *

+ * A ROTATION (OR CIRCULAR SHIFT) is an operation similar to + * shift except that the bits that fall off at one end are put + * back to the other end. + *

+ * For example, 000…11100101 becomes 00..0011100101000 if the number + * is rotated 3 times towards left and becomes 101000..0011100 if the + * number is rotated 3 times towards right. + */ +public class RotateBits { + + public static int leftRotateBits(int n, int times) { + return n << times | n >>> (32 - times); + } + + public static int rightRotateBits(int n, int times) { + return n >>> times | n << (32 - times); + } + + public static void main(String a[]) { + System.out.println(leftRotateBits(5, 3)); + System.out.println(leftRotateBits(234324, 3)); + System.out.println(rightRotateBits(5, 3)); + System.out.println(rightRotateBits(234324, 3)); + } +} From f78ff8d2a057c70a0c6d08fa0b5a9b844e91d35b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 8 Jun 2015 23:27:06 +0530 Subject: [PATCH 077/417] min/max done without branching --- .../ramswaroop/bits/MaxWithoutBranching.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/me/ramswaroop/bits/MaxWithoutBranching.java diff --git a/src/me/ramswaroop/bits/MaxWithoutBranching.java b/src/me/ramswaroop/bits/MaxWithoutBranching.java new file mode 100644 index 00000000..1407998b --- /dev/null +++ b/src/me/ramswaroop/bits/MaxWithoutBranching.java @@ -0,0 +1,46 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/8/15 + * @time: 5:41 PM + * @link: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax + */ +public class MaxWithoutBranching { + + public static int getMinWithoutBranching(int a, int b) { + return b ^ ((a ^ b) & -((a < b) ? 1 : 0)); + } + + public static int getMaxWithoutBranching(int a, int b) { + return a ^ ((a ^ b) & -((a < b) ? 1 : 0)); + } + + public static void main(String a[]) { + System.out.println(getMinWithoutBranching(5, 6)); + System.out.println(getMinWithoutBranching(-5, -6)); + System.out.println(getMinWithoutBranching(-5, 6)); + System.out.println(getMinWithoutBranching(5, -6)); + System.out.println(getMinWithoutBranching(0, 0)); + + System.out.println(getMaxWithoutBranching(5, 6)); + System.out.println(getMaxWithoutBranching(-5, -6)); + System.out.println(getMaxWithoutBranching(-5, 6)); + System.out.println(getMaxWithoutBranching(5, -6)); + System.out.println(getMaxWithoutBranching(0, 0)); + } +} + +/** + * EXPLANATION: + * On some rare machines where branching is very expensive and no condition move + * instructions exist, the above expression might be faster than the obvious + * approach, r = (x < y) ? x : y, even though it involves two more instructions. + * (Typically, the obvious approach is best, though.) It works because if x < y, + * then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x. + * Otherwise, if x >= y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y. + * On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, + * so there may be no advantage. + */ From f7df381ed80639bccef4970cdcc9fd30f62a9779 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 9 Jun 2015 00:00:59 +0530 Subject: [PATCH 078/417] n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number --- src/me/ramswaroop/bits/Modulo.java | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/me/ramswaroop/bits/Modulo.java diff --git a/src/me/ramswaroop/bits/Modulo.java b/src/me/ramswaroop/bits/Modulo.java new file mode 100644 index 00000000..704c4532 --- /dev/null +++ b/src/me/ramswaroop/bits/Modulo.java @@ -0,0 +1,32 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/8/15 + * @time: 11:28 PM + */ +public class Modulo { + + public static int getNmoduloD(int n, int d) { + return n & (d - 1); + } + + public static void main(String a[]) { + System.out.println(getNmoduloD(18, 8)); + System.out.println(getNmoduloD(18, 4)); + System.out.println(getNmoduloD(13, 4)); + System.out.println(getNmoduloD(13, 1)); + System.out.println(getNmoduloD(2, 2)); + System.out.println(getNmoduloD(13, 16)); + } +} + +/** + * For example, + * + * 18 = 10010 + * 8 = 01000 + * 2 = 00010 (remainder = 18 & (8-1)) + */ From 085ab9e25a9d158c84e8aac3aec5265205632cf9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 9 Jun 2015 12:54:57 +0530 Subject: [PATCH 079/417] abs without branching done --- .../ramswaroop/bits/AbsWithoutBranching.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/me/ramswaroop/bits/AbsWithoutBranching.java diff --git a/src/me/ramswaroop/bits/AbsWithoutBranching.java b/src/me/ramswaroop/bits/AbsWithoutBranching.java new file mode 100644 index 00000000..ec55ab9b --- /dev/null +++ b/src/me/ramswaroop/bits/AbsWithoutBranching.java @@ -0,0 +1,38 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/9/15 + * @time: 12:26 PM + */ +public class AbsWithoutBranching { + + /** + * Returns the absolute value of any integer. + * + * @param n + * @return + */ + public static int abs(int n) { + int mask = n >> 31; + return (mask + n) ^ mask; + } + + public static void main(String a[]) { + System.out.println(abs(-5)); + System.out.println(abs(5)); + System.out.println(abs(0)); + System.out.println(abs(-0)); + } +} + +/** + * For example, consider int takes 4 bits: + * So for input = -5, we have + * -5 = 1011 + * mask = 1111 + * mask + n = 1010 + * (mask + n)^mask = 0101 (which is 5) + */ From f7439478f4062b462bee6f0be4844445c128f061 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 9 Jun 2015 14:25:57 +0530 Subject: [PATCH 080/417] power of 4 done --- src/me/ramswaroop/bits/PowerOf4.java | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/me/ramswaroop/bits/PowerOf4.java diff --git a/src/me/ramswaroop/bits/PowerOf4.java b/src/me/ramswaroop/bits/PowerOf4.java new file mode 100644 index 00000000..5f9ec7ec --- /dev/null +++ b/src/me/ramswaroop/bits/PowerOf4.java @@ -0,0 +1,42 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/9/15 + * @time: 12:56 PM + */ +public class PowerOf4 { + + /** + * Determines whether any +ve number + * is power of 4 or not. + * + * @param n + * @return + */ + public static boolean isPowerOf4(int n) { + int zeroBitCount = 0; + // first check whether only 1 bit is set + if (n > 0 && (n & (n - 1)) == 0) { + // count no. of unset bits after the set bit + while (n > 1) { + zeroBitCount++; + n >>= 1; + } + // if no. of unset bits are even then its a power of 4 + return zeroBitCount % 2 == 0; + } + return false; + } + + public static void main(String a[]) { + System.out.println(isPowerOf4(0)); + System.out.println(isPowerOf4(1)); + System.out.println(isPowerOf4(4)); + System.out.println(isPowerOf4(16)); + System.out.println(isPowerOf4(18)); + System.out.println(isPowerOf4(64)); + } +} From 07a629bc5c2f267927136da7b91e39bb0ed9206b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 9 Jun 2015 14:49:42 +0530 Subject: [PATCH 081/417] unset rightmost set bit done --- src/me/ramswaroop/bits/RightmostSetBit.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/me/ramswaroop/bits/RightmostSetBit.java b/src/me/ramswaroop/bits/RightmostSetBit.java index 12b1d6e5..f2ae79b7 100644 --- a/src/me/ramswaroop/bits/RightmostSetBit.java +++ b/src/me/ramswaroop/bits/RightmostSetBit.java @@ -21,6 +21,10 @@ public static int getRightmostSetBitPosition(long n) { return position; } + public static long unsetRightmostSetBit(long n) { + return n & (n - 1); + } + public static void main(String a[]) { System.out.println(getRightmostSetBitPosition(0)); System.out.println(getRightmostSetBitPosition(1)); @@ -28,5 +32,14 @@ public static void main(String a[]) { System.out.println(getRightmostSetBitPosition(5)); System.out.println(getRightmostSetBitPosition(18)); System.out.println(getRightmostSetBitPosition(19)); + + System.out.println("========================"); + + System.out.println(unsetRightmostSetBit(0)); + System.out.println(unsetRightmostSetBit(2)); + System.out.println(unsetRightmostSetBit(12)); + System.out.println(unsetRightmostSetBit(16)); + System.out.println(unsetRightmostSetBit(18)); + System.out.println(unsetRightmostSetBit(-1)); } } From efa21c8615f9457691f9936cbbac7d00f4201e8c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 10 Jun 2015 12:51:12 +0530 Subject: [PATCH 082/417] multiply with 3.5 done --- src/me/ramswaroop/bits/Multiply.java | 36 +++++++++++++------ .../practice/MethodOverloading.java | 4 +++ 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/me/ramswaroop/bits/Multiply.java b/src/me/ramswaroop/bits/Multiply.java index 7422080b..3a474e54 100644 --- a/src/me/ramswaroop/bits/Multiply.java +++ b/src/me/ramswaroop/bits/Multiply.java @@ -17,13 +17,14 @@ public class Multiply { /** - * Multiplies a number with 8 by performing 3 left shifts. + * Multiplies {@param n} with 3.5 and returns only the + * integral part of the number and omits the fractional part. * * @param n * @return */ - public static long multiplyBy8(long n) { - return (n << 3); + public static long multiplyWith3point5(long n) { + return (n << 1) + n + (n >> 1); // n*2 + n + n/2 = 7n/2 = 3.5n } /** @@ -34,16 +35,31 @@ public static long multiplyBy8(long n) { * @param n * @return */ - public static long multiplyBy7(long n) { + public static long multiplyWith7(long n) { return (n << 3) - n; } + /** + * Multiplies a number with 8 by performing 3 left shifts. + * + * @param n + * @return + */ + public static long multiplyWith8(long n) { + return (n << 3); + } + public static void main(String a[]) { - System.out.println(multiplyBy7(4)); - System.out.println(multiplyBy7(6)); - System.out.println(multiplyBy7(7)); - System.out.println(multiplyBy8(4)); - System.out.println(multiplyBy8(6)); - System.out.println(multiplyBy8(7)); + System.out.println(multiplyWith3point5(3)); + System.out.println(multiplyWith3point5(4)); + System.out.println(multiplyWith3point5(6)); + System.out.println(multiplyWith3point5(-7)); + + System.out.println(multiplyWith7(6)); + System.out.println(multiplyWith7(7)); + + System.out.println(multiplyWith8(4)); + System.out.println(multiplyWith8(6)); + System.out.println(multiplyWith8(7)); } } diff --git a/src/me/ramswaroop/practice/MethodOverloading.java b/src/me/ramswaroop/practice/MethodOverloading.java index ff331734..1ae5d961 100644 --- a/src/me/ramswaroop/practice/MethodOverloading.java +++ b/src/me/ramswaroop/practice/MethodOverloading.java @@ -9,6 +9,10 @@ */ class MethodOverloading { + static void go(float x) { + System.out.print("float "); + } + static void go(Long x) { System.out.print("Long "); } From 2c9489a12f53afe786bdbe86403d72b7fa5dbde0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 10 Jun 2015 12:54:48 +0530 Subject: [PATCH 083/417] multiply with 3.5 done in more better way --- src/me/ramswaroop/bits/Multiply.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/me/ramswaroop/bits/Multiply.java b/src/me/ramswaroop/bits/Multiply.java index 3a474e54..9e3115d3 100644 --- a/src/me/ramswaroop/bits/Multiply.java +++ b/src/me/ramswaroop/bits/Multiply.java @@ -24,6 +24,17 @@ public class Multiply { * @return */ public static long multiplyWith3point5(long n) { + return ((n << 3) - n) >> 1; // (8n-n)/2 = 7n/2 = 3.5n + } + + /** + * Multiplies {@param n} with 3.5 and returns only the + * integral part of the number and omits the fractional part. + * + * @param n + * @return + */ + public static long multiplyWith3point5_V1(long n) { return (n << 1) + n + (n >> 1); // n*2 + n + n/2 = 7n/2 = 3.5n } From 5f9258e20de1c000a1bc2672dcb2ab77a8fcdb2d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 10 Jun 2015 16:37:47 +0530 Subject: [PATCH 084/417] add 1 without + operator done --- src/me/ramswaroop/bits/Addition.java | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/me/ramswaroop/bits/Addition.java diff --git a/src/me/ramswaroop/bits/Addition.java b/src/me/ramswaroop/bits/Addition.java new file mode 100644 index 00000000..e9945c99 --- /dev/null +++ b/src/me/ramswaroop/bits/Addition.java @@ -0,0 +1,39 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/10/15 + * @time: 12:55 PM + */ +public class Addition { + + /** + * Idea is to flip all the bits of {@param n} till + * rightmost 0 bit in {@param n}. + * + * @param n + * @return + */ + public static int add1(int n) { + int mask = 1; + // flip all bits in n until rightmost 0 bit + while ((n & mask) != 0) { + n ^= mask; + mask <<= 1; + } + // flip the rightmost 0 bit + return n ^ mask; + } + + public static void main(String a[]) { + System.out.println(add1(0)); + System.out.println(add1(1)); + System.out.println(add1(2)); + System.out.println(add1(3)); + System.out.println(add1(4)); + System.out.println(add1(5)); + System.out.println(add1(7)); + } +} From 700b65125873462c7967277a62746e56a2f44563 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 10 Jun 2015 17:18:14 +0530 Subject: [PATCH 085/417] add 1 done for -ve no.s --- src/me/ramswaroop/bits/Addition.java | 37 +++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/bits/Addition.java b/src/me/ramswaroop/bits/Addition.java index e9945c99..9e22d06f 100644 --- a/src/me/ramswaroop/bits/Addition.java +++ b/src/me/ramswaroop/bits/Addition.java @@ -9,14 +9,34 @@ */ public class Addition { + /** + * Best method. + *

+ * -n = ~n + 1. + * ~n = -(n+1). Therefore, n+1 = -(~n). + *

+ * Works for -ve numbers. + *

+ * Note: This method works only if the numbers + * are stored in 2’s complement form. + * + * @param n + * @return + */ + public static int add1(int n) { + return -(~n); + } + /** * Idea is to flip all the bits of {@param n} till * rightmost 0 bit in {@param n}. + *

+ * Doesn't work for -ve numbers. * * @param n * @return */ - public static int add1(int n) { + public static int add1_V1(int n) { int mask = 1; // flip all bits in n until rightmost 0 bit while ((n & mask) != 0) { @@ -28,12 +48,17 @@ public static int add1(int n) { } public static void main(String a[]) { - System.out.println(add1(0)); + System.out.println(add1_V1(0)); + System.out.println(add1_V1(1)); + System.out.println(add1_V1(2)); + System.out.println(add1_V1(3)); + System.out.println(add1_V1(4)); + System.out.println(add1_V1(5)); + System.out.println(add1_V1(7)); + System.out.println("------"); System.out.println(add1(1)); - System.out.println(add1(2)); - System.out.println(add1(3)); - System.out.println(add1(4)); System.out.println(add1(5)); - System.out.println(add1(7)); + System.out.println(add1(-0)); + System.out.println(add1(-5)); } } From 45a766bc7cb5796ace38ddc01a1ea49e5ff33564 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 11 Jun 2015 12:13:33 +0530 Subject: [PATCH 086/417] added comments --- src/me/ramswaroop/bits/Modulo.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/Modulo.java b/src/me/ramswaroop/bits/Modulo.java index 704c4532..bca0e00e 100644 --- a/src/me/ramswaroop/bits/Modulo.java +++ b/src/me/ramswaroop/bits/Modulo.java @@ -9,6 +9,14 @@ */ public class Modulo { + /** + * Returns {@param n} modulo {@param d} provided + * {@param d} is a power of 2. + * + * @param n + * @param d + * @return + */ public static int getNmoduloD(int n, int d) { return n & (d - 1); } @@ -24,9 +32,9 @@ public static void main(String a[]) { } /** - * For example, + * Consider example, for 18 % 8 * * 18 = 10010 - * 8 = 01000 + * 7 = 00111 (8 = 2 ^ 3, therefore mask has to have three 1's) * 2 = 00010 (remainder = 18 & (8-1)) */ From 5f8021c6f9e431916c52df5925df89d713c0dbb7 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 11 Jun 2015 17:56:09 +0530 Subject: [PATCH 087/417] next higher no. almost done --- src/me/ramswaroop/bits/NextHigherNumber.java | 51 ++++++++++++++++++++ src/me/ramswaroop/trees/BinaryTree.java | 1 - 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/bits/NextHigherNumber.java diff --git a/src/me/ramswaroop/bits/NextHigherNumber.java b/src/me/ramswaroop/bits/NextHigherNumber.java new file mode 100644 index 00000000..44c531c9 --- /dev/null +++ b/src/me/ramswaroop/bits/NextHigherNumber.java @@ -0,0 +1,51 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/10/15 + * @time: 6:08 PM + */ +public class NextHigherNumber { + + /** + * @param n + * @return + */ + public static int getNextHigherNumberWithSameSetBits(int n) { + int leftPattern = 1, rightPattern = 0, count = 0; + + while (n > 0) { + count++; + if (((n & 1) == 1)) { + + rightPattern <<= 1; + rightPattern |= 1; + + if (((n >> 1) & 1) == 0) { + n >>>= 1; + break; + } + } + n >>>= 1; + } + + /*System.out.println("n: " + Integer.toBinaryString(n << count)); + System.out.println("Left pattern: " + Integer.toBinaryString(leftPattern << count)); + System.out.println("Right pattern: " + Integer.toBinaryString(rightPattern >> 1));*/ + + return (n << count) | (leftPattern << count) | (rightPattern >> 1); + } + + public static void main(String a[]) { + System.out.println(getNextHigherNumberWithSameSetBits(0));//doesn't work for 0 + System.out.println(getNextHigherNumberWithSameSetBits(4));//8 + System.out.println(getNextHigherNumberWithSameSetBits(5));//6 + System.out.println(getNextHigherNumberWithSameSetBits(6));//9 + System.out.println(getNextHigherNumberWithSameSetBits(23));//27 + System.out.println(getNextHigherNumberWithSameSetBits(24));//33 + System.out.println(getNextHigherNumberWithSameSetBits(44));//49 + System.out.println(getNextHigherNumberWithSameSetBits(46));//51 + } +} diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/trees/BinaryTree.java index 9a428558..90fe6b00 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/trees/BinaryTree.java @@ -654,7 +654,6 @@ public boolean isBST(BinaryNode node, List> list) { /** * Traverse the tree in in-order fashion and keep track of prev node. *

- * TODO Clarify doubt: Why it doesn't work if I replace "prev.value" with "prev" * * @param node * @param prev From 81092c481366373f1afbcad39a38d21c1ea8fcc0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 12 Jun 2015 10:05:29 +0530 Subject: [PATCH 088/417] next higher no. done --- src/me/ramswaroop/bits/NextHigherNumber.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/bits/NextHigherNumber.java b/src/me/ramswaroop/bits/NextHigherNumber.java index 44c531c9..8130a96a 100644 --- a/src/me/ramswaroop/bits/NextHigherNumber.java +++ b/src/me/ramswaroop/bits/NextHigherNumber.java @@ -10,6 +10,19 @@ public class NextHigherNumber { /** + * The main logic is to flip the bits in the first '01' bit pattern + * of {@param n} from the right and then push all 1 bits to the right + * of '01' to the extreme right. + * + * + * For example, + * + * 3 (0000011) = 5 (0000101) + * 6 (0000110) = 9 (0001001) + * 23 (0010111) = 27 (0011011) + * 24 (0011000) = 33 (0100001) + * 46 (0101110) = 51 (0110011) + * * @param n * @return */ @@ -31,10 +44,6 @@ public static int getNextHigherNumberWithSameSetBits(int n) { n >>>= 1; } - /*System.out.println("n: " + Integer.toBinaryString(n << count)); - System.out.println("Left pattern: " + Integer.toBinaryString(leftPattern << count)); - System.out.println("Right pattern: " + Integer.toBinaryString(rightPattern >> 1));*/ - return (n << count) | (leftPattern << count) | (rightPattern >> 1); } From 1735ac9c79414d1a373f4b4c4930bd3c8020ab0c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 12 Jun 2015 17:09:31 +0530 Subject: [PATCH 089/417] boolean array puzzle done --- .../ramswaroop/bits/BooleanArrayPuzzle.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/me/ramswaroop/bits/BooleanArrayPuzzle.java diff --git a/src/me/ramswaroop/bits/BooleanArrayPuzzle.java b/src/me/ramswaroop/bits/BooleanArrayPuzzle.java new file mode 100644 index 00000000..f244d5ff --- /dev/null +++ b/src/me/ramswaroop/bits/BooleanArrayPuzzle.java @@ -0,0 +1,31 @@ +package me.ramswaroop.bits; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/12/15 + * @time: 3:31 PM + */ +public class BooleanArrayPuzzle { + + /** + * Change 1 to 0 in an array of length 2 containing + * one 0 and the other either 1 or 0. + * + * @param a + * @return + */ + public static int[] change1To0InArray(int a[]) { + a[a[1]] = a[a[0]]; + return a; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(change1To0InArray(new int[]{0, 0}))); + System.out.println(Arrays.toString(change1To0InArray(new int[]{0, 1}))); + System.out.println(Arrays.toString(change1To0InArray(new int[]{1, 0}))); + } +} From 2f627ca48889ca56428101633ad2efdb3508d59d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 13 Jun 2015 11:48:57 +0530 Subject: [PATCH 090/417] smallest element without comparison operators done --- .../ramswaroop/bits/SmallestOf3Integers.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/me/ramswaroop/bits/SmallestOf3Integers.java diff --git a/src/me/ramswaroop/bits/SmallestOf3Integers.java b/src/me/ramswaroop/bits/SmallestOf3Integers.java new file mode 100644 index 00000000..b122140d --- /dev/null +++ b/src/me/ramswaroop/bits/SmallestOf3Integers.java @@ -0,0 +1,57 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/12/15 + * @time: 6:18 PM + */ +public class SmallestOf3Integers { + + /** + * Returns min of 2 numbers without using + * any comparison operators. + * + * @param x + * @param y + * @return + */ + private static int min(int x, int y) { + return y + ((x - y) & ((x - y) >> 31)); + } + + /** + * Returns the smallest element in an + * array of length 3. + * + * @param a + * @return + */ + public static int getSmallest(int a[]) { + return min(a[0], min(a[1], a[2])); + } + + /** + * This method uses repeated subtraction to + * find the smallest element in an array. + * + * @param a + * @return + */ + public static int getSmallest_V1(int a[]) { + int c = 0; + while (a[0] > 0 && a[1] > 0 && a[2] > 0) { + a[0]--; + a[1]--; + a[2]--; + c++; + } + return c; + } + + public static void main(String a[]) { + System.out.println(getSmallest(new int[]{4, 5, 6})); + System.out.println(getSmallest_V1(new int[]{4, 5, 6})); + } +} From 7c204e94e7953628a00ca0b09eb31c4a29d3244b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 13 Jun 2015 16:42:42 +0530 Subject: [PATCH 091/417] addition without using arithmetic operators done --- src/me/ramswaroop/bits/Addition.java | 67 ++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/src/me/ramswaroop/bits/Addition.java b/src/me/ramswaroop/bits/Addition.java index 9e22d06f..b4ced8d0 100644 --- a/src/me/ramswaroop/bits/Addition.java +++ b/src/me/ramswaroop/bits/Addition.java @@ -9,6 +9,55 @@ */ public class Addition { + /** + * Better solution. + *

+ * Adds two numbers without using any + * arithmetic operators. + * + * @param x + * @param y + * @return sum of {@param x} and {@param y} + */ + public static int add(int x, int y) { + int carry; + while (y != 0) { + carry = x & y; + x = x ^ y; + y = carry << 1; + } + return x; + } + + /** + * Naive approach. + *

+ * Adds two numbers without using any + * arithmetic operators. + * + * @param x + * @param y + * @return sum of {@param x} and {@param y} + */ + public static int add_V1(int x, int y) { + int carry = 0, sum = 0, c = 0, xLSB, yLSB; + while (c < 32) { + xLSB = x & 1; + yLSB = y & 1; + sum |= (xLSB ^ yLSB ^ carry) << c; + if ((xLSB & yLSB) == 1 || (xLSB & carry) == 1 || (yLSB & carry) == 1) { + carry = 1; + } else { + carry = 0; + } + x >>= 1; + y >>= 1; + c++; + } + return sum; + } + + /** * Best method. *

@@ -48,6 +97,24 @@ public static int add1_V1(int n) { } public static void main(String a[]) { + System.out.println(add(0, 0)); //0 + System.out.println(add(12, 12)); //24 + System.out.println(add(12, 5)); //17 + System.out.println(add(3, 5)); //8 + System.out.println(add(8, 5)); //13 + System.out.println(add(13, 256)); // 269 + System.out.println(add(456, 982348234)); // 982348690 + System.out.println(add(1, 0xffffffff)); // 0 + System.out.println("------"); + System.out.println(add_V1(0, 0)); //0 + System.out.println(add_V1(12, 12)); //24 + System.out.println(add_V1(12, 5)); //17 + System.out.println(add_V1(3, 5)); //8 + System.out.println(add_V1(8, 5)); //13 + System.out.println(add_V1(13, 256)); // 269 + System.out.println(add_V1(456, 982348234)); // 982348690 + System.out.println(add_V1(1, 0xffffffff)); // 0 + System.out.println("------"); System.out.println(add1_V1(0)); System.out.println(add1_V1(1)); System.out.println(add1_V1(2)); From 4381b4d1deaec17129acb4521f44c0919b29aedf Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 14 Jun 2015 00:08:19 +0530 Subject: [PATCH 092/417] swap bit range done --- src/me/ramswaroop/bits/SwapBits.java | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/me/ramswaroop/bits/SwapBits.java diff --git a/src/me/ramswaroop/bits/SwapBits.java b/src/me/ramswaroop/bits/SwapBits.java new file mode 100644 index 00000000..bdd30a3b --- /dev/null +++ b/src/me/ramswaroop/bits/SwapBits.java @@ -0,0 +1,45 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/13/15 + * @time: 4:45 PM + */ +public class SwapBits { + + /** + * Swaps {@param length} bits in {@param n} starting from + * {@param pos1} with bits starting from {@param pos2}. + *

+ * For example, + * x = 28 (11100) + * p1 = 0 (Start from first bit from right side) + * p2 = 3 (Start from 4th bit from right side) + * l = 2 (No of bits to be swapped) + * Output: + * 7 (00111) + * + * @param n + * @param pos1 starts from 0 + * @param pos2 starts from 0 + * @param length + * @return + */ + public static int swapBitRangeInNumber(int n, int pos1, int pos2, int length) { + int set1 = (n >> pos1) & ((1 << length) - 1); // 1st set of bits to be swapped + int set2 = (n >> pos2) & ((1 << length) - 1); // 2nd set of bits to be swapped + int xor = set1 ^ set2; // difference pattern between the bits to be swapped + + return n ^ (xor << pos1) ^ (xor << pos2); // XORing the difference pattern at the appropriate + // position of the bits to be swapped gives us the result + // (this logic is similar to swapping bits using XOR) + } + + public static void main(String a[]) { + System.out.println(swapBitRangeInNumber(47, 1, 5, 3)); + System.out.println(swapBitRangeInNumber(28, 0, 3, 2)); + System.out.println(swapBitRangeInNumber(269, 1, 3, 2)); + } +} From 5db9cf78c1048d549ebdbc1d684b76610910ee88 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 14 Jun 2015 15:58:51 +0530 Subject: [PATCH 093/417] no. occurring once in array of repeated elements --- .../ramswaroop/bits/ElementOccurringOnce.java | 59 +++++++++++++++++++ src/me/ramswaroop/bits/OppositeSign.java | 21 +++++++ 2 files changed, 80 insertions(+) create mode 100644 src/me/ramswaroop/bits/ElementOccurringOnce.java create mode 100644 src/me/ramswaroop/bits/OppositeSign.java diff --git a/src/me/ramswaroop/bits/ElementOccurringOnce.java b/src/me/ramswaroop/bits/ElementOccurringOnce.java new file mode 100644 index 00000000..0d295186 --- /dev/null +++ b/src/me/ramswaroop/bits/ElementOccurringOnce.java @@ -0,0 +1,59 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/14/15 + * @time: 12:37 AM + */ +public class ElementOccurringOnce { + + /** + * Returns the element occurring once in {@param a} having + * other elements repeating thrice. + * + * @param a + * @return + */ + public static int getElementOccurringOnceInElementsRepeatedThreeTimes(int a[]) { + int result = 0; + for (int i = 0; i < 32; i++) { + int sum = 0; + // sum of all bits at ith position for all elements in a[] + for (int j = 0; j < a.length; j++) { + sum += (a[j] >>> i) & 1; + } + // bit will be set in result if sum mod 3 isn't 0 + result |= (sum % 3) << i; + } + return result; + } + + public static void main(String a[]) { + System.out.println(getElementOccurringOnceInElementsRepeatedThreeTimes(new int[]{12, 12, 6, 6, 2, 12, 6})); + System.out.println(getElementOccurringOnceInElementsRepeatedThreeTimes(new int[]{5, 5, 45, 45, 456, 5, 45})); + System.out.println(getElementOccurringOnceInElementsRepeatedThreeTimes(new int[]{12, 12, 34, 34, 6, 12, 34})); + } +} + +/** + * EXPLANATION: + * 12 = 1100 + * 12 = 1100 + * 6 = 0110 + * 6 = 0110 + * 2 = 0010 + * 12 = 1100 + * 6 = 0110 + * ------------- + * res = 0010 + * + * 1st bit of res = (0+0+0+0+0+0+0) % 3 = 0 + * 2nd bit of res = (0+0+1+1+1+0+1) % 3 = 1 + * 3rd bit of res = (1+1+1+1+0+1+1) % 3 = 0 + * 4th bit of res = (1+1+0+0+0+1+0) % 3 = 0 + * + * NOTE: Sum of bits at a particular position will not be divisible + * by 3 if the no. occurring once has a set bit at that position. + */ diff --git a/src/me/ramswaroop/bits/OppositeSign.java b/src/me/ramswaroop/bits/OppositeSign.java new file mode 100644 index 00000000..0da348ec --- /dev/null +++ b/src/me/ramswaroop/bits/OppositeSign.java @@ -0,0 +1,21 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/14/15 + * @time: 12:24 AM + */ +public class OppositeSign { + + public static int isOppositeSign(int a, int b) { + return (a ^ b) >>> 31; + } + + public static void main(String a[]) { + System.out.println(isOppositeSign(-5, -3)); + System.out.println(isOppositeSign(-5, 3)); + System.out.println(isOppositeSign(5, -3)); + } +} From fae41b37697c4038eff9d76ba107be9b233bd7b4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 15 Jun 2015 15:57:21 +0530 Subject: [PATCH 094/417] string compare ignore case done --- src/me/ramswaroop/bits/StrCmp.java | 78 ++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/me/ramswaroop/bits/StrCmp.java diff --git a/src/me/ramswaroop/bits/StrCmp.java b/src/me/ramswaroop/bits/StrCmp.java new file mode 100644 index 00000000..dceff631 --- /dev/null +++ b/src/me/ramswaroop/bits/StrCmp.java @@ -0,0 +1,78 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/15/15 + * @time: 10:38 AM + */ +public class StrCmp { + + /** + * Compares two strings {@param s1} and {@param s2} lexicographically ignoring case. + * If both are equal, it returns 0 otherwise their lexicographic differences. + * + * @param s1 + * @param s2 + * @return + */ + public static int compareStringIgnoreCase(String s1, String s2) { + int n1 = s1.length(); + int n2 = s2.length(); + int min = Math.min(n1, n2); + for (int i = 0; i < min; i++) { + char c1 = s1.charAt(i); + char c2 = s2.charAt(i); + if (c1 != c2) { + // If characters don't match but case may be ignored, + // try converting both characters to uppercase. + // If the results match, then the comparison scan should + // continue. + c1 = Character.toUpperCase(c1); + c2 = Character.toUpperCase(c2); + if (c1 != c2) { + // Unfortunately, conversion to uppercase does not work properly + // for the Georgian alphabet, which has strange rules about case + // conversion. So we need to make one last check before + // exiting. + c1 = Character.toUpperCase(c1); + c2 = Character.toUpperCase(c2); + if (c1 != c2) { + // No overflow because of numeric promotion + return c1 - c2; + } + } + } + } + return n1 - n2; + } + + public static void main(String a[]) { + System.out.println(compareStringIgnoreCase("ram", "ram")); + System.out.println(compareStringIgnoreCase("ram", "Ram")); + System.out.println(compareStringIgnoreCase("", "")); + System.out.println(compareStringIgnoreCase("", " ")); + System.out.println(compareStringIgnoreCase(" ", " ")); + System.out.println(compareStringIgnoreCase(" ", "")); + System.out.println(compareStringIgnoreCase("Geeks", "apple")); + System.out.println(compareStringIgnoreCase("", "ABCD")); + System.out.println(compareStringIgnoreCase("ABCD", "z")); + System.out.println(compareStringIgnoreCase("ABCD", "abcdEghe")); + System.out.println(compareStringIgnoreCase("GeeksForGeeks", "gEEksFORGeEKs")); + System.out.println(compareStringIgnoreCase("GeeksForGeeks", "geeksForGeeks")); + System.out.println("--------------------"); + System.out.println("ram".compareToIgnoreCase("ram")); + System.out.println("ram".compareToIgnoreCase("Ram")); + System.out.println("".compareToIgnoreCase("")); + System.out.println("".compareToIgnoreCase(" ")); + System.out.println(" ".compareToIgnoreCase(" ")); + System.out.println(" ".compareToIgnoreCase("")); + System.out.println("Geeks".compareToIgnoreCase("apple")); + System.out.println("".compareToIgnoreCase("ABCD")); + System.out.println("ABCD".compareToIgnoreCase("z")); + System.out.println("ABCD".compareToIgnoreCase("abcdEghe")); + System.out.println("GeeksForGeeks".compareToIgnoreCase("gEEksFORGeEKs")); + System.out.println("GeeksForGeeks".compareToIgnoreCase("geeksForGeeks")); + } +} From efc36c19e43eafba79132b9c2b2eb02586d849ff Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 15 Jun 2015 17:21:04 +0530 Subject: [PATCH 095/417] swap even odd bits done --- src/me/ramswaroop/bits/StrCmp.java | 2 +- src/me/ramswaroop/bits/SwapBits.java | 44 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/bits/StrCmp.java b/src/me/ramswaroop/bits/StrCmp.java index dceff631..f7820d29 100644 --- a/src/me/ramswaroop/bits/StrCmp.java +++ b/src/me/ramswaroop/bits/StrCmp.java @@ -11,7 +11,7 @@ public class StrCmp { /** * Compares two strings {@param s1} and {@param s2} lexicographically ignoring case. - * If both are equal, it returns 0 otherwise their lexicographic differences. + * If both are equal it returns 0 otherwise their lexicographic differences. * * @param s1 * @param s2 diff --git a/src/me/ramswaroop/bits/SwapBits.java b/src/me/ramswaroop/bits/SwapBits.java index bdd30a3b..fc5113b0 100644 --- a/src/me/ramswaroop/bits/SwapBits.java +++ b/src/me/ramswaroop/bits/SwapBits.java @@ -9,6 +9,40 @@ */ public class SwapBits { + /** + * Swaps bits at even position with bits + * at odd position in {@param n}. + * + * @param n + * @return + */ + public static int swapEvenOddBits(int n) { + int evenBits = n & 0x55555555; + int oddBits = n & 0xaaaaaaaa; + + return evenBits << 1 | oddBits >> 1; + } + + /** + * Swaps bits at even position with bits + * at odd position in {@param n}. + * + * @param n + * @return + */ + public static int swapEvenOddBits_V1(int n) { + for (int i = 0; i < 32; i += 2) { + int evenBit = (n >> i) & 1; + int oddBit = (n >> (i + 1)) & 1; + int xor = evenBit ^ oddBit; + + n ^= xor << i; + n ^= xor << (i + 1); + } + return n; + } + + /** * Swaps {@param length} bits in {@param n} starting from * {@param pos1} with bits starting from {@param pos2}. @@ -38,6 +72,16 @@ public static int swapBitRangeInNumber(int n, int pos1, int pos2, int length) { } public static void main(String a[]) { + System.out.println(swapEvenOddBits(23)); + System.out.println(swapEvenOddBits(0)); + System.out.println(swapEvenOddBits(5)); + System.out.println(swapEvenOddBits(6)); + System.out.println("-------------------------------"); + System.out.println(swapEvenOddBits_V1(23)); + System.out.println(swapEvenOddBits_V1(0)); + System.out.println(swapEvenOddBits_V1(5)); + System.out.println(swapEvenOddBits_V1(6)); + System.out.println("-------------------------------"); System.out.println(swapBitRangeInNumber(47, 1, 5, 3)); System.out.println(swapBitRangeInNumber(28, 0, 3, 2)); System.out.println(swapBitRangeInNumber(269, 1, 3, 2)); From 0bb9f278525f58a4bbf610892ac0017633d56b05 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 16 Jun 2015 14:32:36 +0530 Subject: [PATCH 096/417] linkedlist boilerplate code done --- src/me/ramswaroop/common/LinkedList.java | 130 ++++++++++++++++++ src/me/ramswaroop/common/LinkedQueue.java | 12 +- src/me/ramswaroop/common/LinkedStack.java | 15 +- src/me/ramswaroop/common/Stack.java | 5 +- .../linkedlists/DoubleLinkedList.java | 88 ++++++++++++ .../linkedlists/SingleLinkedList.java | 88 ++++++++++++ 6 files changed, 322 insertions(+), 16 deletions(-) create mode 100644 src/me/ramswaroop/common/LinkedList.java create mode 100644 src/me/ramswaroop/linkedlists/DoubleLinkedList.java create mode 100644 src/me/ramswaroop/linkedlists/SingleLinkedList.java diff --git a/src/me/ramswaroop/common/LinkedList.java b/src/me/ramswaroop/common/LinkedList.java new file mode 100644 index 00000000..87e7d623 --- /dev/null +++ b/src/me/ramswaroop/common/LinkedList.java @@ -0,0 +1,130 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/16/15 + * @time: 12:53 PM + */ +public interface LinkedList { + + /** + * Appends the specified element to the end of this list. + * + * @param item + * @return + */ + boolean add(E item); + + /** + * Inserts the specified element at the specified position in this list. + * + * @param index + * @param item + * @return + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + boolean add(int index, E item); + + /** + * Inserts the specified element at the beginning of this list. + * + * @param item + */ + void addFirst(E item); + + /** + * Appends the specified element to the end of this list. + * + * @param item + */ + void addLast(E item); + + /** + * Removes all of the elements from this list. + */ + void clear(); + + /** + * Returns a shallow copy of this LinkedList. + * + * @return + */ + LinkedList clone(); + + /** + * Returns true if this list contains the specified element. + * + * @param item + * @return + */ + boolean contains(E item); + + /** + * Returns the element at the specified position in this list. + * + * @param index + * @return + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + E get(int index); + + /** + * Returns the first element in this list. + * + * @return + * @throws java.util.NoSuchElementException if this list is empty + */ + E getFirst(); + + /** + * Returns the last element in this list. + * + * @return + * @throws java.util.NoSuchElementException if this list is empty + */ + E getLast(); + + /** + * Retrieves and removes the head (first element) of this list. + * + * @return + */ + E remove(); + + /** + * Removes the element at the specified position in this list. + * + * @param index + * @return + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + E remove(int index); + + /** + * Removes the first occurrence of the specified element from this list, if it is present. + * + * @param item + * @return {@code true} if this list contained the specified element + */ + boolean remove(E item); + + /** + * Replaces the element at the specified position in this list with the specified element. + * + * @param index + * @param item + * @return + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + E set(int index, E item); + + /** + * Returns the number of elements in this list. + * + * @return + */ + int size(); + +} diff --git a/src/me/ramswaroop/common/LinkedQueue.java b/src/me/ramswaroop/common/LinkedQueue.java index 4c4e402f..64763e0c 100644 --- a/src/me/ramswaroop/common/LinkedQueue.java +++ b/src/me/ramswaroop/common/LinkedQueue.java @@ -45,7 +45,7 @@ public E element() { if (front == null) { throw new NoSuchElementException(); } - return front.value; + return front.item; } @Override @@ -72,17 +72,17 @@ public void print() { return; } for (node = front; node != rear; node = node.next) { - System.out.print(node.value + ","); + System.out.print(node.item + ","); } - System.out.println(node.value + "]"); + System.out.println(node.item + "]"); } private class Node { - E value; + E item; Node next; - public Node(E value, Node next) { - this.value = value; + public Node(E item, Node next) { + this.item = item; this.next = next; } } diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java index da5e0171..113d470f 100644 --- a/src/me/ramswaroop/common/LinkedStack.java +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -37,7 +37,8 @@ public E push(E item) { } /** - * Removes the object at the top of this stack and returns that object as the value of this function. + * Removes the object at the top of this stack and + * returns it. * * @return */ @@ -58,7 +59,7 @@ public E peek() { if (top == null) { throw new EmptyStackException(); } - return top.value; + return top.item; } /** @@ -87,9 +88,9 @@ public void print() { return; } for (node = top; node.next != null; node = node.next) { - System.out.print(node.value + ","); + System.out.print(node.item + ","); } - System.out.println(node.value + "]"); + System.out.println(node.item + "]"); } /** @@ -103,11 +104,11 @@ public boolean isEmpty() { } private class Node { - E value; + E item; Node next; - Node(E value, Node next) { - this.value = value; + Node(E item, Node next) { + this.item = item; this.next = next; } } diff --git a/src/me/ramswaroop/common/Stack.java b/src/me/ramswaroop/common/Stack.java index a59dc420..2a15f154 100644 --- a/src/me/ramswaroop/common/Stack.java +++ b/src/me/ramswaroop/common/Stack.java @@ -16,9 +16,8 @@ public interface Stack { public E push(E item); /** - * Removes the object at the top of this stack and returns - * that object as the value of this function. This method - * throws an exception if this queue is empty. + * Removes the object at the top of this stack and returns it. + * This method throws an exception if this queue is empty. * * @return */ diff --git a/src/me/ramswaroop/linkedlists/DoubleLinkedList.java b/src/me/ramswaroop/linkedlists/DoubleLinkedList.java new file mode 100644 index 00000000..a162d4f9 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DoubleLinkedList.java @@ -0,0 +1,88 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.LinkedList; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/16/15 + * @time: 1:00 PM + */ +public class DoubleLinkedList implements LinkedList { + + @Override + public boolean add(E item) { + return false; + } + + @Override + public boolean add(int index, E item) { + return false; + } + + @Override + public void addFirst(E item) { + + } + + @Override + public void addLast(E item) { + + } + + @Override + public void clear() { + + } + + @Override + public LinkedList clone() { + return null; + } + + @Override + public boolean contains(E item) { + return false; + } + + @Override + public E get(int index) { + return null; + } + + @Override + public E getFirst() { + return null; + } + + @Override + public E getLast() { + return null; + } + + @Override + public E remove() { + return null; + } + + @Override + public E remove(int index) { + return null; + } + + @Override + public boolean remove(E item) { + return false; + } + + @Override + public E set(int index, E item) { + return null; + } + + @Override + public int size() { + return 0; + } +} diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java new file mode 100644 index 00000000..b0811c21 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -0,0 +1,88 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.LinkedList; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/16/15 + * @time: 1:00 PM + */ +public class SingleLinkedList implements LinkedList { + + @Override + public boolean add(E item) { + return false; + } + + @Override + public boolean add(int index, E item) { + return false; + } + + @Override + public void addFirst(E item) { + + } + + @Override + public void addLast(E item) { + + } + + @Override + public void clear() { + + } + + @Override + public LinkedList clone() { + return null; + } + + @Override + public boolean contains(E item) { + return false; + } + + @Override + public E get(int index) { + return null; + } + + @Override + public E getFirst() { + return null; + } + + @Override + public E getLast() { + return null; + } + + @Override + public E remove() { + return null; + } + + @Override + public E remove(int index) { + return null; + } + + @Override + public boolean remove(E item) { + return false; + } + + @Override + public E set(int index, E item) { + return null; + } + + @Override + public int size() { + return 0; + } +} From acc679f98a53c33c129a2e7910dfd790b69e3cc6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 16 Jun 2015 18:21:40 +0530 Subject: [PATCH 097/417] linkedlist add done --- src/me/ramswaroop/Main.java | 38 +++++++++++--- src/me/ramswaroop/common/LinkedList.java | 7 ++- .../linkedlists/DoubleLinkedList.java | 39 ++++++++++++++ .../linkedlists/SingleLinkedList.java | 52 ++++++++++++++++++- 4 files changed, 127 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 32148cf2..3d3a02f0 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -1,9 +1,7 @@ package me.ramswaroop; -import me.ramswaroop.common.LinkedQueue; -import me.ramswaroop.common.LinkedStack; -import me.ramswaroop.common.Queue; -import me.ramswaroop.common.Stack; +import me.ramswaroop.common.*; +import me.ramswaroop.linkedlists.SingleLinkedList; import java.util.Scanner; @@ -16,13 +14,14 @@ public static void main(String[] args) { Scanner in = new Scanner(System.in); Stack stack = new LinkedStack<>(); Queue queue = new LinkedQueue<>(); + LinkedList singleLinkedList = new SingleLinkedList<>(); chooseModule: while (true) { out.println("Choose module:"); out.println("=============="); out.println("1. Stack"); out.println("2. Queue"); - out.println("3. BST"); + out.println("3. SingleLinkedList"); out.println("4. Exit"); k1 = Integer.parseInt(in.nextLine()); switch (k1) { @@ -95,7 +94,34 @@ public static void main(String[] args) { } } case 3: - break; + while (true) { + out.println("Select operation:"); + out.println("================="); + out.println("1. Add"); + out.println("2. Remove"); + out.println("3. Print"); + out.println("4. Exit module"); + k2 = Integer.parseInt(in.nextLine()); + switch (k2) { + case 1: + out.println("Enter value:"); + int input = Integer.parseInt(in.nextLine()); + singleLinkedList.add(input); + singleLinkedList.printList(); + break; + case 2: + out.println("Removed element: " + singleLinkedList.remove()); + singleLinkedList.printList(); + break; + case 3: + singleLinkedList.printList(); + break; + case 5: + continue chooseModule; + default: + out.println("Wrong choice!"); + } + } case 4: out.println("Exiting..."); System.exit(0); diff --git a/src/me/ramswaroop/common/LinkedList.java b/src/me/ramswaroop/common/LinkedList.java index 87e7d623..61e0ed89 100644 --- a/src/me/ramswaroop/common/LinkedList.java +++ b/src/me/ramswaroop/common/LinkedList.java @@ -13,7 +13,7 @@ public interface LinkedList { * Appends the specified element to the end of this list. * * @param item - * @return + * @return {@code true} (as specified by {@link java.util.Collection#add}) */ boolean add(E item); @@ -86,6 +86,11 @@ public interface LinkedList { */ E getLast(); + /** + * Prints the contents of this list. + */ + void printList(); + /** * Retrieves and removes the head (first element) of this list. * diff --git a/src/me/ramswaroop/linkedlists/DoubleLinkedList.java b/src/me/ramswaroop/linkedlists/DoubleLinkedList.java index a162d4f9..d7f7a0af 100644 --- a/src/me/ramswaroop/linkedlists/DoubleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/DoubleLinkedList.java @@ -2,6 +2,8 @@ import me.ramswaroop.common.LinkedList; +import static java.lang.System.out; + /** * Created by IntelliJ IDEA. * @@ -11,6 +13,8 @@ */ public class DoubleLinkedList implements LinkedList { + Node head; + @Override public boolean add(E item) { return false; @@ -85,4 +89,39 @@ public E set(int index, E item) { public int size() { return 0; } + + @Override + public void printList() { + Node curr = head; + out.print("["); + if (curr == null) { + out.println("]"); + return; + } + while (curr.next != null) { + out.print(curr.item + ","); + curr = curr.next; + } + out.println(curr.item + "]"); + } + + private class Node { + E item; + Node next; + Node prev; + + Node(Node prev, E item, Node next) { + this.item = item; + this.next = next; + this.prev = prev; + } + + Node(Node node) { + if (node == null) return; + + this.item = node.item; + this.next = node.next; + this.prev = node.prev; + } + } } diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java index b0811c21..42098677 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -2,6 +2,8 @@ import me.ramswaroop.common.LinkedList; +import static java.lang.System.out; + /** * Created by IntelliJ IDEA. * @@ -11,9 +13,23 @@ */ public class SingleLinkedList implements LinkedList { + Node head; + int size; + @Override public boolean add(E item) { - return false; + Node newNode = new Node<>(item, null); + if (head == null) { + head = newNode; + } else { + Node curr = head; + while (curr.next != null) { + curr = curr.next; + } + curr.next = newNode; + } + size++; + return true; } @Override @@ -83,6 +99,38 @@ public E set(int index, E item) { @Override public int size() { - return 0; + return size; + } + + @Override + public void printList() { + Node curr = head; + out.print("["); + if (curr == null) { + out.println("]"); + return; + } + while (curr.next != null) { + out.print(curr.item + ","); + curr = curr.next; + } + out.println(curr.item + "]"); + } + + private class Node { + E item; + Node next; + + Node(E item, Node next) { + this.item = item; + this.next = next; + } + + Node(Node node) { + if (node == null) return; + + this.item = node.item; + this.next = node.next; + } } } From 5ba5180514a58b7557aa38a00ecd3cd3f2f543c3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 17 Jun 2015 17:00:39 +0530 Subject: [PATCH 098/417] linkedlist: add at index done --- src/me/ramswaroop/Main.java | 20 ++++++++++---- .../linkedlists/SingleLinkedList.java | 27 +++++++++++++++++-- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 3d3a02f0..8e9c1a30 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -98,22 +98,32 @@ public static void main(String[] args) { out.println("Select operation:"); out.println("================="); out.println("1. Add"); - out.println("2. Remove"); - out.println("3. Print"); - out.println("4. Exit module"); + out.println("2. Add at index"); + out.println("3. Remove"); + out.println("4. Print"); + out.println("5. Exit module"); k2 = Integer.parseInt(in.nextLine()); + int input, index; switch (k2) { case 1: out.println("Enter value:"); - int input = Integer.parseInt(in.nextLine()); + input = Integer.parseInt(in.nextLine()); singleLinkedList.add(input); singleLinkedList.printList(); break; case 2: - out.println("Removed element: " + singleLinkedList.remove()); + out.println("Enter value:"); + input = Integer.parseInt(in.nextLine()); + out.println("Enter index:"); + index = Integer.parseInt(in.nextLine()); + singleLinkedList.add(index, input); singleLinkedList.printList(); break; case 3: + out.println("Removed element: " + singleLinkedList.remove()); + singleLinkedList.printList(); + break; + case 4: singleLinkedList.printList(); break; case 5: diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java index 42098677..135b53b6 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -34,7 +34,28 @@ public boolean add(E item) { @Override public boolean add(int index, E item) { - return false; + // base case + if (index > size) { + throw new IndexOutOfBoundsException("LinkedList isn't long enough."); + } + // linkedlist is empty + if (head == null) { + head = new Node<>(item, null); + } else if (index == 0) { // add at first + Node newNode = new Node<>(item, head); + head = newNode; + } else { // add at any other location + Node curr = head; + int i = 0; + while (i < index - 1) { + curr = curr.next; + i++; + } + Node newNode = new Node<>(item, curr.next); + curr.next = newNode; + } + size++; + return true; } @Override @@ -79,7 +100,9 @@ public E getLast() { @Override public E remove() { - return null; + E item = head.item; + head = head.next; + return item; } @Override From 325ce5e510c9b8857e1d053e1a28ecaac8d8fc88 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 17 Jun 2015 18:20:14 +0530 Subject: [PATCH 099/417] linkedlist: addfirst and addlast done --- .../linkedlists/SingleLinkedList.java | 37 +++++++++++++------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java index 135b53b6..ddd570c4 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -34,16 +34,10 @@ public boolean add(E item) { @Override public boolean add(int index, E item) { - // base case - if (index > size) { - throw new IndexOutOfBoundsException("LinkedList isn't long enough."); - } - // linkedlist is empty - if (head == null) { - head = new Node<>(item, null); - } else if (index == 0) { // add at first - Node newNode = new Node<>(item, head); - head = newNode; + isIndexOutOfBounds(index); + + if (index == 0) { // add at first + addFirst(item); } else { // add at any other location Node curr = head; int i = 0; @@ -60,12 +54,13 @@ public boolean add(int index, E item) { @Override public void addFirst(E item) { - + Node newNode = new Node<>(item, head); + head = newNode; } @Override public void addLast(E item) { - + add(item); } @Override @@ -140,6 +135,24 @@ public void printList() { out.println(curr.item + "]"); } + private Node getNode(int index) { + isIndexOutOfBounds(index); + + Node curr = head; + int i = 0; + while (i < index - 1) { + curr = curr.next; + i++; + } + return curr; + } + + private void isIndexOutOfBounds(int index) { + if (index < 0 && index > size) { + throw new IndexOutOfBoundsException("Index must be less than or equal to: " + size); + } + } + private class Node { E item; Node next; From 81887c5a48d0b2c7c363e3b1e793bea61c8735b2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 17 Jun 2015 23:32:01 +0530 Subject: [PATCH 100/417] linkedlist remove almost done --- src/me/ramswaroop/common/LinkedList.java | 1 + .../linkedlists/SingleLinkedList.java | 60 +++++++++++++------ 2 files changed, 44 insertions(+), 17 deletions(-) diff --git a/src/me/ramswaroop/common/LinkedList.java b/src/me/ramswaroop/common/LinkedList.java index 61e0ed89..f25c3112 100644 --- a/src/me/ramswaroop/common/LinkedList.java +++ b/src/me/ramswaroop/common/LinkedList.java @@ -95,6 +95,7 @@ public interface LinkedList { * Retrieves and removes the head (first element) of this list. * * @return + * @throws java.util.NoSuchElementException if this list is empty */ E remove(); diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java index ddd570c4..5c6151bc 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -2,6 +2,8 @@ import me.ramswaroop.common.LinkedList; +import java.util.NoSuchElementException; + import static java.lang.System.out; /** @@ -19,9 +21,9 @@ public class SingleLinkedList implements LinkedList { @Override public boolean add(E item) { Node newNode = new Node<>(item, null); - if (head == null) { + if (head == null) { // list empty head = newNode; - } else { + } else { // add to the end of list Node curr = head; while (curr.next != null) { curr = curr.next; @@ -39,16 +41,11 @@ public boolean add(int index, E item) { if (index == 0) { // add at first addFirst(item); } else { // add at any other location - Node curr = head; - int i = 0; - while (i < index - 1) { - curr = curr.next; - i++; - } - Node newNode = new Node<>(item, curr.next); - curr.next = newNode; + Node nodeAtPrevIndex = getPredecessorNode(index); + Node newNode = new Node<>(item, nodeAtPrevIndex.next); + nodeAtPrevIndex.next = newNode; + size++; } - size++; return true; } @@ -56,6 +53,7 @@ public boolean add(int index, E item) { public void addFirst(E item) { Node newNode = new Node<>(item, head); head = newNode; + size++; } @Override @@ -80,21 +78,23 @@ public boolean contains(E item) { @Override public E get(int index) { - return null; + return getNode(index).item; } @Override public E getFirst() { - return null; + return head.item; } @Override public E getLast() { - return null; + return getNode(size - 1).item; } @Override public E remove() { + isLinkedListEmpty(); + E item = head.item; head = head.next; return item; @@ -102,7 +102,11 @@ public E remove() { @Override public E remove(int index) { - return null; + isIndexOutOfBounds(index); + + Node prevNode = getPredecessorNode(index); + prevNode.next = prevNode.next.next; + return prevNode.next.item; } @Override @@ -112,7 +116,11 @@ public boolean remove(E item) { @Override public E set(int index, E item) { - return null; + isIndexOutOfBounds(index); + + Node node = getNode(index); + node.item = item; + return node.item; } @Override @@ -135,7 +143,7 @@ public void printList() { out.println(curr.item + "]"); } - private Node getNode(int index) { + private Node getPredecessorNode(int index) { isIndexOutOfBounds(index); Node curr = head; @@ -147,6 +155,24 @@ private Node getNode(int index) { return curr; } + private Node getNode(int index) { + isIndexOutOfBounds(index); + + Node curr = head; + int i = 0; + while (i < index) { + curr = curr.next; + i++; + } + return curr; + } + + private void isLinkedListEmpty() { + if (head == null) { + throw new NoSuchElementException("LinkedList empty"); + } + } + private void isIndexOutOfBounds(int index) { if (index < 0 && index > size) { throw new IndexOutOfBoundsException("Index must be less than or equal to: " + size); From c5687fcefff4bc72a99f06bf46db6cd51e84e1eb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 18 Jun 2015 11:41:55 +0530 Subject: [PATCH 101/417] liknkedlist operations done but not tested --- src/me/ramswaroop/Main.java | 37 +++++++-- .../linkedlists/SingleLinkedList.java | 76 ++++++++++++++++--- 2 files changed, 97 insertions(+), 16 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 8e9c1a30..67f3032b 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -100,23 +100,26 @@ public static void main(String[] args) { out.println("1. Add"); out.println("2. Add at index"); out.println("3. Remove"); - out.println("4. Print"); - out.println("5. Exit module"); + out.println("4. Remove at index"); + out.println("5. Remove item"); + out.println("6. Edit item"); + out.println("7. Print"); + out.println("8. Exit module"); k2 = Integer.parseInt(in.nextLine()); - int input, index; + int item, index; switch (k2) { case 1: out.println("Enter value:"); - input = Integer.parseInt(in.nextLine()); - singleLinkedList.add(input); + item = Integer.parseInt(in.nextLine()); + singleLinkedList.add(item); singleLinkedList.printList(); break; case 2: out.println("Enter value:"); - input = Integer.parseInt(in.nextLine()); + item = Integer.parseInt(in.nextLine()); out.println("Enter index:"); index = Integer.parseInt(in.nextLine()); - singleLinkedList.add(index, input); + singleLinkedList.add(index, item); singleLinkedList.printList(); break; case 3: @@ -124,9 +127,29 @@ public static void main(String[] args) { singleLinkedList.printList(); break; case 4: + out.println("Enter index:"); + index = Integer.parseInt(in.nextLine()); + out.println("Removed element: " + singleLinkedList.remove(index)); singleLinkedList.printList(); break; case 5: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + out.println("Removed: " + singleLinkedList.remove(item)); + singleLinkedList.printList(); + break; + case 6: + out.println("Enter index to edit:"); + index = Integer.parseInt(in.nextLine()); + out.println("Enter new value:"); + item = Integer.parseInt(in.nextLine()); + singleLinkedList.set(index, item); + singleLinkedList.printList(); + break; + case 7: + singleLinkedList.printList(); + break; + case 8: continue chooseModule; default: out.println("Wrong choice!"); diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java index 5c6151bc..d645b171 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -73,7 +73,7 @@ public LinkedList clone() { @Override public boolean contains(E item) { - return false; + return getNode(item) == null; } @Override @@ -83,6 +83,7 @@ public E get(int index) { @Override public E getFirst() { + isLinkedListEmpty(); return head.item; } @@ -97,27 +98,41 @@ public E remove() { E item = head.item; head = head.next; + size--; return item; } @Override public E remove(int index) { - isIndexOutOfBounds(index); - Node prevNode = getPredecessorNode(index); - prevNode.next = prevNode.next.next; - return prevNode.next.item; + if (prevNode == null) { // index = 0 + head = head.next; + size--; + return head.item; + } else { + prevNode.next = prevNode.next.next; + size--; + return prevNode.next.item; + } } @Override public boolean remove(E item) { - return false; + if (!contains(item)) return false; + + Node prevNode = getPredecessorNode(item); + if (prevNode == null) { // index = 0 + head = head.next; + size--; + } else { + prevNode.next = prevNode.next.next; + size--; + } + return true; } @Override public E set(int index, E item) { - isIndexOutOfBounds(index); - Node node = getNode(index); node.item = item; return node.item; @@ -152,7 +167,30 @@ private Node getPredecessorNode(int index) { curr = curr.next; i++; } - return curr; + return (index == 0) ? null : curr; + } + + private Node getPredecessorNode(E item) { + Node prev = null; + Node curr = head; + if (item == null) { + while (curr != null) { + if (curr.item == item) { // when item is null, use == rather than equals() + return prev; + } + prev = curr; + curr = curr.next; + } + } else { + while (curr != null) { + if (curr.item.equals(item)) { + return prev; + } + prev = curr; + curr = curr.next; + } + } + return null; } private Node getNode(int index) { @@ -167,6 +205,26 @@ private Node getNode(int index) { return curr; } + private Node getNode(E item) { + Node curr = head; + if (item == null) { + while (curr != null) { // when item is null, use == rather than equals() + if (curr.item == item) { + return curr; + } + curr = curr.next; + } + } else { + while (curr != null) { + if (curr.item.equals(item)) { + return curr; + } + curr = curr.next; + } + } + return null; + } + private void isLinkedListEmpty() { if (head == null) { throw new NoSuchElementException("LinkedList empty"); From 377ea5c9f0686bb6ab8fba7269edddbebb878312 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 18 Jun 2015 14:27:11 +0530 Subject: [PATCH 102/417] linkedlist done (tested) --- .../linkedlists/SingleLinkedList.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/linkedlists/SingleLinkedList.java index d645b171..a13c664c 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/SingleLinkedList.java @@ -73,7 +73,7 @@ public LinkedList clone() { @Override public boolean contains(E item) { - return getNode(item) == null; + return getNode(item) != null; } @Override @@ -104,20 +104,27 @@ public E remove() { @Override public E remove(int index) { + isLinkedListEmpty(); + Node prevNode = getPredecessorNode(index); + Node delNode; if (prevNode == null) { // index = 0 + delNode = head; head = head.next; size--; - return head.item; + return delNode.item; } else { - prevNode.next = prevNode.next.next; + delNode = prevNode.next; + prevNode.next = delNode.next; size--; - return prevNode.next.item; + return delNode.item; } } @Override public boolean remove(E item) { + isLinkedListEmpty(); + if (!contains(item)) return false; Node prevNode = getPredecessorNode(item); @@ -232,8 +239,8 @@ private void isLinkedListEmpty() { } private void isIndexOutOfBounds(int index) { - if (index < 0 && index > size) { - throw new IndexOutOfBoundsException("Index must be less than or equal to: " + size); + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException("Index must be less than " + size); } } From 7ae7cd3d97684c9a1c0a6015b8140c07690a80a2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 18 Jun 2015 14:35:33 +0530 Subject: [PATCH 103/417] remove function renamed as 'remove(int)' was clashing with 'remove(E)' when E = Integer --- src/me/ramswaroop/Main.java | 3 +-- .../{linkedlists => common}/DoubleLinkedList.java | 6 ++---- src/me/ramswaroop/common/LinkedList.java | 2 +- .../{linkedlists => common}/SingleLinkedList.java | 6 ++---- 4 files changed, 6 insertions(+), 11 deletions(-) rename src/me/ramswaroop/{linkedlists => common}/DoubleLinkedList.java (94%) rename src/me/ramswaroop/{linkedlists => common}/SingleLinkedList.java (98%) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 67f3032b..6784a442 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -1,7 +1,6 @@ package me.ramswaroop; import me.ramswaroop.common.*; -import me.ramswaroop.linkedlists.SingleLinkedList; import java.util.Scanner; @@ -135,7 +134,7 @@ public static void main(String[] args) { case 5: out.println("Enter value:"); item = Integer.parseInt(in.nextLine()); - out.println("Removed: " + singleLinkedList.remove(item)); + out.println("Removed: " + singleLinkedList.removeItem(item)); singleLinkedList.printList(); break; case 6: diff --git a/src/me/ramswaroop/linkedlists/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java similarity index 94% rename from src/me/ramswaroop/linkedlists/DoubleLinkedList.java rename to src/me/ramswaroop/common/DoubleLinkedList.java index d7f7a0af..7bdcd14a 100644 --- a/src/me/ramswaroop/linkedlists/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -1,6 +1,4 @@ -package me.ramswaroop.linkedlists; - -import me.ramswaroop.common.LinkedList; +package me.ramswaroop.common; import static java.lang.System.out; @@ -76,7 +74,7 @@ public E remove(int index) { } @Override - public boolean remove(E item) { + public boolean removeItem(E item) { return false; } diff --git a/src/me/ramswaroop/common/LinkedList.java b/src/me/ramswaroop/common/LinkedList.java index f25c3112..475d98da 100644 --- a/src/me/ramswaroop/common/LinkedList.java +++ b/src/me/ramswaroop/common/LinkedList.java @@ -114,7 +114,7 @@ public interface LinkedList { * @param item * @return {@code true} if this list contained the specified element */ - boolean remove(E item); + boolean removeItem(E item); /** * Replaces the element at the specified position in this list with the specified element. diff --git a/src/me/ramswaroop/linkedlists/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java similarity index 98% rename from src/me/ramswaroop/linkedlists/SingleLinkedList.java rename to src/me/ramswaroop/common/SingleLinkedList.java index a13c664c..9161ed98 100644 --- a/src/me/ramswaroop/linkedlists/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -1,6 +1,4 @@ -package me.ramswaroop.linkedlists; - -import me.ramswaroop.common.LinkedList; +package me.ramswaroop.common; import java.util.NoSuchElementException; @@ -122,7 +120,7 @@ public E remove(int index) { } @Override - public boolean remove(E item) { + public boolean removeItem(E item) { isLinkedListEmpty(); if (!contains(item)) return false; From 947f8d540763078194bb7bf6166a279d02d70485 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 18 Jun 2015 14:51:40 +0530 Subject: [PATCH 104/417] linkedlist code structure done --- .../ramswaroop/common/DoubleLinkedList.java | 24 +------- .../ramswaroop/common/DoubleLinkedNode.java | 29 ++++++++++ .../ramswaroop/common/SingleLinkedList.java | 57 +++++++------------ .../ramswaroop/common/SingleLinkedNode.java | 26 +++++++++ src/me/ramswaroop/linkedlists/DeleteNode.java | 27 +++++++++ 5 files changed, 104 insertions(+), 59 deletions(-) create mode 100644 src/me/ramswaroop/common/DoubleLinkedNode.java create mode 100644 src/me/ramswaroop/common/SingleLinkedNode.java create mode 100644 src/me/ramswaroop/linkedlists/DeleteNode.java diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index 7bdcd14a..d1fc0a4a 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -11,7 +11,7 @@ */ public class DoubleLinkedList implements LinkedList { - Node head; + DoubleLinkedNode head; @Override public boolean add(E item) { @@ -90,7 +90,7 @@ public int size() { @Override public void printList() { - Node curr = head; + DoubleLinkedNode curr = head; out.print("["); if (curr == null) { out.println("]"); @@ -102,24 +102,4 @@ public void printList() { } out.println(curr.item + "]"); } - - private class Node { - E item; - Node next; - Node prev; - - Node(Node prev, E item, Node next) { - this.item = item; - this.next = next; - this.prev = prev; - } - - Node(Node node) { - if (node == null) return; - - this.item = node.item; - this.next = node.next; - this.prev = node.prev; - } - } } diff --git a/src/me/ramswaroop/common/DoubleLinkedNode.java b/src/me/ramswaroop/common/DoubleLinkedNode.java new file mode 100644 index 00000000..61b06f48 --- /dev/null +++ b/src/me/ramswaroop/common/DoubleLinkedNode.java @@ -0,0 +1,29 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 2:42 PM + */ +public class DoubleLinkedNode { + + E item; + DoubleLinkedNode next; + DoubleLinkedNode prev; + + DoubleLinkedNode(DoubleLinkedNode prev, E item, DoubleLinkedNode next) { + this.item = item; + this.next = next; + this.prev = prev; + } + + DoubleLinkedNode(DoubleLinkedNode node) { + if (node == null) return; + + this.item = node.item; + this.next = node.next; + this.prev = node.prev; + } +} diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index 9161ed98..b35ad984 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -13,16 +13,16 @@ */ public class SingleLinkedList implements LinkedList { - Node head; + SingleLinkedNode head; int size; @Override public boolean add(E item) { - Node newNode = new Node<>(item, null); + SingleLinkedNode newNode = new SingleLinkedNode<>(item, null); if (head == null) { // list empty head = newNode; } else { // add to the end of list - Node curr = head; + SingleLinkedNode curr = head; while (curr.next != null) { curr = curr.next; } @@ -39,8 +39,8 @@ public boolean add(int index, E item) { if (index == 0) { // add at first addFirst(item); } else { // add at any other location - Node nodeAtPrevIndex = getPredecessorNode(index); - Node newNode = new Node<>(item, nodeAtPrevIndex.next); + SingleLinkedNode nodeAtPrevIndex = getPredecessorNode(index); + SingleLinkedNode newNode = new SingleLinkedNode<>(item, nodeAtPrevIndex.next); nodeAtPrevIndex.next = newNode; size++; } @@ -49,7 +49,7 @@ public boolean add(int index, E item) { @Override public void addFirst(E item) { - Node newNode = new Node<>(item, head); + SingleLinkedNode newNode = new SingleLinkedNode<>(item, head); head = newNode; size++; } @@ -104,8 +104,8 @@ public E remove() { public E remove(int index) { isLinkedListEmpty(); - Node prevNode = getPredecessorNode(index); - Node delNode; + SingleLinkedNode prevNode = getPredecessorNode(index); + SingleLinkedNode delNode; if (prevNode == null) { // index = 0 delNode = head; head = head.next; @@ -125,7 +125,7 @@ public boolean removeItem(E item) { if (!contains(item)) return false; - Node prevNode = getPredecessorNode(item); + SingleLinkedNode prevNode = getPredecessorNode(item); if (prevNode == null) { // index = 0 head = head.next; size--; @@ -138,7 +138,7 @@ public boolean removeItem(E item) { @Override public E set(int index, E item) { - Node node = getNode(index); + SingleLinkedNode node = getNode(index); node.item = item; return node.item; } @@ -150,7 +150,7 @@ public int size() { @Override public void printList() { - Node curr = head; + SingleLinkedNode curr = head; out.print("["); if (curr == null) { out.println("]"); @@ -163,10 +163,10 @@ public void printList() { out.println(curr.item + "]"); } - private Node getPredecessorNode(int index) { + private SingleLinkedNode getPredecessorNode(int index) { isIndexOutOfBounds(index); - Node curr = head; + SingleLinkedNode curr = head; int i = 0; while (i < index - 1) { curr = curr.next; @@ -175,9 +175,9 @@ private Node getPredecessorNode(int index) { return (index == 0) ? null : curr; } - private Node getPredecessorNode(E item) { - Node prev = null; - Node curr = head; + private SingleLinkedNode getPredecessorNode(E item) { + SingleLinkedNode prev = null; + SingleLinkedNode curr = head; if (item == null) { while (curr != null) { if (curr.item == item) { // when item is null, use == rather than equals() @@ -198,10 +198,10 @@ private Node getPredecessorNode(E item) { return null; } - private Node getNode(int index) { + protected SingleLinkedNode getNode(int index) { isIndexOutOfBounds(index); - Node curr = head; + SingleLinkedNode curr = head; int i = 0; while (i < index) { curr = curr.next; @@ -210,8 +210,8 @@ private Node getNode(int index) { return curr; } - private Node getNode(E item) { - Node curr = head; + protected SingleLinkedNode getNode(E item) { + SingleLinkedNode curr = head; if (item == null) { while (curr != null) { // when item is null, use == rather than equals() if (curr.item == item) { @@ -241,21 +241,4 @@ private void isIndexOutOfBounds(int index) { throw new IndexOutOfBoundsException("Index must be less than " + size); } } - - private class Node { - E item; - Node next; - - Node(E item, Node next) { - this.item = item; - this.next = next; - } - - Node(Node node) { - if (node == null) return; - - this.item = node.item; - this.next = node.next; - } - } } diff --git a/src/me/ramswaroop/common/SingleLinkedNode.java b/src/me/ramswaroop/common/SingleLinkedNode.java new file mode 100644 index 00000000..3f71b408 --- /dev/null +++ b/src/me/ramswaroop/common/SingleLinkedNode.java @@ -0,0 +1,26 @@ +package me.ramswaroop.common; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 2:37 PM + */ +public class SingleLinkedNode { + + E item; + SingleLinkedNode next; + + SingleLinkedNode(E item, SingleLinkedNode next) { + this.item = item; + this.next = next; + } + + SingleLinkedNode(SingleLinkedNode node) { + if (node == null) return; + + this.item = node.item; + this.next = node.next; + } +} diff --git a/src/me/ramswaroop/linkedlists/DeleteNode.java b/src/me/ramswaroop/linkedlists/DeleteNode.java new file mode 100644 index 00000000..de0e2ea9 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DeleteNode.java @@ -0,0 +1,27 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 2:35 PM + */ +public class DeleteNode extends SingleLinkedList { + + public void deleteNode(SingleLinkedNode node) { + + } + + public static void main(String a[]) { + DeleteNode linkedList = new DeleteNode<>(); + linkedList.add(34); + linkedList.add(64); + linkedList.add(43); + linkedList.deleteNode(linkedList.getNode(1)); + linkedList.printList(); + } +} From bd215cae1d1967e94a50c90f2f13baaf79735313 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 18 Jun 2015 18:48:41 +0530 Subject: [PATCH 105/417] delete node done --- src/me/ramswaroop/common/SingleLinkedNode.java | 4 ++-- src/me/ramswaroop/linkedlists/DeleteNode.java | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/common/SingleLinkedNode.java b/src/me/ramswaroop/common/SingleLinkedNode.java index 3f71b408..effb4d8f 100644 --- a/src/me/ramswaroop/common/SingleLinkedNode.java +++ b/src/me/ramswaroop/common/SingleLinkedNode.java @@ -9,8 +9,8 @@ */ public class SingleLinkedNode { - E item; - SingleLinkedNode next; + public E item; + public SingleLinkedNode next; SingleLinkedNode(E item, SingleLinkedNode next) { this.item = item; diff --git a/src/me/ramswaroop/linkedlists/DeleteNode.java b/src/me/ramswaroop/linkedlists/DeleteNode.java index de0e2ea9..c8ce47a8 100644 --- a/src/me/ramswaroop/linkedlists/DeleteNode.java +++ b/src/me/ramswaroop/linkedlists/DeleteNode.java @@ -13,7 +13,9 @@ public class DeleteNode extends SingleLinkedList { public void deleteNode(SingleLinkedNode node) { - + // assert node isn't the last node in the linked list + node.item = node.next.item; + node.next = node.next.next; } public static void main(String a[]) { @@ -21,6 +23,7 @@ public static void main(String a[]) { linkedList.add(34); linkedList.add(64); linkedList.add(43); + linkedList.printList(); linkedList.deleteNode(linkedList.getNode(1)); linkedList.printList(); } From 2241912167e819e7165a52fa1dd5d10fb5dd41b4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 18 Jun 2015 19:15:50 +0530 Subject: [PATCH 106/417] nth node from last done --- .../linkedlists/NthNodeFromLast.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/NthNodeFromLast.java diff --git a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java new file mode 100644 index 00000000..0026c7ee --- /dev/null +++ b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java @@ -0,0 +1,42 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 6:49 PM + */ +public class NthNodeFromLast extends SingleLinkedList { + + public SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { + SingleLinkedNode slow = node; + SingleLinkedNode fast = node; + // move the fast reference ahead of slow reference by 'n' nodes + for (int i = 0; i < n; i++) { + // assert length of linkedlist > n + fast = fast.next; + } + while (fast != null) { + slow = slow.next; + fast = fast.next; + } + return slow; + } + + public static void main(String a[]) { + NthNodeFromLast linkedList = new NthNodeFromLast<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.add(88); + System.out.println(linkedList.getNthNodeFromLast(linkedList.getNode(0), 3).item); + } +} From da1813e53f0b6ab98245b9cb336c1839acafd363 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 19 Jun 2015 09:24:15 +0530 Subject: [PATCH 107/417] linkedlist: middle node and clear() done --- src/me/ramswaroop/Main.java | 10 ++++- .../ramswaroop/common/SingleLinkedList.java | 13 ++++++- src/me/ramswaroop/linkedlists/MiddleNode.java | 37 +++++++++++++++++++ 3 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/MiddleNode.java diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 6784a442..0d33c433 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -102,8 +102,9 @@ public static void main(String[] args) { out.println("4. Remove at index"); out.println("5. Remove item"); out.println("6. Edit item"); - out.println("7. Print"); - out.println("8. Exit module"); + out.println("7. Delete LinkedList"); + out.println("8. Print"); + out.println("9. Exit module"); k2 = Integer.parseInt(in.nextLine()); int item, index; switch (k2) { @@ -146,9 +147,14 @@ public static void main(String[] args) { singleLinkedList.printList(); break; case 7: + out.println("LinkedList deleted."); + singleLinkedList.clear(); singleLinkedList.printList(); break; case 8: + singleLinkedList.printList(); + break; + case 9: continue chooseModule; default: out.println("Wrong choice!"); diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index b35ad984..689ad57b 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -61,7 +61,18 @@ public void addLast(E item) { @Override public void clear() { - + // Clearing all of the links between nodes is "unnecessary", but: + // - helps a generational GC if the discarded nodes inhabit + // more than one generation + // - is sure to free memory even if there is a reachable Iterator + for (SingleLinkedNode node = head; node != null; ) { + SingleLinkedNode next = node.next; + node.item = null; + node.next = null; + node = next; + } + head = null; + size = 0; } @Override diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java new file mode 100644 index 00000000..15b1f109 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -0,0 +1,37 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 10:34 PM + */ +public class MiddleNode extends SingleLinkedList { + + public SingleLinkedNode getMiddleNode(SingleLinkedNode node) { + SingleLinkedNode slow = node; + SingleLinkedNode fast = node; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } + + public static void main(String a[]) { + MiddleNode linkedList = new MiddleNode<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.add(88); + System.out.println(linkedList.getMiddleNode(linkedList.getNode(0)).item); + } +} From b7765cadd0c4bccbc72ae879e572ad2ddd8a878d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 19 Jun 2015 09:57:19 +0530 Subject: [PATCH 108/417] reverse list done --- .../ramswaroop/common/SingleLinkedList.java | 4 +- .../ramswaroop/linkedlists/ReverseList.java | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/ReverseList.java diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index 689ad57b..b6b8b8cf 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -13,8 +13,8 @@ */ public class SingleLinkedList implements LinkedList { - SingleLinkedNode head; - int size; + public SingleLinkedNode head; + public int size; @Override public boolean add(E item) { diff --git a/src/me/ramswaroop/linkedlists/ReverseList.java b/src/me/ramswaroop/linkedlists/ReverseList.java new file mode 100644 index 00000000..28c6ba03 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/ReverseList.java @@ -0,0 +1,39 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/19/15 + * @time: 9:24 AM + */ +public class ReverseList extends SingleLinkedList { + + public void reverseList(SingleLinkedNode node) { + SingleLinkedNode prev = node; + SingleLinkedNode curr = node.next; + prev.next = null; // this will be the last node after reversal, so make next of node = null + while (curr != null) { + SingleLinkedNode next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } + head = prev; + } + + public static void main(String a[]) { + ReverseList linkedList = new ReverseList<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.printList(); + linkedList.reverseList(linkedList.getNode(0)); + linkedList.printList(); + } +} From 329d390254e5f472421c13c253afed58adc2188c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 19 Jun 2015 10:20:00 +0530 Subject: [PATCH 109/417] linkedlist: loop detect done --- src/me/ramswaroop/linkedlists/DetectLoop.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/DetectLoop.java diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java new file mode 100644 index 00000000..8904ea06 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -0,0 +1,50 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/19/15 + * @time: 9:24 AM + */ +public class DetectLoop extends SingleLinkedList { + + /** + * Uses Flyod's Cycle Finding algorithm. + *

+ * This is the fastest method. Traverse + * linked list using two pointers. Move one + * pointer by one and other pointer by two. + * If these pointers meet at some node then + * there is a loop. If pointers do not meet + * then linked list does not have loop. + * + * @param node + * @return + */ + public boolean isLoopPresent(SingleLinkedNode node) { + SingleLinkedNode prev = node, curr = node; + while (curr != null && curr.next != null) { + prev = prev.next; + curr = curr.next.next; + if (prev == curr) { + return true; + } + } + return false; + } + + public static void main(String a[]) { + DetectLoop linkedList = new DetectLoop<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.getNode(4).next = linkedList.getNode(3); + System.out.println(linkedList.isLoopPresent(linkedList.getNode(0))); + } +} From c34ba2257d5a9c1d17753e296d0acf70ec2f43cd Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 19 Jun 2015 12:14:21 +0530 Subject: [PATCH 110/417] detect loop done using hashmap --- src/me/ramswaroop/Main.java | 2 +- src/me/ramswaroop/linkedlists/DetectLoop.java | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 0d33c433..7ed739bc 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -147,8 +147,8 @@ public static void main(String[] args) { singleLinkedList.printList(); break; case 7: - out.println("LinkedList deleted."); singleLinkedList.clear(); + out.println("LinkedList deleted."); singleLinkedList.printList(); break; case 8: diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index 8904ea06..52b33be4 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -3,6 +3,8 @@ import me.ramswaroop.common.SingleLinkedList; import me.ramswaroop.common.SingleLinkedNode; +import java.util.HashMap; + /** * Created by IntelliJ IDEA. * @@ -22,6 +24,9 @@ public class DetectLoop extends SingleLinkedList { * there is a loop. If pointers do not meet * then linked list does not have loop. * + * Time: O(n) + * Space: O(1) + * * @param node * @return */ @@ -37,6 +42,28 @@ public boolean isLoopPresent(SingleLinkedNode node) { return false; } + /** + * Uses HashMap to store visited nodes. + *

+ * Time: O(n) + * Space: O(n) + * + * @param node + * @return + */ + public boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { + HashMap, Boolean> map = new HashMap<>(); + SingleLinkedNode curr = node; + while (curr != null) { + if (map.get(curr) != null && map.get(curr) == true) { + return true; + } + map.put(curr, true); + curr = curr.next; + } + return false; + } + public static void main(String a[]) { DetectLoop linkedList = new DetectLoop<>(); linkedList.add(11); From 90d6777e2016983aa34d3154c32fe278197a74c1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 19 Jun 2015 14:35:11 +0530 Subject: [PATCH 111/417] reverse linkedlist done recursively --- .../ramswaroop/linkedlists/ReverseList.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/ReverseList.java b/src/me/ramswaroop/linkedlists/ReverseList.java index 28c6ba03..15457b96 100644 --- a/src/me/ramswaroop/linkedlists/ReverseList.java +++ b/src/me/ramswaroop/linkedlists/ReverseList.java @@ -12,6 +12,11 @@ */ public class ReverseList extends SingleLinkedList { + /** + * Reverses the linked list using 3 references prev, curr and next. + * + * @param node + */ public void reverseList(SingleLinkedNode node) { SingleLinkedNode prev = node; SingleLinkedNode curr = node.next; @@ -25,6 +30,27 @@ public void reverseList(SingleLinkedNode node) { head = prev; } + /** + * Recursive method to reverse a linked list. + * + * @param node + * @return + */ + public SingleLinkedNode recursiveReverseList(SingleLinkedNode node) { + if (node == null) return null; + + SingleLinkedNode nextNode = recursiveReverseList(node.next); + + if (nextNode == null) { + head.next = null; // head will be the last node so head.next = null; + head = node; + } else { + nextNode.next = node; + } + + return node; + } + public static void main(String a[]) { ReverseList linkedList = new ReverseList<>(); linkedList.add(11); @@ -35,5 +61,7 @@ public static void main(String a[]) { linkedList.printList(); linkedList.reverseList(linkedList.getNode(0)); linkedList.printList(); + linkedList.recursiveReverseList(linkedList.getNode(0)); + linkedList.printList(); } } From 452f28cafc24bf3fa92cd1bb1b1e7dd117fea04c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 20 Jun 2015 12:03:13 +0530 Subject: [PATCH 112/417] IsPalindrome done --- src/me/ramswaroop/linkedlists/DeleteNode.java | 6 +-- src/me/ramswaroop/linkedlists/DetectLoop.java | 1 + .../ramswaroop/linkedlists/IsPalindrome.java | 47 +++++++++++++++++++ src/me/ramswaroop/linkedlists/MiddleNode.java | 1 + .../linkedlists/NthNodeFromLast.java | 1 + 5 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/IsPalindrome.java diff --git a/src/me/ramswaroop/linkedlists/DeleteNode.java b/src/me/ramswaroop/linkedlists/DeleteNode.java index c8ce47a8..4e1b139c 100644 --- a/src/me/ramswaroop/linkedlists/DeleteNode.java +++ b/src/me/ramswaroop/linkedlists/DeleteNode.java @@ -20,9 +20,9 @@ public void deleteNode(SingleLinkedNode node) { public static void main(String a[]) { DeleteNode linkedList = new DeleteNode<>(); - linkedList.add(34); - linkedList.add(64); - linkedList.add(43); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); linkedList.printList(); linkedList.deleteNode(linkedList.getNode(1)); linkedList.printList(); diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index 52b33be4..7db7fd8c 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -66,6 +66,7 @@ public boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { public static void main(String a[]) { DetectLoop linkedList = new DetectLoop<>(); + linkedList.add(00); linkedList.add(11); linkedList.add(22); linkedList.add(33); diff --git a/src/me/ramswaroop/linkedlists/IsPalindrome.java b/src/me/ramswaroop/linkedlists/IsPalindrome.java new file mode 100644 index 00000000..3bb9e085 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/IsPalindrome.java @@ -0,0 +1,47 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 2:35 PM + */ +public class IsPalindrome extends SingleLinkedList { + + /** + * Recursive function to test whether a linked list + * is palindrome or not. + *

+ * NOTE: This method moves the head reference. (disadvantage) + * + * @param node + * @return + */ + public boolean isPalindrome(SingleLinkedNode node) { + if (node == null) return true; + + boolean isPalindrome = isPalindrome(node.next); + + if (head.item == node.item) { + head = head.next; + return isPalindrome; + } else { + return false; + } + } + + public static void main(String a[]) { + IsPalindrome linkedList = new IsPalindrome<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(11); + linkedList.add(00); + linkedList.printList(); + System.out.println(linkedList.isPalindrome(linkedList.getNode(0))); + } +} diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java index 15b1f109..71c38201 100644 --- a/src/me/ramswaroop/linkedlists/MiddleNode.java +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -24,6 +24,7 @@ public SingleLinkedNode getMiddleNode(SingleLinkedNode node) { public static void main(String a[]) { MiddleNode linkedList = new MiddleNode<>(); + linkedList.add(00); linkedList.add(11); linkedList.add(22); linkedList.add(33); diff --git a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java index 0026c7ee..d8b5c20b 100644 --- a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java +++ b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java @@ -29,6 +29,7 @@ public SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { public static void main(String a[]) { NthNodeFromLast linkedList = new NthNodeFromLast<>(); + linkedList.add(00); linkedList.add(11); linkedList.add(22); linkedList.add(33); From c84eb46a096a8b52826c95111d3bb583fa56ed1c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 20 Jun 2015 12:57:00 +0530 Subject: [PATCH 113/417] IsPalindrome done (using stack) --- .../ramswaroop/linkedlists/IsPalindrome.java | 40 +++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/IsPalindrome.java b/src/me/ramswaroop/linkedlists/IsPalindrome.java index 3bb9e085..f6eec0d0 100644 --- a/src/me/ramswaroop/linkedlists/IsPalindrome.java +++ b/src/me/ramswaroop/linkedlists/IsPalindrome.java @@ -1,7 +1,9 @@ package me.ramswaroop.linkedlists; +import me.ramswaroop.common.LinkedStack; import me.ramswaroop.common.SingleLinkedList; import me.ramswaroop.common.SingleLinkedNode; +import me.ramswaroop.common.Stack; /** * Created by IntelliJ IDEA. @@ -12,19 +14,47 @@ */ public class IsPalindrome extends SingleLinkedList { + /** + * Uses Stack to test whether a linked list starting + * from {@param node} is palindrome or not. + * + * @param node + * @return + */ + public static boolean isPalindrome(SingleLinkedNode node) { + SingleLinkedNode curr = node; + Stack> stack = new LinkedStack<>(); + + while (curr != null) { + stack.push(curr); + curr = curr.next; + } + + curr = node; + + while (curr != null) { + if (curr.item != stack.pop().item) { + return false; + } + curr = curr.next; + } + + return true; + } + /** * Recursive function to test whether a linked list - * is palindrome or not. + * starting from {@param node} is palindrome or not. *

* NOTE: This method moves the head reference. (disadvantage) * * @param node * @return */ - public boolean isPalindrome(SingleLinkedNode node) { + public boolean isPalindromeRecursive(SingleLinkedNode node) { if (node == null) return true; - boolean isPalindrome = isPalindrome(node.next); + boolean isPalindrome = isPalindromeRecursive(node.next); if (head.item == node.item) { head = head.next; @@ -42,6 +72,8 @@ public static void main(String a[]) { linkedList.add(11); linkedList.add(00); linkedList.printList(); - System.out.println(linkedList.isPalindrome(linkedList.getNode(0))); + System.out.println(isPalindrome(linkedList.getNode(0))); + linkedList.printList(); + System.out.println(linkedList.isPalindromeRecursive(linkedList.getNode(0))); } } From 346a22cd2f17a60a32287f236f9346e9951275ec Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 20 Jun 2015 22:44:22 +0530 Subject: [PATCH 114/417] Double LinkedList operations done and tested --- src/me/ramswaroop/Main.java | 72 ++++++- .../ramswaroop/common/DoubleLinkedList.java | 175 ++++++++++++++++-- .../ramswaroop/common/SingleLinkedList.java | 12 +- 3 files changed, 233 insertions(+), 26 deletions(-) diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 7ed739bc..4f35c6bb 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -14,6 +14,7 @@ public static void main(String[] args) { Stack stack = new LinkedStack<>(); Queue queue = new LinkedQueue<>(); LinkedList singleLinkedList = new SingleLinkedList<>(); + LinkedList doubleLinkedList = new DoubleLinkedList<>(); chooseModule: while (true) { out.println("Choose module:"); @@ -21,7 +22,8 @@ public static void main(String[] args) { out.println("1. Stack"); out.println("2. Queue"); out.println("3. SingleLinkedList"); - out.println("4. Exit"); + out.println("4. DoubleLinkedList"); + out.println("5. Exit"); k1 = Integer.parseInt(in.nextLine()); switch (k1) { case 1: @@ -161,6 +163,74 @@ public static void main(String[] args) { } } case 4: + while (true) { + out.println("Select operation:"); + out.println("================="); + out.println("1. Add"); + out.println("2. Add at index"); + out.println("3. Remove"); + out.println("4. Remove at index"); + out.println("5. Remove item"); + out.println("6. Edit item"); + out.println("7. Delete LinkedList"); + out.println("8. Print"); + out.println("9. Exit module"); + k2 = Integer.parseInt(in.nextLine()); + int item, index; + switch (k2) { + case 1: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + doubleLinkedList.add(item); + doubleLinkedList.printList(); + break; + case 2: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + out.println("Enter index:"); + index = Integer.parseInt(in.nextLine()); + doubleLinkedList.add(index, item); + doubleLinkedList.printList(); + break; + case 3: + out.println("Removed element: " + doubleLinkedList.remove()); + doubleLinkedList.printList(); + break; + case 4: + out.println("Enter index:"); + index = Integer.parseInt(in.nextLine()); + out.println("Removed element: " + doubleLinkedList.remove(index)); + doubleLinkedList.printList(); + break; + case 5: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + out.println("Removed: " + doubleLinkedList.removeItem(item)); + doubleLinkedList.printList(); + break; + case 6: + out.println("Enter index to edit:"); + index = Integer.parseInt(in.nextLine()); + out.println("Enter new value:"); + item = Integer.parseInt(in.nextLine()); + doubleLinkedList.set(index, item); + doubleLinkedList.printList(); + break; + case 7: + doubleLinkedList.clear(); + out.println("LinkedList deleted."); + doubleLinkedList.printList(); + break; + case 8: + doubleLinkedList.printList(); + break; + case 9: + continue chooseModule; + default: + out.println("Wrong choice!"); + } + } + case 5: out.println("Exiting..."); System.exit(0); default: diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index d1fc0a4a..9105eb2c 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -1,5 +1,7 @@ package me.ramswaroop.common; +import java.util.NoSuchElementException; + import static java.lang.System.out; /** @@ -11,31 +13,71 @@ */ public class DoubleLinkedList implements LinkedList { - DoubleLinkedNode head; + public DoubleLinkedNode head; + public int size; @Override public boolean add(E item) { - return false; + DoubleLinkedNode newNode = new DoubleLinkedNode<>(null, item, null); + if (head == null) { // list empty + head = newNode; + } else { // add to the end of list + DoubleLinkedNode curr = head; + while (curr.next != null) { + curr = curr.next; + } + curr.next = newNode; + newNode.prev = curr; + } + size++; + return true; } @Override public boolean add(int index, E item) { - return false; + isIndexOutOfBounds(index); + + if (index == 0) { // add at first + addFirst(item); + } else { // add at any other location + DoubleLinkedNode prevNode = getPredecessorNode(index); + DoubleLinkedNode nextNode = prevNode.next; + DoubleLinkedNode newNode = new DoubleLinkedNode<>(prevNode, item, prevNode.next); + prevNode.next = newNode; + if (nextNode != null) nextNode.prev = newNode; + size++; + } + return true; } @Override public void addFirst(E item) { - + DoubleLinkedNode newNode = new DoubleLinkedNode<>(null, item, head); + if (head != null) head.prev = newNode; + head = newNode; + size++; } @Override public void addLast(E item) { - + add(item); } @Override public void clear() { - + // Clearing all of the links between nodes is "unnecessary", but: + // - helps a generational GC if the discarded nodes inhabit + // more than one generation + // - is sure to free memory even if there is a reachable Iterator + for (DoubleLinkedNode node = head; node != null; ) { + DoubleLinkedNode next = node.next; + node.item = null; + node.next = null; + node.prev = null; + node = next; + } + head = null; + size = 0; } @Override @@ -45,47 +87,90 @@ public LinkedList clone() { @Override public boolean contains(E item) { - return false; + return getNode(item) != null; } @Override public E get(int index) { - return null; + return getNode(index).item; } @Override public E getFirst() { - return null; + isLinkedListEmpty(); + return head.item; } @Override public E getLast() { - return null; + return getNode(size - 1).item; } @Override public E remove() { - return null; + isLinkedListEmpty(); + + E item = head.item; + head = head.next; + if (head != null) head.prev = null; // check for linked list size = 1 + size--; + return item; } @Override public E remove(int index) { - return null; + isLinkedListEmpty(); + + DoubleLinkedNode prevNode = getPredecessorNode(index); + DoubleLinkedNode nextNode; + DoubleLinkedNode delNode; + if (prevNode == null) { // index = 0 + delNode = head; + head = head.next; + if (head != null) head.prev = null; // check for linked list size = 1 + size--; + return delNode.item; + } else { + delNode = prevNode.next; + nextNode = delNode.next; + prevNode.next = nextNode; + if (nextNode != null) nextNode.prev = prevNode; // check needed if node to be deleted is last node + size--; + return delNode.item; + } } @Override public boolean removeItem(E item) { - return false; + isLinkedListEmpty(); + + if (!contains(item)) return false; + + DoubleLinkedNode prevNode = getPredecessorNode(item); + DoubleLinkedNode nextNode; + if (prevNode == null) { // index = 0 + head = head.next; + if (head != null) head.prev = null; // condition for list size = 1 + size--; + } else { + nextNode = prevNode.next.next; + prevNode.next = nextNode; + if (nextNode != null) nextNode.prev = prevNode; + size--; + } + return true; } @Override public E set(int index, E item) { - return null; + DoubleLinkedNode node = getNode(index); + node.item = item; + return node.item; } @Override public int size() { - return 0; + return size; } @Override @@ -96,10 +181,70 @@ public void printList() { out.println("]"); return; } + // prints the list from first node while (curr.next != null) { out.print(curr.item + ","); curr = curr.next; } out.println(curr.item + "]"); + // prints the list from last node + out.print("["); + while (curr.prev != null) { + out.print(curr.item + ","); + curr = curr.prev; + } + out.println(curr.item + "]"); + } + + private DoubleLinkedNode getPredecessorNode(int index) { + return index > 0 ? getNode(index - 1) : null; + } + + private DoubleLinkedNode getPredecessorNode(E item) { + return getNode(item) != null ? getNode(item).prev : null; + } + + protected DoubleLinkedNode getNode(int index) { + isIndexOutOfBounds(index); + + DoubleLinkedNode curr = head; + int i = 0; + while (i < index) { + curr = curr.next; + i++; + } + return curr; + } + + protected DoubleLinkedNode getNode(E item) { + DoubleLinkedNode curr = head; + if (item == null) { + while (curr != null) { // when item is null, use == rather than equals() + if (curr.item == item) { + return curr; + } + curr = curr.next; + } + } else { + while (curr != null) { + if (curr.item.equals(item)) { + return curr; + } + curr = curr.next; + } + } + return null; + } + + private void isLinkedListEmpty() { + if (head == null) { + throw new NoSuchElementException("LinkedList empty"); + } + } + + private void isIndexOutOfBounds(int index) { + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException("Index [" + index + "] must be less than size [" + size + "]"); + } } } diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index b6b8b8cf..478e9cb4 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -175,15 +175,7 @@ public void printList() { } private SingleLinkedNode getPredecessorNode(int index) { - isIndexOutOfBounds(index); - - SingleLinkedNode curr = head; - int i = 0; - while (i < index - 1) { - curr = curr.next; - i++; - } - return (index == 0) ? null : curr; + return getNode(index - 1); } private SingleLinkedNode getPredecessorNode(E item) { @@ -249,7 +241,7 @@ private void isLinkedListEmpty() { private void isIndexOutOfBounds(int index) { if (index < 0 || index > size) { - throw new IndexOutOfBoundsException("Index must be less than " + size); + throw new IndexOutOfBoundsException("Index [" + index + "] must be less than size [" + size + "]"); } } } From 0739b45db3c27629e2e8390370ad3a2b841f987a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 20 Jun 2015 23:37:22 +0530 Subject: [PATCH 115/417] code refactoring --- .../ramswaroop/common/DoubleLinkedList.java | 21 +++++++++++++++---- .../ramswaroop/common/SingleLinkedList.java | 21 +++++++++++++++---- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index 9105eb2c..cab4c151 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -35,7 +35,7 @@ public boolean add(E item) { @Override public boolean add(int index, E item) { - isIndexOutOfBounds(index); + isPositionIndex(index); if (index == 0) { // add at first addFirst(item); @@ -205,7 +205,7 @@ private DoubleLinkedNode getPredecessorNode(E item) { } protected DoubleLinkedNode getNode(int index) { - isIndexOutOfBounds(index); + isElementIndex(index); DoubleLinkedNode curr = head; int i = 0; @@ -242,9 +242,22 @@ private void isLinkedListEmpty() { } } - private void isIndexOutOfBounds(int index) { - if (index < 0 || index > size) { + /** + * Tells if the argument is the index of an existing element. + */ + private void isElementIndex(int index) { + if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index [" + index + "] must be less than size [" + size + "]"); } } + + /** + * Tells if the argument is the index of a valid position for an + * iterator or an add operation. + */ + private void isPositionIndex(int index) { + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException("Index [" + index + "] must be less than or equal to size [" + size + "]"); + } + } } diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index 478e9cb4..bfb7a97b 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -34,7 +34,7 @@ public boolean add(E item) { @Override public boolean add(int index, E item) { - isIndexOutOfBounds(index); + isPositionIndex(index); if (index == 0) { // add at first addFirst(item); @@ -202,7 +202,7 @@ private SingleLinkedNode getPredecessorNode(E item) { } protected SingleLinkedNode getNode(int index) { - isIndexOutOfBounds(index); + isElementIndex(index); SingleLinkedNode curr = head; int i = 0; @@ -239,9 +239,22 @@ private void isLinkedListEmpty() { } } - private void isIndexOutOfBounds(int index) { - if (index < 0 || index > size) { + /** + * Tells if the argument is the index of an existing element. + */ + private void isElementIndex(int index) { + if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index [" + index + "] must be less than size [" + size + "]"); } } + + /** + * Tells if the argument is the index of a valid position for an + * iterator or an add operation. + */ + private void isPositionIndex(int index) { + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException("Index [" + index + "] must be less than or equal to size [" + size + "]"); + } + } } From d0861cd3fbf651ad17402f727794a9ccb7944870 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 21 Jun 2015 16:43:11 +0530 Subject: [PATCH 116/417] clone with random pointers almost done + code refactoring --- .../ramswaroop/common/DoubleLinkedList.java | 14 +++-- .../ramswaroop/common/DoubleLinkedNode.java | 10 +-- .../ramswaroop/common/SingleLinkedList.java | 4 +- .../ramswaroop/common/SingleLinkedNode.java | 4 +- .../linkedlists/CloneWithRandPointers.java | 62 +++++++++++++++++++ src/me/ramswaroop/linkedlists/DeleteNode.java | 12 +++- src/me/ramswaroop/linkedlists/DetectLoop.java | 8 +-- src/me/ramswaroop/linkedlists/MiddleNode.java | 6 +- .../linkedlists/NthNodeFromLast.java | 6 +- 9 files changed, 100 insertions(+), 26 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/CloneWithRandPointers.java diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index cab4c151..9c1919c9 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -188,12 +188,18 @@ public void printList() { } out.println(curr.item + "]"); // prints the list from last node - out.print("["); + /*out.print("["); while (curr.prev != null) { out.print(curr.item + ","); curr = curr.prev; } - out.println(curr.item + "]"); + out.println(curr.item + "]");*/ + } + + public static DoubleLinkedList getLinkedList(DoubleLinkedNode node) { + DoubleLinkedList linkedList = new DoubleLinkedList<>(); + linkedList.head = node; + return linkedList; } private DoubleLinkedNode getPredecessorNode(int index) { @@ -204,7 +210,7 @@ private DoubleLinkedNode getPredecessorNode(E item) { return getNode(item) != null ? getNode(item).prev : null; } - protected DoubleLinkedNode getNode(int index) { + public DoubleLinkedNode getNode(int index) { isElementIndex(index); DoubleLinkedNode curr = head; @@ -216,7 +222,7 @@ protected DoubleLinkedNode getNode(int index) { return curr; } - protected DoubleLinkedNode getNode(E item) { + public DoubleLinkedNode getNode(E item) { DoubleLinkedNode curr = head; if (item == null) { while (curr != null) { // when item is null, use == rather than equals() diff --git a/src/me/ramswaroop/common/DoubleLinkedNode.java b/src/me/ramswaroop/common/DoubleLinkedNode.java index 61b06f48..b0de1911 100644 --- a/src/me/ramswaroop/common/DoubleLinkedNode.java +++ b/src/me/ramswaroop/common/DoubleLinkedNode.java @@ -9,17 +9,17 @@ */ public class DoubleLinkedNode { - E item; - DoubleLinkedNode next; - DoubleLinkedNode prev; + public E item; + public DoubleLinkedNode next; + public DoubleLinkedNode prev; - DoubleLinkedNode(DoubleLinkedNode prev, E item, DoubleLinkedNode next) { + public DoubleLinkedNode(DoubleLinkedNode prev, E item, DoubleLinkedNode next) { this.item = item; this.next = next; this.prev = prev; } - DoubleLinkedNode(DoubleLinkedNode node) { + public DoubleLinkedNode(DoubleLinkedNode node) { if (node == null) return; this.item = node.item; diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index bfb7a97b..f5942ab4 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -201,7 +201,7 @@ private SingleLinkedNode getPredecessorNode(E item) { return null; } - protected SingleLinkedNode getNode(int index) { + public SingleLinkedNode getNode(int index) { isElementIndex(index); SingleLinkedNode curr = head; @@ -213,7 +213,7 @@ protected SingleLinkedNode getNode(int index) { return curr; } - protected SingleLinkedNode getNode(E item) { + public SingleLinkedNode getNode(E item) { SingleLinkedNode curr = head; if (item == null) { while (curr != null) { // when item is null, use == rather than equals() diff --git a/src/me/ramswaroop/common/SingleLinkedNode.java b/src/me/ramswaroop/common/SingleLinkedNode.java index effb4d8f..e26f750e 100644 --- a/src/me/ramswaroop/common/SingleLinkedNode.java +++ b/src/me/ramswaroop/common/SingleLinkedNode.java @@ -12,12 +12,12 @@ public class SingleLinkedNode { public E item; public SingleLinkedNode next; - SingleLinkedNode(E item, SingleLinkedNode next) { + public SingleLinkedNode(E item, SingleLinkedNode next) { this.item = item; this.next = next; } - SingleLinkedNode(SingleLinkedNode node) { + public SingleLinkedNode(SingleLinkedNode node) { if (node == null) return; this.item = node.item; diff --git a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java new file mode 100644 index 00000000..e7047bd4 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java @@ -0,0 +1,62 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.DoubleLinkedList; +import me.ramswaroop.common.DoubleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/20/15 + * @time: 1:00 PM + */ +public class CloneWithRandPointers extends DoubleLinkedList { + + public static DoubleLinkedList clone(DoubleLinkedNode node) { + DoubleLinkedNode curr = node; + + // copy node and insert after it + while (curr != null && curr.next != null) { + DoubleLinkedNode newNode = new DoubleLinkedNode<>(null, curr.item, curr.next); + curr.next = newNode; + curr = curr.next.next; + } + + curr = node; + + // copy all random pointers + while (curr != null && curr.next != null) { + curr.next.prev = curr.prev; + curr = curr.next.next; + } + + curr = node; + DoubleLinkedNode cloneHead = node.next; + DoubleLinkedNode dupNode; + // separate the copy nodes into a different linked list + while (curr != null) { + dupNode = curr.next; + curr.next = (dupNode != null) ? dupNode.next : null; + if (dupNode != null) { + dupNode.next = (curr.next != null) ? curr.next.next : null; + } + curr = curr.next; + } + return DoubleLinkedList.getLinkedList(cloneHead); + } + + public static void main(String a[]) { + DoubleLinkedList linkedList = new DoubleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.getNode(0).prev = linkedList.getNode(2); + linkedList.getNode(1).prev = linkedList.getNode(3); + linkedList.getNode(2).prev = linkedList.getNode(0); + linkedList.getNode(3).prev = linkedList.getNode(1); + linkedList.printList(); + DoubleLinkedList clonedList = clone(linkedList.getNode(0)); + clonedList.printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/DeleteNode.java b/src/me/ramswaroop/linkedlists/DeleteNode.java index 4e1b139c..93d55798 100644 --- a/src/me/ramswaroop/linkedlists/DeleteNode.java +++ b/src/me/ramswaroop/linkedlists/DeleteNode.java @@ -12,19 +12,25 @@ */ public class DeleteNode extends SingleLinkedList { - public void deleteNode(SingleLinkedNode node) { + /** + * Given a pointer to a node, delete it. + * + * @param node + * @param + */ + public static void deleteNode(SingleLinkedNode node) { // assert node isn't the last node in the linked list node.item = node.next.item; node.next = node.next.next; } public static void main(String a[]) { - DeleteNode linkedList = new DeleteNode<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); linkedList.add(11); linkedList.add(22); linkedList.printList(); - linkedList.deleteNode(linkedList.getNode(1)); + deleteNode(linkedList.getNode(1)); linkedList.printList(); } } diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index 7db7fd8c..626aacbd 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -30,7 +30,7 @@ public class DetectLoop extends SingleLinkedList { * @param node * @return */ - public boolean isLoopPresent(SingleLinkedNode node) { + public static boolean isLoopPresent(SingleLinkedNode node) { SingleLinkedNode prev = node, curr = node; while (curr != null && curr.next != null) { prev = prev.next; @@ -51,7 +51,7 @@ public boolean isLoopPresent(SingleLinkedNode node) { * @param node * @return */ - public boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { + public static boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { HashMap, Boolean> map = new HashMap<>(); SingleLinkedNode curr = node; while (curr != null) { @@ -65,7 +65,7 @@ public boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { } public static void main(String a[]) { - DetectLoop linkedList = new DetectLoop<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); linkedList.add(11); linkedList.add(22); @@ -73,6 +73,6 @@ public static void main(String a[]) { linkedList.add(44); linkedList.add(55); linkedList.getNode(4).next = linkedList.getNode(3); - System.out.println(linkedList.isLoopPresent(linkedList.getNode(0))); + System.out.println(isLoopPresent(linkedList.getNode(0))); } } diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java index 71c38201..46a3f1bc 100644 --- a/src/me/ramswaroop/linkedlists/MiddleNode.java +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -12,7 +12,7 @@ */ public class MiddleNode extends SingleLinkedList { - public SingleLinkedNode getMiddleNode(SingleLinkedNode node) { + public static SingleLinkedNode getMiddleNode(SingleLinkedNode node) { SingleLinkedNode slow = node; SingleLinkedNode fast = node; while (fast != null && fast.next != null) { @@ -23,7 +23,7 @@ public SingleLinkedNode getMiddleNode(SingleLinkedNode node) { } public static void main(String a[]) { - MiddleNode linkedList = new MiddleNode<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); linkedList.add(11); linkedList.add(22); @@ -33,6 +33,6 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.add(88); - System.out.println(linkedList.getMiddleNode(linkedList.getNode(0)).item); + System.out.println(getMiddleNode(linkedList.getNode(0)).item); } } diff --git a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java index d8b5c20b..1425695e 100644 --- a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java +++ b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java @@ -12,7 +12,7 @@ */ public class NthNodeFromLast extends SingleLinkedList { - public SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { + public static SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { SingleLinkedNode slow = node; SingleLinkedNode fast = node; // move the fast reference ahead of slow reference by 'n' nodes @@ -28,7 +28,7 @@ public SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { } public static void main(String a[]) { - NthNodeFromLast linkedList = new NthNodeFromLast<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); linkedList.add(11); linkedList.add(22); @@ -38,6 +38,6 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.add(88); - System.out.println(linkedList.getNthNodeFromLast(linkedList.getNode(0), 3).item); + System.out.println(getNthNodeFromLast(linkedList.getNode(0), 3).item); } } From 72c2687019daadffadc4e569a52d0ca37f226493 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 21 Jun 2015 22:39:23 +0530 Subject: [PATCH 117/417] insertion in sorted linked list --- .../ramswaroop/common/DoubleLinkedList.java | 4 +- .../ramswaroop/common/DoubleLinkedNode.java | 2 +- src/me/ramswaroop/common/LinkedList.java | 2 +- .../ramswaroop/common/SingleLinkedList.java | 2 +- .../ramswaroop/common/SingleLinkedNode.java | 2 +- .../linkedlists/CloneWithRandPointers.java | 7 +++- src/me/ramswaroop/linkedlists/DeleteNode.java | 4 +- src/me/ramswaroop/linkedlists/DetectLoop.java | 6 +-- .../linkedlists/InsertionInSortedList.java | 41 +++++++++++++++++++ .../ramswaroop/linkedlists/IsPalindrome.java | 4 +- src/me/ramswaroop/linkedlists/MiddleNode.java | 4 +- .../linkedlists/NthNodeFromLast.java | 4 +- .../ramswaroop/linkedlists/ReverseList.java | 2 +- 13 files changed, 64 insertions(+), 20 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/InsertionInSortedList.java diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index 9c1919c9..0ac6a342 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -11,7 +11,7 @@ * @date: 6/16/15 * @time: 1:00 PM */ -public class DoubleLinkedList implements LinkedList { +public class DoubleLinkedList> implements LinkedList { public DoubleLinkedNode head; public int size; @@ -196,7 +196,7 @@ public void printList() { out.println(curr.item + "]");*/ } - public static DoubleLinkedList getLinkedList(DoubleLinkedNode node) { + public static > DoubleLinkedList getLinkedList(DoubleLinkedNode node) { DoubleLinkedList linkedList = new DoubleLinkedList<>(); linkedList.head = node; return linkedList; diff --git a/src/me/ramswaroop/common/DoubleLinkedNode.java b/src/me/ramswaroop/common/DoubleLinkedNode.java index b0de1911..caebe339 100644 --- a/src/me/ramswaroop/common/DoubleLinkedNode.java +++ b/src/me/ramswaroop/common/DoubleLinkedNode.java @@ -7,7 +7,7 @@ * @date: 6/18/15 * @time: 2:42 PM */ -public class DoubleLinkedNode { +public class DoubleLinkedNode> { public E item; public DoubleLinkedNode next; diff --git a/src/me/ramswaroop/common/LinkedList.java b/src/me/ramswaroop/common/LinkedList.java index 475d98da..1819496e 100644 --- a/src/me/ramswaroop/common/LinkedList.java +++ b/src/me/ramswaroop/common/LinkedList.java @@ -7,7 +7,7 @@ * @date: 6/16/15 * @time: 12:53 PM */ -public interface LinkedList { +public interface LinkedList> { /** * Appends the specified element to the end of this list. diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index f5942ab4..4d6a4019 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -11,7 +11,7 @@ * @date: 6/16/15 * @time: 1:00 PM */ -public class SingleLinkedList implements LinkedList { +public class SingleLinkedList> implements LinkedList { public SingleLinkedNode head; public int size; diff --git a/src/me/ramswaroop/common/SingleLinkedNode.java b/src/me/ramswaroop/common/SingleLinkedNode.java index e26f750e..e1b006e6 100644 --- a/src/me/ramswaroop/common/SingleLinkedNode.java +++ b/src/me/ramswaroop/common/SingleLinkedNode.java @@ -7,7 +7,7 @@ * @date: 6/18/15 * @time: 2:37 PM */ -public class SingleLinkedNode { +public class SingleLinkedNode> { public E item; public SingleLinkedNode next; diff --git a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java index e7047bd4..dc2f1416 100644 --- a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java +++ b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java @@ -10,9 +10,9 @@ * @date: 6/20/15 * @time: 1:00 PM */ -public class CloneWithRandPointers extends DoubleLinkedList { +public class CloneWithRandPointers> extends DoubleLinkedList { - public static DoubleLinkedList clone(DoubleLinkedNode node) { + public static > DoubleLinkedList clone(DoubleLinkedNode node) { DoubleLinkedNode curr = node; // copy node and insert after it @@ -57,6 +57,9 @@ public static void main(String a[]) { linkedList.getNode(3).prev = linkedList.getNode(1); linkedList.printList(); DoubleLinkedList clonedList = clone(linkedList.getNode(0)); + clonedList.size = 4; + clonedList.set(1, 567); clonedList.printList(); + linkedList.printList(); } } diff --git a/src/me/ramswaroop/linkedlists/DeleteNode.java b/src/me/ramswaroop/linkedlists/DeleteNode.java index 93d55798..9474c767 100644 --- a/src/me/ramswaroop/linkedlists/DeleteNode.java +++ b/src/me/ramswaroop/linkedlists/DeleteNode.java @@ -10,7 +10,7 @@ * @date: 6/18/15 * @time: 2:35 PM */ -public class DeleteNode extends SingleLinkedList { +public class DeleteNode> extends SingleLinkedList { /** * Given a pointer to a node, delete it. @@ -18,7 +18,7 @@ public class DeleteNode extends SingleLinkedList { * @param node * @param */ - public static void deleteNode(SingleLinkedNode node) { + public static > void deleteNode(SingleLinkedNode node) { // assert node isn't the last node in the linked list node.item = node.next.item; node.next = node.next.next; diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index 626aacbd..28d55bb6 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -12,7 +12,7 @@ * @date: 6/19/15 * @time: 9:24 AM */ -public class DetectLoop extends SingleLinkedList { +public class DetectLoop> extends SingleLinkedList { /** * Uses Flyod's Cycle Finding algorithm. @@ -30,7 +30,7 @@ public class DetectLoop extends SingleLinkedList { * @param node * @return */ - public static boolean isLoopPresent(SingleLinkedNode node) { + public static > boolean isLoopPresent(SingleLinkedNode node) { SingleLinkedNode prev = node, curr = node; while (curr != null && curr.next != null) { prev = prev.next; @@ -51,7 +51,7 @@ public static boolean isLoopPresent(SingleLinkedNode node) { * @param node * @return */ - public static boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { + public static > boolean isLoopPresentUsingHashMap(SingleLinkedNode node) { HashMap, Boolean> map = new HashMap<>(); SingleLinkedNode curr = node; while (curr != null) { diff --git a/src/me/ramswaroop/linkedlists/InsertionInSortedList.java b/src/me/ramswaroop/linkedlists/InsertionInSortedList.java new file mode 100644 index 00000000..7e93fc6f --- /dev/null +++ b/src/me/ramswaroop/linkedlists/InsertionInSortedList.java @@ -0,0 +1,41 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/21/15 + * @time: 10:20 PM + */ +public class InsertionInSortedList> extends SingleLinkedList { + + /** + * Insert an element in the sorted linked list. + * + * @param item + */ + public void insert(E item) { + int index = 0; + SingleLinkedNode node = head; + while (node != null) { + if (item.compareTo(node.item) < 0) break; + index++; + node = node.next; + } + add(index, item); + } + + public static void main(String a[]) { + InsertionInSortedList linkedList = new InsertionInSortedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.printList(); + linkedList.insert(13); + linkedList.printList(); + } +} \ No newline at end of file diff --git a/src/me/ramswaroop/linkedlists/IsPalindrome.java b/src/me/ramswaroop/linkedlists/IsPalindrome.java index f6eec0d0..2aed3858 100644 --- a/src/me/ramswaroop/linkedlists/IsPalindrome.java +++ b/src/me/ramswaroop/linkedlists/IsPalindrome.java @@ -12,7 +12,7 @@ * @date: 6/18/15 * @time: 2:35 PM */ -public class IsPalindrome extends SingleLinkedList { +public class IsPalindrome> extends SingleLinkedList { /** * Uses Stack to test whether a linked list starting @@ -21,7 +21,7 @@ public class IsPalindrome extends SingleLinkedList { * @param node * @return */ - public static boolean isPalindrome(SingleLinkedNode node) { + public static > boolean isPalindrome(SingleLinkedNode node) { SingleLinkedNode curr = node; Stack> stack = new LinkedStack<>(); diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java index 46a3f1bc..eff6fd54 100644 --- a/src/me/ramswaroop/linkedlists/MiddleNode.java +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -10,9 +10,9 @@ * @date: 6/18/15 * @time: 10:34 PM */ -public class MiddleNode extends SingleLinkedList { +public class MiddleNode> extends SingleLinkedList { - public static SingleLinkedNode getMiddleNode(SingleLinkedNode node) { + public static > SingleLinkedNode getMiddleNode(SingleLinkedNode node) { SingleLinkedNode slow = node; SingleLinkedNode fast = node; while (fast != null && fast.next != null) { diff --git a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java index 1425695e..e07cb19c 100644 --- a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java +++ b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java @@ -10,9 +10,9 @@ * @date: 6/18/15 * @time: 6:49 PM */ -public class NthNodeFromLast extends SingleLinkedList { +public class NthNodeFromLast> extends SingleLinkedList { - public static SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { + public static > SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { SingleLinkedNode slow = node; SingleLinkedNode fast = node; // move the fast reference ahead of slow reference by 'n' nodes diff --git a/src/me/ramswaroop/linkedlists/ReverseList.java b/src/me/ramswaroop/linkedlists/ReverseList.java index 15457b96..17ac4471 100644 --- a/src/me/ramswaroop/linkedlists/ReverseList.java +++ b/src/me/ramswaroop/linkedlists/ReverseList.java @@ -10,7 +10,7 @@ * @date: 6/19/15 * @time: 9:24 AM */ -public class ReverseList extends SingleLinkedList { +public class ReverseList> extends SingleLinkedList { /** * Reverses the linked list using 3 references prev, curr and next. From 88cfd305f00bf2c6bfe07443d0580e4e80b0b08f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 22 Jun 2015 13:58:37 +0530 Subject: [PATCH 118/417] clone linkedlist with random pointers done (optimization pending) --- .../ramswaroop/common/DoubleLinkedList.java | 4 +-- .../linkedlists/CloneWithRandPointers.java | 25 +++++++++---------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index 0ac6a342..88956f05 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -188,12 +188,12 @@ public void printList() { } out.println(curr.item + "]"); // prints the list from last node - /*out.print("["); + out.print("["); while (curr.prev != null) { out.print(curr.item + ","); curr = curr.prev; } - out.println(curr.item + "]");*/ + out.println(curr.item + "]"); } public static > DoubleLinkedList getLinkedList(DoubleLinkedNode node) { diff --git a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java index dc2f1416..c41289ed 100644 --- a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java +++ b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java @@ -15,33 +15,31 @@ public class CloneWithRandPointers> extends DoubleLinked public static > DoubleLinkedList clone(DoubleLinkedNode node) { DoubleLinkedNode curr = node; - // copy node and insert after it - while (curr != null && curr.next != null) { + // copy each node and insert after it + while (curr != null) { DoubleLinkedNode newNode = new DoubleLinkedNode<>(null, curr.item, curr.next); curr.next = newNode; curr = curr.next.next; } + // copy all random pointers from original node to the copied node curr = node; - - // copy all random pointers while (curr != null && curr.next != null) { - curr.next.prev = curr.prev; + curr.next.prev = (curr.prev != null) ? curr.prev.next : null; curr = curr.next.next; } + // separate the copied nodes into a different linked list curr = node; DoubleLinkedNode cloneHead = node.next; - DoubleLinkedNode dupNode; - // separate the copy nodes into a different linked list - while (curr != null) { + DoubleLinkedNode dupNode = cloneHead; + while (curr != null && curr.next != null) { dupNode = curr.next; curr.next = (dupNode != null) ? dupNode.next : null; - if (dupNode != null) { - dupNode.next = (curr.next != null) ? curr.next.next : null; - } + dupNode.next = (curr.next != null) ? curr.next.next : null; curr = curr.next; } + return DoubleLinkedList.getLinkedList(cloneHead); } @@ -51,13 +49,14 @@ public static void main(String a[]) { linkedList.add(11); linkedList.add(22); linkedList.add(33); - linkedList.getNode(0).prev = linkedList.getNode(2); - linkedList.getNode(1).prev = linkedList.getNode(3); + linkedList.getNode(0).prev = null; + linkedList.getNode(1).prev = linkedList.getNode(2); linkedList.getNode(2).prev = linkedList.getNode(0); linkedList.getNode(3).prev = linkedList.getNode(1); linkedList.printList(); DoubleLinkedList clonedList = clone(linkedList.getNode(0)); clonedList.size = 4; + clonedList.set(0, 234); clonedList.set(1, 567); clonedList.printList(); linkedList.printList(); From 99407a32c877617eb29b9f2128049e29cd859074 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 22 Jun 2015 16:33:17 +0530 Subject: [PATCH 119/417] intersection of 2 lists done + code refactoring --- .../ramswaroop/common/DoubleLinkedList.java | 7 ++ .../ramswaroop/common/SingleLinkedList.java | 13 ++++ .../linkedlists/CloneWithRandPointers.java | 2 +- .../linkedlists/IntersectionOfTwoLists.java | 67 +++++++++++++++++++ 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index 88956f05..3a2961d8 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -198,7 +198,14 @@ public void printList() { public static > DoubleLinkedList getLinkedList(DoubleLinkedNode node) { DoubleLinkedList linkedList = new DoubleLinkedList<>(); + // set head linkedList.head = node; + // set size + DoubleLinkedNode curr = node; + while (curr != null) { + linkedList.size++; + curr = curr.next; + } return linkedList; } diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index 4d6a4019..b530c7e4 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -174,6 +174,19 @@ public void printList() { out.println(curr.item + "]"); } + public static > SingleLinkedList getLinkedList(SingleLinkedNode node) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + // set head + linkedList.head = node; + // set size + SingleLinkedNode curr = node; + while (curr != null) { + linkedList.size++; + curr = curr.next; + } + return linkedList; + } + private SingleLinkedNode getPredecessorNode(int index) { return getNode(index - 1); } diff --git a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java index c41289ed..664e4dfd 100644 --- a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java +++ b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java @@ -9,6 +9,7 @@ * @author: ramswaroop * @date: 6/20/15 * @time: 1:00 PM + * @see: http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/ */ public class CloneWithRandPointers> extends DoubleLinkedList { @@ -55,7 +56,6 @@ public static void main(String a[]) { linkedList.getNode(3).prev = linkedList.getNode(1); linkedList.printList(); DoubleLinkedList clonedList = clone(linkedList.getNode(0)); - clonedList.size = 4; clonedList.set(0, 234); clonedList.set(1, 567); clonedList.printList(); diff --git a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java b/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java new file mode 100644 index 00000000..29c6fcac --- /dev/null +++ b/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java @@ -0,0 +1,67 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 10:34 PM + */ +public class IntersectionOfTwoLists> extends SingleLinkedList { + + + public static > SingleLinkedNode getIntersectionNode(SingleLinkedList list1, + SingleLinkedList list2) { + + SingleLinkedNode curr1, curr2; + int diffLength = Math.abs(list1.size - list2.size); + + // forward the pointer in the longer list by their diff. in length + if (list1.size > list2.size) { + curr1 = list1.getNode(0); + curr2 = list2.getNode(0); + } else { + curr1 = list2.getNode(0); + curr2 = list1.getNode(0); + } + while (diffLength > 0) { + curr1 = curr1.next; + diffLength--; + } + + // now compare both lists node by node + while (curr1 != null) { + if (curr1 == curr2) return curr1; + curr1 = curr1.next; + curr2 = curr2.next; + } + + // lists do not intersect + return null; + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.add(66); + linkedList1.add(77); + linkedList1.add(88); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(56); + linkedList2.add(78); + linkedList2.add(45); + linkedList2.add(23); + linkedList2.getNode(3).next = linkedList1.getNode(5); // join 2 lists at some point + linkedList2.size = 8; // update size after joining + System.out.println(getIntersectionNode(linkedList1, linkedList2) != null ? + getIntersectionNode(linkedList1, linkedList2).item : "List don't intersect!"); + } +} From e984055c6d78d65838a0c8f065747ae118f1440b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 22 Jun 2015 17:33:04 +0530 Subject: [PATCH 120/417] printList in reverse done --- src/me/ramswaroop/linkedlists/ReverseList.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/ReverseList.java b/src/me/ramswaroop/linkedlists/ReverseList.java index 17ac4471..94a52a23 100644 --- a/src/me/ramswaroop/linkedlists/ReverseList.java +++ b/src/me/ramswaroop/linkedlists/ReverseList.java @@ -51,6 +51,23 @@ public SingleLinkedNode recursiveReverseList(SingleLinkedNode node) { return node; } + /** + * Recursive method to PRINT the linked list in reverse. + *

+ * NOTE: It doesn't reverse the linked list but just PRINTS + * them in reverse. + * + * @param node + * @param + */ + public static > void printListInReverse(SingleLinkedNode node) { + if (node == null) return; + + printListInReverse(node.next); + + System.out.print(node.item + ","); + } + public static void main(String a[]) { ReverseList linkedList = new ReverseList<>(); linkedList.add(11); @@ -63,5 +80,6 @@ public static void main(String a[]) { linkedList.printList(); linkedList.recursiveReverseList(linkedList.getNode(0)); linkedList.printList(); + printListInReverse(linkedList.getNode(0)); } } From 5cba5db950f70ff1894e91629200f24ab72b82d1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 22 Jun 2015 20:17:33 +0530 Subject: [PATCH 121/417] remove duplicates in sorted linked list done + code refactoring --- .../linkedlists/CloneWithRandPointers.java | 28 +++++++--- src/me/ramswaroop/linkedlists/DetectLoop.java | 9 ++-- .../ramswaroop/linkedlists/IsPalindrome.java | 11 ++-- src/me/ramswaroop/linkedlists/MiddleNode.java | 8 +-- .../linkedlists/NthNodeFromLast.java | 8 +-- .../linkedlists/RemoveDuplicates.java | 53 +++++++++++++++++++ 6 files changed, 93 insertions(+), 24 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/RemoveDuplicates.java diff --git a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java index 664e4dfd..a3cba37e 100644 --- a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java +++ b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java @@ -13,8 +13,17 @@ */ public class CloneWithRandPointers> extends DoubleLinkedList { - public static > DoubleLinkedList clone(DoubleLinkedNode node) { - DoubleLinkedNode curr = node; + /** + * Clones a linked list with next pointer pointing to the + * next node and prev pointer pointing to any random node. + * + * @param list + * @param + * @return + */ + public static > DoubleLinkedList clone(DoubleLinkedList list) { + DoubleLinkedNode firstNode = list.getNode(0); + DoubleLinkedNode curr = firstNode; // copy each node and insert after it while (curr != null) { @@ -24,16 +33,16 @@ public static > DoubleLinkedList clone(DoubleLinkedNo } // copy all random pointers from original node to the copied node - curr = node; + curr = firstNode; while (curr != null && curr.next != null) { curr.next.prev = (curr.prev != null) ? curr.prev.next : null; curr = curr.next.next; } // separate the copied nodes into a different linked list - curr = node; - DoubleLinkedNode cloneHead = node.next; - DoubleLinkedNode dupNode = cloneHead; + curr = firstNode; + DoubleLinkedNode cloneHead = firstNode.next; + DoubleLinkedNode dupNode; while (curr != null && curr.next != null) { dupNode = curr.next; curr.next = (dupNode != null) ? dupNode.next : null; @@ -54,11 +63,16 @@ public static void main(String a[]) { linkedList.getNode(1).prev = linkedList.getNode(2); linkedList.getNode(2).prev = linkedList.getNode(0); linkedList.getNode(3).prev = linkedList.getNode(1); + System.out.println("======Original======"); linkedList.printList(); - DoubleLinkedList clonedList = clone(linkedList.getNode(0)); + DoubleLinkedList clonedList = clone(linkedList); + System.out.println("======Cloned======"); + clonedList.printList(); + System.out.println("======Cloned (Modified)======"); clonedList.set(0, 234); clonedList.set(1, 567); clonedList.printList(); + System.out.println("======Original======"); linkedList.printList(); } } diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index 28d55bb6..e1a750db 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -27,11 +27,12 @@ public class DetectLoop> extends SingleLinkedList { * Time: O(n) * Space: O(1) * - * @param node + * @param list * @return */ - public static > boolean isLoopPresent(SingleLinkedNode node) { - SingleLinkedNode prev = node, curr = node; + public static > boolean isLoopPresent(SingleLinkedList list) { + SingleLinkedNode firstNode = list.getNode(0); + SingleLinkedNode prev = firstNode, curr = firstNode; while (curr != null && curr.next != null) { prev = prev.next; curr = curr.next.next; @@ -73,6 +74,6 @@ public static void main(String a[]) { linkedList.add(44); linkedList.add(55); linkedList.getNode(4).next = linkedList.getNode(3); - System.out.println(isLoopPresent(linkedList.getNode(0))); + System.out.println(isLoopPresent(linkedList)); } } diff --git a/src/me/ramswaroop/linkedlists/IsPalindrome.java b/src/me/ramswaroop/linkedlists/IsPalindrome.java index 2aed3858..d2ed1fa8 100644 --- a/src/me/ramswaroop/linkedlists/IsPalindrome.java +++ b/src/me/ramswaroop/linkedlists/IsPalindrome.java @@ -18,11 +18,12 @@ public class IsPalindrome> extends SingleLinkedList { * Uses Stack to test whether a linked list starting * from {@param node} is palindrome or not. * - * @param node + * @param list * @return */ - public static > boolean isPalindrome(SingleLinkedNode node) { - SingleLinkedNode curr = node; + public static > boolean isPalindrome(SingleLinkedList list) { + SingleLinkedNode head = list.getNode(0); + SingleLinkedNode curr = head; Stack> stack = new LinkedStack<>(); while (curr != null) { @@ -30,7 +31,7 @@ public static > boolean isPalindrome(SingleLinkedNode curr = curr.next; } - curr = node; + curr = head; while (curr != null) { if (curr.item != stack.pop().item) { @@ -72,7 +73,7 @@ public static void main(String a[]) { linkedList.add(11); linkedList.add(00); linkedList.printList(); - System.out.println(isPalindrome(linkedList.getNode(0))); + System.out.println(isPalindrome(linkedList)); linkedList.printList(); System.out.println(linkedList.isPalindromeRecursive(linkedList.getNode(0))); } diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java index eff6fd54..5f0f2d8e 100644 --- a/src/me/ramswaroop/linkedlists/MiddleNode.java +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -12,9 +12,9 @@ */ public class MiddleNode> extends SingleLinkedList { - public static > SingleLinkedNode getMiddleNode(SingleLinkedNode node) { - SingleLinkedNode slow = node; - SingleLinkedNode fast = node; + public static > SingleLinkedNode getMiddleNode(SingleLinkedList list) { + SingleLinkedNode slow = list.getNode(0); + SingleLinkedNode fast = list.getNode(0); while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; @@ -33,6 +33,6 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.add(88); - System.out.println(getMiddleNode(linkedList.getNode(0)).item); + System.out.println(getMiddleNode(linkedList).item); } } diff --git a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java index e07cb19c..64062092 100644 --- a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java +++ b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java @@ -12,9 +12,9 @@ */ public class NthNodeFromLast> extends SingleLinkedList { - public static > SingleLinkedNode getNthNodeFromLast(SingleLinkedNode node, int n) { - SingleLinkedNode slow = node; - SingleLinkedNode fast = node; + public static > SingleLinkedNode getNthNodeFromLast(SingleLinkedList list, int n) { + SingleLinkedNode slow = list.getNode(0); + SingleLinkedNode fast = list.getNode(0); // move the fast reference ahead of slow reference by 'n' nodes for (int i = 0; i < n; i++) { // assert length of linkedlist > n @@ -38,6 +38,6 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.add(88); - System.out.println(getNthNodeFromLast(linkedList.getNode(0), 3).item); + System.out.println(getNthNodeFromLast(linkedList, 3).item); } } diff --git a/src/me/ramswaroop/linkedlists/RemoveDuplicates.java b/src/me/ramswaroop/linkedlists/RemoveDuplicates.java new file mode 100644 index 00000000..e16e862c --- /dev/null +++ b/src/me/ramswaroop/linkedlists/RemoveDuplicates.java @@ -0,0 +1,53 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/18/15 + * @time: 2:35 PM + */ +public class RemoveDuplicates> extends SingleLinkedList { + + /** + * Removes duplicates in a sorted linked list + * by traversing it once. + * + * @param list + * @param + */ + public static > void removeDuplicates(SingleLinkedList list) { + SingleLinkedNode firstNode = list.getNode(0), curr = firstNode; + int index = 0; + while (curr != null) { + while (curr.next != null && curr.item == curr.next.item) { + list.remove(index + 1); + } + index++; + curr = curr.next; + } + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(00); + linkedList.add(00); + linkedList.add(11); + linkedList.add(11); + linkedList.add(22); + linkedList.add(22); + linkedList.add(22); + linkedList.add(22); + linkedList.add(33); + linkedList.add(33); + linkedList.add(33); + linkedList.add(33); + linkedList.printList(); + removeDuplicates(linkedList); + linkedList.printList(); + } +} From 3a6a28a1c9d965a1ab12d8b038325db613572753 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 22 Jun 2015 23:39:25 +0530 Subject: [PATCH 122/417] removes duplicates from an unsorted linked list --- .../linkedlists/RemoveDuplicates.java | 47 ++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/RemoveDuplicates.java b/src/me/ramswaroop/linkedlists/RemoveDuplicates.java index e16e862c..297ec8da 100644 --- a/src/me/ramswaroop/linkedlists/RemoveDuplicates.java +++ b/src/me/ramswaroop/linkedlists/RemoveDuplicates.java @@ -3,6 +3,9 @@ import me.ramswaroop.common.SingleLinkedList; import me.ramswaroop.common.SingleLinkedNode; +import java.util.HashMap; +import java.util.Map; + /** * Created by IntelliJ IDEA. * @@ -13,16 +16,17 @@ public class RemoveDuplicates> extends SingleLinkedList { /** - * Removes duplicates in a sorted linked list + * Removes duplicates from a sorted linked list * by traversing it once. * * @param list * @param */ public static > void removeDuplicates(SingleLinkedList list) { - SingleLinkedNode firstNode = list.getNode(0), curr = firstNode; + SingleLinkedNode curr = list.getNode(0); int index = 0; while (curr != null) { + // inner while loop for removing multiple duplicates while (curr.next != null && curr.item == curr.next.item) { list.remove(index + 1); } @@ -31,6 +35,31 @@ public static > void removeDuplicates(SingleLinkedList + * This method uses {@link java.util.HashMap}, another + * way is that you can sort it using merge sort and then + * call {@link #removeDuplicates}. + * + * @param list + * @param + */ + public static > void removeDuplicatesFromUnsortedList(SingleLinkedList list) { + SingleLinkedNode curr = list.getNode(0); + Map map = new HashMap<>(); + int index = 0; + while (curr != null) { + if (map.get(curr.item) == null) { + map.put(curr.item, true); + index++; + } else { + list.remove(index); + } + curr = curr.next; + } + } + public static void main(String a[]) { SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); @@ -49,5 +78,19 @@ public static void main(String a[]) { linkedList.printList(); removeDuplicates(linkedList); linkedList.printList(); + + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(00); + linkedList2.add(00); + linkedList2.add(22); + linkedList2.add(11); + linkedList2.add(44); + linkedList2.add(22); + linkedList2.add(66); + linkedList2.add(77); + linkedList2.add(66); + linkedList2.printList(); + removeDuplicatesFromUnsortedList(linkedList2); + linkedList2.printList(); } } From 5b048d1195efbd1e4f21d7378e35b7fe1ddc5045 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 23 Jun 2015 14:28:01 +0530 Subject: [PATCH 123/417] reverse double linked list done --- .../linkedlists/ReverseDoubleLinkedList.java | 50 +++++++++++++++++++ ...List.java => ReverseSingleLinkedList.java} | 16 +++--- 2 files changed, 58 insertions(+), 8 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java rename src/me/ramswaroop/linkedlists/{ReverseList.java => ReverseSingleLinkedList.java} (81%) diff --git a/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java b/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java new file mode 100644 index 00000000..32cd0ea9 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java @@ -0,0 +1,50 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.DoubleLinkedList; +import me.ramswaroop.common.DoubleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/19/15 + * @time: 9:24 AM + */ +public class ReverseDoubleLinkedList> extends DoubleLinkedList { + + /** + * Reverses the doubly linked list. + * + * @param list + */ + public static > void reverseList(DoubleLinkedList list) { + + DoubleLinkedNode curr = list.getNode(0); + DoubleLinkedNode temp = curr; + + while (curr != null) { + temp = curr.prev; + curr.prev = curr.next; + curr.next = temp; + curr = curr.prev; + } + + // temp will be null if linked list has only one node + if (temp != null) { + list.head = temp.prev; + } + } + + public static void main(String a[]) { + DoubleLinkedList linkedList = new DoubleLinkedList<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.printList(); + reverseList(linkedList); + linkedList.printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/ReverseList.java b/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java similarity index 81% rename from src/me/ramswaroop/linkedlists/ReverseList.java rename to src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java index 94a52a23..c2a6911d 100644 --- a/src/me/ramswaroop/linkedlists/ReverseList.java +++ b/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java @@ -10,16 +10,16 @@ * @date: 6/19/15 * @time: 9:24 AM */ -public class ReverseList> extends SingleLinkedList { +public class ReverseSingleLinkedList> extends SingleLinkedList { /** * Reverses the linked list using 3 references prev, curr and next. * - * @param node + * @param list */ - public void reverseList(SingleLinkedNode node) { - SingleLinkedNode prev = node; - SingleLinkedNode curr = node.next; + public static > void reverseList(SingleLinkedList list) { + SingleLinkedNode prev = list.getNode(0); + SingleLinkedNode curr = prev.next; prev.next = null; // this will be the last node after reversal, so make next of node = null while (curr != null) { SingleLinkedNode next = curr.next; @@ -27,7 +27,7 @@ public void reverseList(SingleLinkedNode node) { prev = curr; curr = next; } - head = prev; + list.head = prev; } /** @@ -69,14 +69,14 @@ public static > void printListInReverse(SingleLinkedNode } public static void main(String a[]) { - ReverseList linkedList = new ReverseList<>(); + ReverseSingleLinkedList linkedList = new ReverseSingleLinkedList<>(); linkedList.add(11); linkedList.add(22); linkedList.add(33); linkedList.add(44); linkedList.add(55); linkedList.printList(); - linkedList.reverseList(linkedList.getNode(0)); + reverseList(linkedList); linkedList.printList(); linkedList.recursiveReverseList(linkedList.getNode(0)); linkedList.printList(); From 0ecdc0cffc4d8a487f0d3c399c47a613993c90b0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 23 Jun 2015 17:38:24 +0530 Subject: [PATCH 124/417] circular linked list done + code refactoring --- src/me/ramswaroop/Main.java | 76 ++++- .../common/CircularSingleLinkedList.java | 293 ++++++++++++++++++ .../ramswaroop/common/SingleLinkedList.java | 2 +- 3 files changed, 369 insertions(+), 2 deletions(-) create mode 100644 src/me/ramswaroop/common/CircularSingleLinkedList.java diff --git a/src/me/ramswaroop/Main.java b/src/me/ramswaroop/Main.java index 4f35c6bb..a749125c 100644 --- a/src/me/ramswaroop/Main.java +++ b/src/me/ramswaroop/Main.java @@ -15,6 +15,7 @@ public static void main(String[] args) { Queue queue = new LinkedQueue<>(); LinkedList singleLinkedList = new SingleLinkedList<>(); LinkedList doubleLinkedList = new DoubleLinkedList<>(); + LinkedList circularSingleLinkedList = new CircularSingleLinkedList<>(); chooseModule: while (true) { out.println("Choose module:"); @@ -23,7 +24,9 @@ public static void main(String[] args) { out.println("2. Queue"); out.println("3. SingleLinkedList"); out.println("4. DoubleLinkedList"); - out.println("5. Exit"); + out.println("5. CircularSingleLinkedList"); + out.println("6. CircularDoubleLinkedList"); + out.println("7. Exit"); k1 = Integer.parseInt(in.nextLine()); switch (k1) { case 1: @@ -231,6 +234,77 @@ public static void main(String[] args) { } } case 5: + while (true) { + out.println("Select operation:"); + out.println("================="); + out.println("1. Add"); + out.println("2. Add at index"); + out.println("3. Remove"); + out.println("4. Remove at index"); + out.println("5. Remove item"); + out.println("6. Edit item"); + out.println("7. Delete LinkedList"); + out.println("8. Print"); + out.println("9. Exit module"); + k2 = Integer.parseInt(in.nextLine()); + int item, index; + switch (k2) { + case 1: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + circularSingleLinkedList.add(item); + circularSingleLinkedList.printList(); + break; + case 2: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + out.println("Enter index:"); + index = Integer.parseInt(in.nextLine()); + circularSingleLinkedList.add(index, item); + circularSingleLinkedList.printList(); + break; + case 3: + out.println("Removed element: " + circularSingleLinkedList.remove()); + circularSingleLinkedList.printList(); + break; + case 4: + out.println("Enter index:"); + index = Integer.parseInt(in.nextLine()); + out.println("Removed element: " + circularSingleLinkedList.remove(index)); + circularSingleLinkedList.printList(); + break; + case 5: + out.println("Enter value:"); + item = Integer.parseInt(in.nextLine()); + out.println("Removed: " + circularSingleLinkedList.removeItem(item)); + circularSingleLinkedList.printList(); + break; + case 6: + out.println("Enter index to edit:"); + index = Integer.parseInt(in.nextLine()); + out.println("Enter new value:"); + item = Integer.parseInt(in.nextLine()); + circularSingleLinkedList.set(index, item); + circularSingleLinkedList.printList(); + break; + case 7: + circularSingleLinkedList.clear(); + out.println("LinkedList deleted."); + circularSingleLinkedList.printList(); + break; + case 8: + circularSingleLinkedList.printList(); + break; + case 9: + continue chooseModule; + default: + out.println("Wrong choice!"); + } + } + case 6: + out.println("Yet to be developed!"); + break; + case 7: out.println("Exiting..."); System.exit(0); default: diff --git a/src/me/ramswaroop/common/CircularSingleLinkedList.java b/src/me/ramswaroop/common/CircularSingleLinkedList.java new file mode 100644 index 00000000..4e4e3723 --- /dev/null +++ b/src/me/ramswaroop/common/CircularSingleLinkedList.java @@ -0,0 +1,293 @@ +package me.ramswaroop.common; + +import java.util.NoSuchElementException; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/16/15 + * @time: 1:00 PM + */ +public class CircularSingleLinkedList> implements LinkedList { + + public SingleLinkedNode head; + public int size; + + @Override + public boolean add(E item) { + SingleLinkedNode newNode = new SingleLinkedNode<>(item, head); + if (head == null) { // list empty + head = newNode; + newNode.next = head; + } else { // add to the end of list + SingleLinkedNode curr = head; + while (curr.next != head) { + curr = curr.next; + } + curr.next = newNode; + } + size++; + return true; + } + + @Override + public boolean add(int index, E item) { + isPositionIndex(index); + + if (index == 0) { // add at first + addFirst(item); + } else { // add at any other location + SingleLinkedNode nodeAtPrevIndex = getPredecessorNode(index); + SingleLinkedNode newNode = new SingleLinkedNode<>(item, nodeAtPrevIndex.next); + nodeAtPrevIndex.next = newNode; + size++; + } + return true; + } + + @Override + public void addFirst(E item) { + SingleLinkedNode newNode = new SingleLinkedNode<>(item, head), node; + if (head == null) { // empty linked list + newNode.next = newNode; + } else { + node = getNode(size - 1); + node.next = newNode; + } + head = newNode; + size++; + } + + @Override + public void addLast(E item) { + add(item); + } + + @Override + public void clear() { + // Clearing all of the links between nodes is "unnecessary", but: + // - helps a generational GC if the discarded nodes inhabit + // more than one generation + // - is sure to free memory even if there is a reachable Iterator + for (SingleLinkedNode node = head; node != null; ) { + SingleLinkedNode next = node.next; + node.item = null; + node.next = null; + node = next; + } + head = null; + size = 0; + } + + @Override + public LinkedList clone() { + return null; + } + + @Override + public boolean contains(E item) { + return getNode(item) != null; + } + + @Override + public E get(int index) { + return getNode(index).item; + } + + @Override + public E getFirst() { + isLinkedListEmpty(); + return head.item; + } + + @Override + public E getLast() { + return getNode(size - 1).item; + } + + @Override + public E remove() { + isLinkedListEmpty(); + + E item = head.item; + // last node should point to new head + SingleLinkedNode lastNode = getNode(size - 1); + lastNode.next = head.next; + head = (head.next != head) ? head.next : null; + size--; + return item; + } + + @Override + public E remove(int index) { + isLinkedListEmpty(); + + SingleLinkedNode prevNode = getPredecessorNode(index), + delNode, + lastNode; + if (prevNode == null) { // index = 0 + delNode = head; + head = (head.next != head) ? head.next : null; + size--; + return delNode.item; + } else { + delNode = prevNode.next; + prevNode.next = delNode.next; + // last node should point to new head + lastNode = getNode(size - 1); + lastNode.next = head.next; + head = head.next; + size--; + return delNode.item; + } + } + + @Override + public boolean removeItem(E item) { + isLinkedListEmpty(); + + if (!contains(item)) return false; + + SingleLinkedNode prevNode = getPredecessorNode(item), + lastNode; + if (prevNode == null) { // index = 0 + head = (head.next != head) ? head.next : null; + size--; + } else { + prevNode.next = prevNode.next.next; + // last node should point to new head + lastNode = getNode(size - 1); + lastNode.next = head.next; + head = head.next; + size--; + } + return true; + } + + @Override + public E set(int index, E item) { + SingleLinkedNode node = getNode(index); + node.item = item; + return node.item; + } + + @Override + public int size() { + return size; + } + + @Override + public void printList() { + SingleLinkedNode curr = head; + out.print("["); + if (curr == null) { + out.println("]"); + return; + } + while (curr.next != head) { + out.print(curr.item + ","); + curr = curr.next; + } + out.println(curr.item + "]"); + } + + public static > CircularSingleLinkedList getLinkedList(SingleLinkedNode node) { + CircularSingleLinkedList linkedList = new CircularSingleLinkedList<>(); + // set head + linkedList.head = node; + // set size + SingleLinkedNode curr = node; + while (curr != linkedList.head) { + linkedList.size++; + curr = curr.next; + } + return linkedList; + } + + private SingleLinkedNode getPredecessorNode(int index) { + return index > 0 ? getNode(index - 1) : null; + } + + private SingleLinkedNode getPredecessorNode(E item) { + SingleLinkedNode prev = null; + SingleLinkedNode curr = head; + if (item == null) { + while (curr != head) { + if (curr.item == item) { // when item is null, use == rather than equals() + return prev; + } + prev = curr; + curr = curr.next; + } + } else { + while (curr != head) { + if (curr.item.equals(item)) { + return prev; + } + prev = curr; + curr = curr.next; + } + } + return null; + } + + public SingleLinkedNode getNode(int index) { + isElementIndex(index); + + SingleLinkedNode curr = head; + int i = 0; + while (i < index) { + curr = curr.next; + i++; + } + return curr; + } + + public SingleLinkedNode getNode(E item) { + SingleLinkedNode curr = head; + if (item == null) { + while (curr != head) { // when item is null, use == rather than equals() + if (curr.item == item) { + return curr; + } + curr = curr.next; + } + } else { + while (curr != head) { + if (curr.item.equals(item)) { + return curr; + } + curr = curr.next; + } + } + return null; + } + + private void isLinkedListEmpty() { + if (head == null) { + throw new NoSuchElementException("LinkedList empty"); + } + } + + /** + * Tells if the argument is the index of an existing element. + */ + private void isElementIndex(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException("Index [" + index + "] must be less than size [" + size + "]"); + } + } + + /** + * Tells if the argument is the index of a valid position for an + * iterator or an add operation. + */ + private void isPositionIndex(int index) { + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException("Index [" + index + "] must be less than or equal to size [" + size + "]"); + } + } +} diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index b530c7e4..ba5e4a51 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -188,7 +188,7 @@ public static > SingleLinkedList getLinkedList(Single } private SingleLinkedNode getPredecessorNode(int index) { - return getNode(index - 1); + return index > 0 ? getNode(index - 1) : null; } private SingleLinkedNode getPredecessorNode(E item) { From ddecef4cf5897420b4b72a1fb703a7464c82e2e2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 23 Jun 2015 18:22:33 +0530 Subject: [PATCH 125/417] divide a single circular linked list into two halves --- .../DivideCircularListIntoTwo.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java diff --git a/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java b/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java new file mode 100644 index 00000000..1da6fe8e --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java @@ -0,0 +1,37 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.CircularSingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/23/15 + * @time: 6:01 PM + */ +public class DivideCircularListIntoTwo> extends CircularSingleLinkedList { + + public static > CircularSingleLinkedList[] divideIntoTwoHalves(CircularSingleLinkedList list) { + SingleLinkedNode middleNode = list.getNode(list.size >> 1), + lastNode = list.getNode(list.size - 1), + secondHead = middleNode.next; + + lastNode.next = middleNode.next; + middleNode.next = list.head; + + return new CircularSingleLinkedList[]{getLinkedList(list.head), getLinkedList(secondHead)}; + } + + public static void main(String a[]) { + CircularSingleLinkedList linkedList = new CircularSingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + CircularSingleLinkedList linkedLists[] = divideIntoTwoHalves(linkedList); + linkedLists[0].printList(); + linkedLists[1].printList(); + } +} From 2f71ec1b1e4dfb877a9579765ff05bebda546887 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 23 Jun 2015 19:51:48 +0530 Subject: [PATCH 126/417] minor fix --- src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java b/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java index 1da6fe8e..d7eeca8a 100644 --- a/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java +++ b/src/me/ramswaroop/linkedlists/DivideCircularListIntoTwo.java @@ -13,11 +13,12 @@ public class DivideCircularListIntoTwo> extends CircularSingleLinkedList { public static > CircularSingleLinkedList[] divideIntoTwoHalves(CircularSingleLinkedList list) { - SingleLinkedNode middleNode = list.getNode(list.size >> 1), + SingleLinkedNode middleNode = list.getNode(list.size - 1 >> 1), lastNode = list.getNode(list.size - 1), secondHead = middleNode.next; - + // make the 2nd half circular first lastNode.next = middleNode.next; + // then make the 1st half circular middleNode.next = list.head; return new CircularSingleLinkedList[]{getLinkedList(list.head), getLinkedList(secondHead)}; From 779a0f7d068397d1dd36ebcaa9ae351bfaf69afd Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 23 Jun 2015 20:01:15 +0530 Subject: [PATCH 127/417] move last node to first: done --- .../linkedlists/MoveLastNodeToFirst.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java diff --git a/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java b/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java new file mode 100644 index 00000000..fe6c07ad --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java @@ -0,0 +1,38 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/23/15 + * @time: 7:52 PM + */ +public class MoveLastNodeToFirst> extends SingleLinkedList { + + public static > void moveLastNodeToFirst(SingleLinkedList list) { + if (list.size <= 1) return; + + SingleLinkedNode curr = list.getNode(0), prev = curr; + while (curr.next != null) { + prev = curr; + curr = curr.next; + } + prev.next = null; + curr.next = list.head; + list.head = curr; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.printList(); + moveLastNodeToFirst(linkedList); + linkedList.printList(); + } +} From f280044dd0d867155f8586cf0dde0dfd12f30fdd Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 24 Jun 2015 12:38:58 +0530 Subject: [PATCH 128/417] next lower power of 2: done --- src/me/ramswaroop/bits/NextPowerOf2.java | 87 +++++++++++++++++------- 1 file changed, 62 insertions(+), 25 deletions(-) diff --git a/src/me/ramswaroop/bits/NextPowerOf2.java b/src/me/ramswaroop/bits/NextPowerOf2.java index 2ed695c5..1002f2a8 100644 --- a/src/me/ramswaroop/bits/NextPowerOf2.java +++ b/src/me/ramswaroop/bits/NextPowerOf2.java @@ -9,15 +9,18 @@ */ public class NextPowerOf2 { - /** + * Returns a power of 2 number which is larger + * than {@param n} but if {@param n} is already + * a power of 2 then it simply returns it. + *

* Left shifts 1 number of times equal to the * leftmost set bit position in n. * * @param n * @return */ - public static long nextPowerOf2(long n) { + public static long nextHigherPowerOf2(long n) { // if n is already a power of 2 then return n if (n != 0 && ((n & (n - 1)) == 0)) return n; @@ -29,13 +32,17 @@ public static long nextPowerOf2(long n) { } /** + * Returns a power of 2 number which is larger + * than {@param n} but if {@param n} is already + * a power of 2 then it simply returns it. + *

* Finds the leftmost set bit position and * left shifts 1 that many times. * * @param n * @return */ - public static long nextPowerOf2_V2(long n) { + public static long nextHigherPowerOf2_V2(long n) { // if n is already a power of 2 then return n if (n != 0 && ((n & (n - 1)) == 0)) return n; @@ -50,13 +57,17 @@ public static long nextPowerOf2_V2(long n) { } /** + * Returns a power of 2 number which is larger + * than {@param n} but if {@param n} is already + * a power of 2 then it simply returns it. + *

* Finds the leftmost set bit position and * left shifts 1 that many times. * * @param n * @return */ - public static long nextPowerOf2_V1(long n) { + public static long nextHigherPowerOf2_V1(long n) { if (PowerOf2.isPowerOf2(n)) { return n; } @@ -73,34 +84,60 @@ public static long nextPowerOf2_V1(long n) { return 1 << c; } + + /** + * Returns a power of 2 number which is smaller + * than {@param n}. + * + * @param n + * @return + */ + public static long nextLowerPowerOf2(long n) { + long p = 1; + while (p < n) { + p <<= 1; + } + return (n > 1) ? p >> 1 : n; // check for n = 0 or 1; + } + public static void main(String a[]) { - System.out.println(nextPowerOf2(2)); - System.out.println(nextPowerOf2(3)); - System.out.println(nextPowerOf2(18)); - System.out.println(nextPowerOf2(6)); - System.out.println(nextPowerOf2(7)); - System.out.println(nextPowerOf2(1)); - System.out.println(nextPowerOf2(0)); + System.out.println(nextHigherPowerOf2(2)); + System.out.println(nextHigherPowerOf2(3)); + System.out.println(nextHigherPowerOf2(18)); + System.out.println(nextHigherPowerOf2(6)); + System.out.println(nextHigherPowerOf2(7)); + System.out.println(nextHigherPowerOf2(1)); + System.out.println(nextHigherPowerOf2(0)); + + System.out.println("================="); + + System.out.println(nextHigherPowerOf2_V2(2)); + System.out.println(nextHigherPowerOf2_V2(3)); + System.out.println(nextHigherPowerOf2_V2(18)); + System.out.println(nextHigherPowerOf2_V2(6)); + System.out.println(nextHigherPowerOf2_V2(7)); + System.out.println(nextHigherPowerOf2_V2(1)); + System.out.println(nextHigherPowerOf2_V2(0)); System.out.println("================="); - System.out.println(nextPowerOf2_V2(2)); - System.out.println(nextPowerOf2_V2(3)); - System.out.println(nextPowerOf2_V2(18)); - System.out.println(nextPowerOf2_V2(6)); - System.out.println(nextPowerOf2_V2(7)); - System.out.println(nextPowerOf2_V2(1)); - System.out.println(nextPowerOf2_V2(0)); + System.out.println(nextHigherPowerOf2_V1(2)); + System.out.println(nextHigherPowerOf2_V1(3)); + System.out.println(nextHigherPowerOf2_V1(18)); + System.out.println(nextHigherPowerOf2_V1(6)); + System.out.println(nextHigherPowerOf2_V1(7)); + System.out.println(nextHigherPowerOf2_V1(1)); + System.out.println(nextHigherPowerOf2_V1(0)); System.out.println("================="); - System.out.println(nextPowerOf2_V1(2)); - System.out.println(nextPowerOf2_V1(3)); - System.out.println(nextPowerOf2_V1(18)); - System.out.println(nextPowerOf2_V1(6)); - System.out.println(nextPowerOf2_V1(7)); - System.out.println(nextPowerOf2_V1(1)); - System.out.println(nextPowerOf2_V1(0)); + System.out.println(nextLowerPowerOf2(2)); + System.out.println(nextLowerPowerOf2(3)); + System.out.println(nextLowerPowerOf2(18)); + System.out.println(nextLowerPowerOf2(6)); + System.out.println(nextLowerPowerOf2(7)); + System.out.println(nextLowerPowerOf2(1)); + System.out.println(nextLowerPowerOf2(0)); } } From e88a8ae9a30a7ce66e676224635655b7efc66dfc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 24 Jun 2015 22:40:24 +0530 Subject: [PATCH 129/417] count set bits for -ve nos: done --- src/me/ramswaroop/bits/CountSetBits.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/bits/CountSetBits.java b/src/me/ramswaroop/bits/CountSetBits.java index c1f607b1..21f9d541 100644 --- a/src/me/ramswaroop/bits/CountSetBits.java +++ b/src/me/ramswaroop/bits/CountSetBits.java @@ -12,7 +12,7 @@ public class CountSetBits { /** - * Unoptimized version. + * Unoptimized version. Works for -ve numbers as well. * * @param number * @return @@ -29,7 +29,7 @@ static int countSetBits(int number) { } /** - * Optimized version. + * Optimized version. Works for -ve numbers as well. * * Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset * in each iteration. The time complexity is proportional to the number of bits set. @@ -42,7 +42,7 @@ static int countSetBits(int number) { */ static int countSetBits(long n) { int count = 0; - while (n > 0) { + while (n != 0) { n &= n - 1; // right most set bit in n is unset count++; } From f5b1049f175f7305497e9355ffc426e84beac3ac Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 25 Jun 2015 10:05:33 +0530 Subject: [PATCH 130/417] rightmost setbit workable for -ve nos: done --- src/me/ramswaroop/bits/RightmostSetBit.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/RightmostSetBit.java b/src/me/ramswaroop/bits/RightmostSetBit.java index f2ae79b7..73757c3b 100644 --- a/src/me/ramswaroop/bits/RightmostSetBit.java +++ b/src/me/ramswaroop/bits/RightmostSetBit.java @@ -9,9 +9,18 @@ */ public class RightmostSetBit { + /** + * Returns the position of the rightmost set bit + * in {@param n} where the position starts from 1. + *

+ * Works for -ve no.s as well. + * + * @param n + * @return + */ public static int getRightmostSetBitPosition(long n) { int position = 0; - while (n > 0) { + while (n != 0) { position++; if ((n & 1) == 1) { break; @@ -22,7 +31,7 @@ public static int getRightmostSetBitPosition(long n) { } public static long unsetRightmostSetBit(long n) { - return n & (n - 1); + return n & (n - 1); // brian kerningham's algorithm } public static void main(String a[]) { @@ -32,6 +41,9 @@ public static void main(String a[]) { System.out.println(getRightmostSetBitPosition(5)); System.out.println(getRightmostSetBitPosition(18)); System.out.println(getRightmostSetBitPosition(19)); + System.out.println(getRightmostSetBitPosition(-1)); + System.out.println(getRightmostSetBitPosition(-2)); + System.out.println(getRightmostSetBitPosition(-4)); System.out.println("========================"); From 35c9685fcdfb7d85fbe7d3fa728773afc04c266b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 25 Jun 2015 12:21:11 +0530 Subject: [PATCH 131/417] Update README.md --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index b188aef4..1edcaa3a 100644 --- a/README.md +++ b/README.md @@ -1 +1,13 @@ # Algorithms and Data Structures in Java + +The repo consists of solutions to various problems invloving different data structures and algorithms. All solutions are coded in Java. + +## Environment + +### IDE +IntelliJ IDEA 14 + +### Machine +MacBook Pro +2.6 GHz Intel Core i5 +8 GB 1600 MHz DDR3 From df51cd4851e499ce84dc9091653b33e3305f3298 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 16:29:05 +0530 Subject: [PATCH 132/417] pair wise swap: done --- .../ramswaroop/linkedlists/PairWiseSwap.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/PairWiseSwap.java diff --git a/src/me/ramswaroop/linkedlists/PairWiseSwap.java b/src/me/ramswaroop/linkedlists/PairWiseSwap.java new file mode 100644 index 00000000..bc8462fb --- /dev/null +++ b/src/me/ramswaroop/linkedlists/PairWiseSwap.java @@ -0,0 +1,61 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/24/15 + * @time: 3:48 PM + */ +public class PairWiseSwap> extends SingleLinkedList { + + /** + * Recursively swaps adjacent nodes of a linked list. + * The swapping is done in place. + * + * @param node + */ + public void pairWiseSwap(SingleLinkedNode node) { + if (node == null || node.next == null) return; + + // the trick is to swap the next two nodes of {@param node} + // but if {@param node} is head then swap itself with the next node + SingleLinkedNode firstNode = (node == head) ? node : node.next, + secondNode = (node == head) ? node.next : node.next.next; + + if (firstNode == null || secondNode == null) return; + + firstNode.next = secondNode.next; + secondNode.next = firstNode; + + if (node == head) { + head = secondNode; + } else { + node.next = secondNode; + } + + // pass firstNode as the next two nodes are swapped + pairWiseSwap(firstNode); + } + + public void pairWiseSwap() { + pairWiseSwap(head); + } + + public static void main(String a[]) { + PairWiseSwap linkedList = new PairWiseSwap<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.printList(); + linkedList.pairWiseSwap(); + linkedList.printList(); + } +} \ No newline at end of file From dd6896336ac3ba69feb17870ff79b1eb5fe4dbe2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 16:32:13 +0530 Subject: [PATCH 133/417] updated readme --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 1edcaa3a..952ff262 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,11 @@ The repo consists of solutions to various problems invloving different data stru ## Environment +### Java Version +Java version 1.7.0_51 +Java(TM) SE Runtime Environment (build 1.7.0_51-b13) +Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode) + ### IDE IntelliJ IDEA 14 From 1edfb03962748aa2d3306558b308e66e1b407a91 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 16:33:28 +0530 Subject: [PATCH 134/417] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 952ff262..f22212d9 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ The repo consists of solutions to various problems invloving different data stru ## Environment ### Java Version -Java version 1.7.0_51 -Java(TM) SE Runtime Environment (build 1.7.0_51-b13) -Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode) +Java version 1.7.0_51 +Java(TM) SE Runtime Environment (build 1.7.0_51-b13) +Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode) ### IDE IntelliJ IDEA 14 From c5cd23cc452c46c606a016383eb159b08b80dd52 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 16:36:19 +0530 Subject: [PATCH 135/417] added eclipse template --- .gitignore | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/.gitignore b/.gitignore index 8aebf097..b9284dea 100644 --- a/.gitignore +++ b/.gitignore @@ -63,3 +63,43 @@ crashlytics.properties crashlytics-build.properties + +### Eclipse template +*.pydevproject +.metadata +.gradle +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath + +# Eclipse Core +.project + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# PDT-specific +.buildpath + +# sbteclipse plugin +.target + +# TeXlipse plugin +.texlipse + + From 77f34a31db7f650fc18abee8118e4765ea3c241d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 18:19:51 +0530 Subject: [PATCH 136/417] code refactoring --- .../ramswaroop/{trees => common}/AVLTree.java | 2 +- .../{trees => common}/BinarySearchTree.java | 64 +--- .../{trees => common}/BinaryTree.java | 274 +----------------- src/me/ramswaroop/{trees => common}/Tree.java | 2 +- src/me/ramswaroop/trees/DoubleTree.java | 51 ++++ src/me/ramswaroop/trees/IdenticalTrees.java | 60 ++++ src/me/ramswaroop/trees/LeafNodes.java | 44 +++ src/me/ramswaroop/trees/RootToLeafPaths.java | 122 ++++++++ src/me/ramswaroop/trees/SpiralTraversal.java | 115 ++++++++ src/me/ramswaroop/trees/TreeToList.java | 74 +++++ 10 files changed, 474 insertions(+), 334 deletions(-) rename src/me/ramswaroop/{trees => common}/AVLTree.java (84%) rename src/me/ramswaroop/{trees => common}/BinarySearchTree.java (72%) rename src/me/ramswaroop/{trees => common}/BinaryTree.java (66%) rename src/me/ramswaroop/{trees => common}/Tree.java (88%) create mode 100644 src/me/ramswaroop/trees/DoubleTree.java create mode 100644 src/me/ramswaroop/trees/IdenticalTrees.java create mode 100644 src/me/ramswaroop/trees/LeafNodes.java create mode 100644 src/me/ramswaroop/trees/RootToLeafPaths.java create mode 100644 src/me/ramswaroop/trees/SpiralTraversal.java create mode 100644 src/me/ramswaroop/trees/TreeToList.java diff --git a/src/me/ramswaroop/trees/AVLTree.java b/src/me/ramswaroop/common/AVLTree.java similarity index 84% rename from src/me/ramswaroop/trees/AVLTree.java rename to src/me/ramswaroop/common/AVLTree.java index 1ac6e505..b995d78f 100644 --- a/src/me/ramswaroop/trees/AVLTree.java +++ b/src/me/ramswaroop/common/AVLTree.java @@ -1,4 +1,4 @@ -package me.ramswaroop.trees; +package me.ramswaroop.common; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/trees/BinarySearchTree.java b/src/me/ramswaroop/common/BinarySearchTree.java similarity index 72% rename from src/me/ramswaroop/trees/BinarySearchTree.java rename to src/me/ramswaroop/common/BinarySearchTree.java index 33210f64..eab0dc10 100644 --- a/src/me/ramswaroop/trees/BinarySearchTree.java +++ b/src/me/ramswaroop/common/BinarySearchTree.java @@ -1,6 +1,4 @@ -package me.ramswaroop.trees; - -import me.ramswaroop.common.BinaryNode; +package me.ramswaroop.common; import java.util.NoSuchElementException; @@ -45,8 +43,6 @@ public static void main(String[] a) { out.println(""); bst.postOrder(); out.println("\n" + bst.size()); - out.println(BinaryTree.isIdentical(bst.root.right, bst.root.right)); - out.println(bst.isIdentical(bst.root)); out.println(bst.height()); /*obj.delete(); out.println("After deletion: "); @@ -56,15 +52,12 @@ public static void main(String[] a) { /*out.println("\nAfter mirroring: "); obj.mirror(); obj.inOrder();*/ - out.println("\nRoot to leafs: "); - bst.rootToLeafPaths(); out.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); out.println("Min: " + bst.min().value); out.println("BFT: "); bst.breadthFirstTraversal(); out.println("\nBFT using queue: "); bst.breadthFirstTraversalUsingQueue(); - out.println("\nNo. of leaf nodes: " + bst.countLeafNodes()); out.println("Is BST: " + bst.isBST()); /*out.print("Tree to list: "); bst.treeToList();*/ @@ -157,60 +150,7 @@ public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) } } - - /** - * A recursive function that takes an ordered binary tree - * and rearranges the internal pointers to make a circular - * doubly linked list out of the tree nodes. The list should - * be arranged so that the nodes are in increasing order. - */ - public void treeToList() { - // print the list - printList(treeToList(root)); - } - - public BinaryNode treeToList(BinaryNode node) { - if (node == null) return null; - - BinaryNode aList = treeToList(node.left); - BinaryNode bList = treeToList(node.right); - - node.left = node; - node.right = node; - - // attach left child then root followed by right child (so that final list is in ascending order) - aList = addToList(aList, node); - aList = addToList(aList, bList); - - return aList; - } - - private BinaryNode addToList(BinaryNode aList, BinaryNode bList) { - - if (aList == null) return bList; - if (bList == null) return aList; - - // find the last node in each list - BinaryNode aListLast = aList.left; - BinaryNode bListLast = bList.left; - - // join end of one list to beginning of another - aListLast.right = bList; - bList.left = aListLast; - - // make circular - aListLast.left = bListLast; - bListLast.right = aList; - - return aList; - } - - - /** - * Utility methods. - */ - - private void printList(BinaryNode node) { + public void printList(BinaryNode node) { BinaryNode current = node; out.print("["); if (current == null) { diff --git a/src/me/ramswaroop/trees/BinaryTree.java b/src/me/ramswaroop/common/BinaryTree.java similarity index 66% rename from src/me/ramswaroop/trees/BinaryTree.java rename to src/me/ramswaroop/common/BinaryTree.java index 90fe6b00..7c7bb41b 100644 --- a/src/me/ramswaroop/trees/BinaryTree.java +++ b/src/me/ramswaroop/common/BinaryTree.java @@ -1,9 +1,5 @@ -package me.ramswaroop.trees; +package me.ramswaroop.common; -import me.ramswaroop.common.*; - -import java.util.ArrayList; -import java.util.EmptyStackException; import java.util.List; import java.util.NoSuchElementException; @@ -18,7 +14,7 @@ */ public class BinaryTree> extends Tree { - BinaryNode root; + public BinaryNode root; Queue> queue = new LinkedQueue<>(); // needed for insertion public static void main(String[] a) { @@ -32,8 +28,6 @@ public static void main(String[] a) { binaryTree.put(7);*/ out.print("Breadth-first Traversal: "); binaryTree.breadthFirstTraversal(); - out.print("\nSpiral Traversal: "); - binaryTree.spiralTraversal(); out.print("\nIn order traversal: "); binaryTree.inOrder(); out.print("\nIn order traversal without stack: "); @@ -46,9 +40,7 @@ public static void main(String[] a) { binaryTree.breadthFirstTraversal();*/ out.print("\nIs height balanced: " + binaryTree.isHeightBalanced()); out.print("\nDiameter: " + binaryTree.diameter()); - out.print("\nRoot to Leaf Sum: " + binaryTree.rootToLeafPathsSum(binaryTree.root, new ArrayList(), 13)); - out.print("\nBFS after Double tree: "); - binaryTree.doubleTree(); + binaryTree.breadthFirstTraversalUsingQueue(); out.print("\nIn order traversal: "); binaryTree.inOrder(); @@ -278,97 +270,6 @@ public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue node, int level) { - if (node == null) return; - - // print the starting node - if (level == 0) printValue(node); - - // print the neighbour nodes - if (level % 2 == 0) { - printValue(node.left); - printValue(node.right); - } else { - printValue(node.right); - printValue(node.left); - } - - // go to next level - level++; - if (level % 2 == 0) { - spiralTraversal(node.left, level); - spiralTraversal(node.right, level); - } else { - spiralTraversal(node.right, level); - spiralTraversal(node.left, level); - } - } - - public void spiralTraversalUsingStacks(BinaryNode node) { - Stack> stack1 = new LinkedStack<>(); // for nodes to be printed ltr - Stack> stack2 = new LinkedStack<>(); // for nodes to be printed rtl - - printValue(node); - - stack1.push(node.right); - stack1.push(node.left); - - // pop stack1 and push their child nodes in stack2 - while (!stack1.isEmpty()) { - - BinaryNode leftChild = stack1.pop(); - BinaryNode rightChild = stack1.pop(); - - printValue(leftChild); - printValue(rightChild); - - try { - if (leftChild != null) stack2.push(leftChild.left); - if (leftChild != null) stack2.push(leftChild.right); - if (rightChild != null) stack2.push(rightChild.left); - if (rightChild != null) stack2.push(rightChild.right); - } catch (EmptyStackException e) { - // ignore error when stack empty - } - } - - // pop stack2 and push their child nodes in stack1 - while (!stack2.isEmpty()) { - - BinaryNode rightChild = stack2.pop(); - BinaryNode leftChild = stack2.pop(); - - printValue(rightChild); - printValue(leftChild); - - try { - if (rightChild != null) stack1.push(rightChild.right); - if (rightChild != null) stack1.push(rightChild.left); - if (leftChild != null) stack1.push(leftChild.right); - if (leftChild != null) stack1.push(leftChild.left); - } catch (EmptyStackException e) { - // ignore error when stack empty - } - } - } - - - public void constructTreeWithInOrderAndPreOrder(List> inOrder, List> preOrder) { - for (int i = 0; i < preOrder.size(); i++) { - - } - } - - /** * Deletes the entire tree. */ @@ -442,37 +343,6 @@ public boolean isEmpty() { return root == null; } - /** - * Checks whether this tree and another with @param node - * as root are identical or not. - * - * @param node - * @return - */ - public boolean isIdentical(BinaryNode node) { - return isIdentical(this.root, node); - } - - /** - * Checks whether two trees having their roots at node1 and node2 - * are identical or not. - * - * @param node1 - * @param node2 - * @param - * @return - */ - public static > boolean isIdentical(BinaryNode node1, BinaryNode node2) { - if (node1 == null && node2 == null) return true; - if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; - - if (node1.value == node2.value) { - return true && isIdentical(node1.left, node2.left) && isIdentical(node1.right, node2.right); - } else { - return false; - } - } - /** * Converts a Tree to its Mirror Tree. @@ -503,116 +373,6 @@ public void mirror(BinaryNode node) { } - /** - * Prints the node to leaf paths, one per line. - */ - public void rootToLeafPaths() { - List pathList = new ArrayList<>(); - rootToLeafPaths(root, pathList); - - /*E[] pathList = (E[]) new Object[100]; - rootToLeafPaths(root, pathList, 0);*/ - } - - /** - * Prints the node to leaf paths, one per line. - * (Using array) - */ - public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { - if (node == null) return; - - pathList[pathLength] = node.value; - pathLength++; - - // if its a leaf node then print the list - if (node.left == null && node.right == null) { - int i; - for (i = 0; i < pathLength - 1; i++) { - out.print(pathList[i] + " -> "); - } - // outside the loop so that "->" doesn't appear after the last node - out.println(pathList[i]); - } else { - // do the same for subtrees - rootToLeafPaths(node.left, pathList, pathLength); - rootToLeafPaths(node.right, pathList, pathLength); - } - } - - /** - * Prints the node to leaf paths, one per line. - * (Using ArrayList) - */ - public void rootToLeafPaths(BinaryNode node, List pathList) { - if (node == null) return; - - pathList.add(node.value); - - // if its a leaf node then print the list - if (node.left == null && node.right == null) { - int i; - for (i = 0; i < pathList.size() - 1; i++) { - out.print(pathList.get(i) + " -> "); - } - // outside the loop so that "->" doesn't appear after the last node - out.println(pathList.get(i)); - } else { - // do the same for subtrees - rootToLeafPaths(node.left, new ArrayList<>(pathList)); - rootToLeafPaths(node.right, new ArrayList<>(pathList)); - } - } - - - /** - * Given a binary tree and a number, return true if the tree has a root-to-leaf - * path such that adding up all the values along the path equals the given number. - * Return false if no such path can be found. - * - * @param node - * @param pathList - * @param pathSum - * @return - */ - public boolean rootToLeafPathsSum(BinaryNode node, List pathList, int pathSum) { - int sum = 0; - - if (node != null) pathList.add(node.value); - - // if its either a leaf node or null then path is complete, add all in the list - if (node == null || (node.left == null && node.right == null)) { - for (int i = 0; i < pathList.size(); i++) { - sum += Integer.parseInt(pathList.get(i).toString()); - } - return sum == pathSum; - } else { - // do the same for subtrees - return rootToLeafPathsSum(node.left, new ArrayList<>(pathList), pathSum) || - rootToLeafPathsSum(node.right, new ArrayList<>(pathList), pathSum); - } - } - - - /** - * Returns the number of leaf nodes in a binary tree. - * - * @return - */ - public int countLeafNodes() { - return countLeafNodes(root); - } - - public int countLeafNodes(BinaryNode node) { - if (node == null) { - return 0; - } else if (node.left == null && node.right == null) { - return 1; - } else { - return countLeafNodes(node.left) + countLeafNodes(node.right); - } - } - - /** * Checks whether the binary tree is a BST or not. *

@@ -813,33 +573,7 @@ private void increment(BinaryNode node, int diff) { } } - - /** - * Converts a given tree to its Double tree. To create a Double tree - * of the given tree, create a new duplicate for each node, and insert - * the duplicate as the left child of the original node. - */ - public void doubleTree() { - doubleTree(root); - } - - public void doubleTree(BinaryNode node) { - if (node == null) return; - - BinaryNode newNode = new BinaryNode<>(node.value, node.left, null); - - node.left = newNode; - - doubleTree(newNode.left); - doubleTree(node.right); - } - - - /** - * Utility methods. - */ - - protected void printValue(BinaryNode node) { + public void printValue(BinaryNode node) { if (node == null) return; out.print(node.value); diff --git a/src/me/ramswaroop/trees/Tree.java b/src/me/ramswaroop/common/Tree.java similarity index 88% rename from src/me/ramswaroop/trees/Tree.java rename to src/me/ramswaroop/common/Tree.java index f07a6b0d..93fb207e 100644 --- a/src/me/ramswaroop/trees/Tree.java +++ b/src/me/ramswaroop/common/Tree.java @@ -1,4 +1,4 @@ -package me.ramswaroop.trees; +package me.ramswaroop.common; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/trees/DoubleTree.java b/src/me/ramswaroop/trees/DoubleTree.java new file mode 100644 index 00000000..ca276e5b --- /dev/null +++ b/src/me/ramswaroop/trees/DoubleTree.java @@ -0,0 +1,51 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 6:02 PM + */ +public class DoubleTree> extends BinaryTree { + + /** + * Converts a given tree to its Double tree. To create a Double tree + * of the given tree, create a new duplicate for each node, and insert + * the duplicate as the left child of the original node. + */ + public void doubleTree() { + doubleTree(root); + } + + public void doubleTree(BinaryNode node) { + if (node == null) return; + + BinaryNode newNode = new BinaryNode<>(node.value, node.left, null); + + node.left = newNode; + + doubleTree(newNode.left); + doubleTree(node.right); + } + + public static void main(String a[]) { + DoubleTree bt = new DoubleTree<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + bt.breadthFirstTraversal(); + out.println(); + bt.doubleTree(); + out.println("BFS after Double tree: "); + bt.breadthFirstTraversal(); + } +} diff --git a/src/me/ramswaroop/trees/IdenticalTrees.java b/src/me/ramswaroop/trees/IdenticalTrees.java new file mode 100644 index 00000000..2236ad16 --- /dev/null +++ b/src/me/ramswaroop/trees/IdenticalTrees.java @@ -0,0 +1,60 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; +import me.ramswaroop.common.BinaryTree; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 5:36 PM + */ +public class IdenticalTrees> extends BinaryTree { + + /** + * Checks whether this tree and another with {@param node} + * as root are identical or not. + * + * @param node + * @return + */ + public boolean isIdentical(BinaryNode node) { + return isIdentical(this.root, node); + } + + /** + * Checks whether two trees having their roots at node1 and node2 + * are identical or not. + * + * @param node1 + * @param node2 + * @param + * @return + */ + public static > boolean isIdentical(BinaryNode node1, BinaryNode node2) { + if (node1 == null && node2 == null) return true; + if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; + + if (node1.value == node2.value) { + return true && isIdentical(node1.left, node2.left) && isIdentical(node1.right, node2.right); + } else { + return false; + } + } + + public static void main(String a[]) { + BinarySearchTree bst = new BinarySearchTree<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + out.println(IdenticalTrees.isIdentical(bst.root.right, bst.root.right)); + out.println(IdenticalTrees.isIdentical(bst.root.right, bst.root)); + } +} diff --git a/src/me/ramswaroop/trees/LeafNodes.java b/src/me/ramswaroop/trees/LeafNodes.java new file mode 100644 index 00000000..0375338a --- /dev/null +++ b/src/me/ramswaroop/trees/LeafNodes.java @@ -0,0 +1,44 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 6:08 PM + */ +public class LeafNodes> extends BinaryTree { + + /** + * Returns the number of leaf nodes in a binary tree. + * + * @return + */ + public int countLeafNodes() { + return countLeafNodes(root); + } + + public int countLeafNodes(BinaryNode node) { + if (node == null) { + return 0; + } else if (node.left == null && node.right == null) { + return 1; + } else { + return countLeafNodes(node.left) + countLeafNodes(node.right); + } + } + + public static void main(String a[]) { + LeafNodes bt = new LeafNodes<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + System.out.println(bt.countLeafNodes()); + } +} diff --git a/src/me/ramswaroop/trees/RootToLeafPaths.java b/src/me/ramswaroop/trees/RootToLeafPaths.java new file mode 100644 index 00000000..f3d76931 --- /dev/null +++ b/src/me/ramswaroop/trees/RootToLeafPaths.java @@ -0,0 +1,122 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +import java.util.ArrayList; +import java.util.List; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 5:52 PM + */ +public class RootToLeafPaths> extends BinaryTree { + + /** + * Prints the node to leaf paths, one per line. + */ + public void rootToLeafPaths() { + List pathList = new ArrayList<>(); + rootToLeafPaths(root, pathList); + + /*E[] pathList = (E[]) new Object[100]; + rootToLeafPaths(root, pathList, 0);*/ + } + + /** + * Prints the node to leaf paths, one per line. + * (Using array) + */ + public void rootToLeafPaths(BinaryNode node, E[] pathList, int pathLength) { + if (node == null) return; + + pathList[pathLength] = node.value; + pathLength++; + + // if its a leaf node then print the list + if (node.left == null && node.right == null) { + int i; + for (i = 0; i < pathLength - 1; i++) { + out.print(pathList[i] + " -> "); + } + // outside the loop so that "->" doesn't appear after the last node + out.println(pathList[i]); + } else { + // do the same for subtrees + rootToLeafPaths(node.left, pathList, pathLength); + rootToLeafPaths(node.right, pathList, pathLength); + } + } + + /** + * Prints the node to leaf paths, one per line. + * (Using ArrayList) + */ + public void rootToLeafPaths(BinaryNode node, List pathList) { + if (node == null) return; + + pathList.add(node.value); + + // if its a leaf node then print the list + if (node.left == null && node.right == null) { + int i; + for (i = 0; i < pathList.size() - 1; i++) { + out.print(pathList.get(i) + " -> "); + } + // outside the loop so that "->" doesn't appear after the last node + out.println(pathList.get(i)); + } else { + // do the same for subtrees + rootToLeafPaths(node.left, new ArrayList<>(pathList)); + rootToLeafPaths(node.right, new ArrayList<>(pathList)); + } + } + + + /** + * Given a binary tree and a number, return true if the tree has a root-to-leaf + * path such that adding up all the values along the path equals the given number. + * Return false if no such path can be found. + * + * @param node + * @param pathList + * @param pathSum + * @return + */ + public boolean rootToLeafPathsSum(BinaryNode node, List pathList, int pathSum) { + int sum = 0; + + if (node != null) pathList.add(node.value); + + // if its either a leaf node or null then path is complete, add all in the list + if (node == null || (node.left == null && node.right == null)) { + for (int i = 0; i < pathList.size(); i++) { + sum += Integer.parseInt(pathList.get(i).toString()); + } + return sum == pathSum; + } else { + // do the same for subtrees + return rootToLeafPathsSum(node.left, new ArrayList<>(pathList), pathSum) || + rootToLeafPathsSum(node.right, new ArrayList<>(pathList), pathSum); + } + } + + public static void main(String a[]) { + RootToLeafPaths bt = new RootToLeafPaths<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + out.println("Root to leafs: "); + bt.rootToLeafPaths(); + out.println("Root to Leaf Sum: "); + out.println(bt.rootToLeafPathsSum(bt.root, new ArrayList(), 13)); + } +} diff --git a/src/me/ramswaroop/trees/SpiralTraversal.java b/src/me/ramswaroop/trees/SpiralTraversal.java new file mode 100644 index 00000000..d159931e --- /dev/null +++ b/src/me/ramswaroop/trees/SpiralTraversal.java @@ -0,0 +1,115 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; +import me.ramswaroop.common.LinkedStack; +import me.ramswaroop.common.Stack; + +import java.util.EmptyStackException; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 5:14 PM + */ +public class SpiralTraversal> extends BinaryTree { + + /** + * In spiral order traversal, nodes at different levels + * are printed in alternating order. + */ + public void spiralTraversal() { + spiralTraversal(root, 0); // uses recursion + } + + public void spiralTraversal(BinaryNode node, int level) { + if (node == null) return; + + // print the starting node + if (level == 0) printValue(node); + + // print the neighbour nodes + if (level % 2 == 0) { + printValue(node.left); + printValue(node.right); + } else { + printValue(node.right); + printValue(node.left); + } + + // go to next level + level++; + if (level % 2 == 0) { + spiralTraversal(node.left, level); + spiralTraversal(node.right, level); + } else { + spiralTraversal(node.right, level); + spiralTraversal(node.left, level); + } + } + + public void spiralTraversalUsingStacks(BinaryNode node) { + Stack> stack1 = new LinkedStack<>(); // for nodes to be printed ltr + Stack> stack2 = new LinkedStack<>(); // for nodes to be printed rtl + + printValue(node); + + stack1.push(node.right); + stack1.push(node.left); + + // pop stack1 and push their child nodes in stack2 + while (!stack1.isEmpty()) { + + BinaryNode leftChild = stack1.pop(); + BinaryNode rightChild = stack1.pop(); + + printValue(leftChild); + printValue(rightChild); + + try { + if (leftChild != null) stack2.push(leftChild.left); + if (leftChild != null) stack2.push(leftChild.right); + if (rightChild != null) stack2.push(rightChild.left); + if (rightChild != null) stack2.push(rightChild.right); + } catch (EmptyStackException e) { + // ignore error when stack empty + } + } + + // pop stack2 and push their child nodes in stack1 + while (!stack2.isEmpty()) { + + BinaryNode rightChild = stack2.pop(); + BinaryNode leftChild = stack2.pop(); + + printValue(rightChild); + printValue(leftChild); + + try { + if (rightChild != null) stack1.push(rightChild.right); + if (rightChild != null) stack1.push(rightChild.left); + if (leftChild != null) stack1.push(leftChild.right); + if (leftChild != null) stack1.push(leftChild.left); + } catch (EmptyStackException e) { + // ignore error when stack empty + } + } + } + + public static void main(String a[]) { + SpiralTraversal bt = new SpiralTraversal<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + bt.breadthFirstTraversal(); + System.out.println(""); + bt.spiralTraversal(); + System.out.println(""); + bt.spiralTraversalUsingStacks(bt.root); + } +} diff --git a/src/me/ramswaroop/trees/TreeToList.java b/src/me/ramswaroop/trees/TreeToList.java new file mode 100644 index 00000000..6f10d83c --- /dev/null +++ b/src/me/ramswaroop/trees/TreeToList.java @@ -0,0 +1,74 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 4:38 PM + */ +public class TreeToList> extends BinarySearchTree { + + /** + * A recursive function that takes an ordered binary tree + * and rearranges the internal pointers to make a circular + * doubly linked list out of the tree nodes. The list should + * be arranged so that the nodes are in increasing order. + */ + public void treeToList() { + // print the list + printList(treeToList(root)); + } + + public static > BinaryNode treeToList(BinaryNode node) { + if (node == null) return null; + + BinaryNode aList = treeToList(node.left); + BinaryNode bList = treeToList(node.right); + + node.left = node; + node.right = node; + + // attach left child then root followed by right child (so that final list is in ascending order) + aList = addToList(aList, node); + aList = addToList(aList, bList); + + return aList; + } + + private static > BinaryNode addToList(BinaryNode aList, BinaryNode bList) { + + if (aList == null) return bList; + if (bList == null) return aList; + + // find the last node in each list + BinaryNode aListLast = aList.left; + BinaryNode bListLast = bList.left; + + // join end of one list to beginning of another + aListLast.right = bList; + bList.left = aListLast; + + // make circular + aListLast.left = bListLast; + bListLast.right = aList; + + return aList; + } + + public static void main(String a[]) { + BinarySearchTree bst = new BinarySearchTree<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + bst.inOrder(); + // TODO incorrect results + bst.printList(treeToList(bst.root)); + } +} From 227f782e3517f97fc7169533371d0df6fa07c1ca Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 19:44:30 +0530 Subject: [PATCH 137/417] code refactoring done for trees --- .../ramswaroop/common/BinarySearchTree.java | 86 ----- src/me/ramswaroop/common/BinaryTree.java | 330 +----------------- src/me/ramswaroop/trees/BFSUsingQueue.java | 52 +++ src/me/ramswaroop/trees/CheckForBST.java | 92 +++++ src/me/ramswaroop/trees/ChildrenSum.java | 104 ++++++ src/me/ramswaroop/trees/HeightBalanced.java | 49 +++ .../ramswaroop/trees/InOrderUsingStack.java | 60 ++++ .../ramswaroop/trees/LeastCommonAncestor.java | 66 ++++ src/me/ramswaroop/trees/MirrorTree.java | 57 +++ 9 files changed, 481 insertions(+), 415 deletions(-) create mode 100644 src/me/ramswaroop/trees/BFSUsingQueue.java create mode 100644 src/me/ramswaroop/trees/CheckForBST.java create mode 100644 src/me/ramswaroop/trees/ChildrenSum.java create mode 100644 src/me/ramswaroop/trees/HeightBalanced.java create mode 100644 src/me/ramswaroop/trees/InOrderUsingStack.java create mode 100644 src/me/ramswaroop/trees/LeastCommonAncestor.java create mode 100644 src/me/ramswaroop/trees/MirrorTree.java diff --git a/src/me/ramswaroop/common/BinarySearchTree.java b/src/me/ramswaroop/common/BinarySearchTree.java index eab0dc10..37093271 100644 --- a/src/me/ramswaroop/common/BinarySearchTree.java +++ b/src/me/ramswaroop/common/BinarySearchTree.java @@ -12,59 +12,6 @@ * To change this template go to Preferences | IDE Settings | File and Code Templates */ public class BinarySearchTree> extends BinaryTree { - public static void main(String[] a) { - BinarySearchTree bst = new BinarySearchTree<>(); - bst.put(6); - bst.put(3); - bst.put(5); - bst.put(7); - bst.put(8); - bst.put(9); - /*bst.put(12); - bst.put(10); - bst.put(16); - bst.put(14); - bst.put(25); - bst.put(15); - bst.put(20); - bst.put(35); - bst.put(23); - bst.put(22); - bst.put(21); - bst.put(45); - bst.put(40); - bst.put(56); - bst.put(65); - bst.put(75); - bst.put(85);*/ - bst.preOrder(); - out.println(""); - bst.inOrder(); - out.println(""); - bst.postOrder(); - out.println("\n" + bst.size()); - out.println(bst.height()); - /*obj.delete(); - out.println("After deletion: "); - obj.postOrder();*/ - out.print("\nIn Order: "); - bst.inOrder(); - /*out.println("\nAfter mirroring: "); - obj.mirror(); - obj.inOrder();*/ - out.println("LCA: " + bst.leastCommonAncestor(bst.root, 6, 8).value); - out.println("Min: " + bst.min().value); - out.println("BFT: "); - bst.breadthFirstTraversal(); - out.println("\nBFT using queue: "); - bst.breadthFirstTraversalUsingQueue(); - out.println("Is BST: " + bst.isBST()); - /*out.print("Tree to list: "); - bst.treeToList();*/ - out.print("\nIs height balanced: " + bst.isHeightBalanced()); - out.print("\nDiameter: " + bst.diameter()); - } - /** * Inserts a node into the BST. @@ -117,39 +64,6 @@ public BinaryNode min(BinaryNode node) { } } - - /** - * Determines the LCA for a BST - *

- * DEFINITION OF LCA: - * Let T be a rooted tree. The lowest - * common ancestor between two nodes n1 and - * n2 is defined as the lowest node in T that has - * both n1 and n2 as descendants (where we allow - * a node to be a descendant of itself). - */ - public void leastCommonAncestor() { - /*int value1, value2; - Scanner in = new Scanner(System.in); - out.println("Enter value 1: "); - value1 = (E) Integer.valueOf(in.nextLine()); - out.println("Enter value 1: "); - value2 = (E) in.nextLine(); - out.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ - } - - public BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { - if (node == null || value1.compareTo(value2) > 0) throw new NoSuchElementException(); - - if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) { - return node; - } else if (value1.compareTo(node.value) > 0 && value2.compareTo(node.value) > 0) { - return leastCommonAncestor(node.right, value1, value2); - } else { - return leastCommonAncestor(node.left, value1, value2); - } - } - public void printList(BinaryNode node) { BinaryNode current = node; out.print("["); diff --git a/src/me/ramswaroop/common/BinaryTree.java b/src/me/ramswaroop/common/BinaryTree.java index 7c7bb41b..4019fea5 100644 --- a/src/me/ramswaroop/common/BinaryTree.java +++ b/src/me/ramswaroop/common/BinaryTree.java @@ -1,8 +1,5 @@ package me.ramswaroop.common; -import java.util.List; -import java.util.NoSuchElementException; - import static java.lang.System.out; /** @@ -17,38 +14,6 @@ public class BinaryTree> extends Tree { public BinaryNode root; Queue> queue = new LinkedQueue<>(); // needed for insertion - public static void main(String[] a) { - BinaryTree binaryTree = new BinaryTree<>(); - binaryTree.put(6); - binaryTree.put(3); - binaryTree.put(9); - binaryTree.put(2); - /*binaryTree.put(4); - binaryTree.put(5); - binaryTree.put(7);*/ - out.print("Breadth-first Traversal: "); - binaryTree.breadthFirstTraversal(); - out.print("\nIn order traversal: "); - binaryTree.inOrder(); - out.print("\nIn order traversal without stack: "); - binaryTree.inOrderWithoutStackAndRecursion(binaryTree.root); - out.print("\nWidth: " + binaryTree.width()); - out.print("\nIs BST: " + binaryTree.isBST()); - out.print("\nIs Children Sum : " + binaryTree.isChildrenSum()); - /*binaryTree.toChildrenSum(); - out.print("\nBreadth-first Traversal after to children sum: "); - binaryTree.breadthFirstTraversal();*/ - out.print("\nIs height balanced: " + binaryTree.isHeightBalanced()); - out.print("\nDiameter: " + binaryTree.diameter()); - - binaryTree.breadthFirstTraversalUsingQueue(); - out.print("\nIn order traversal: "); - binaryTree.inOrder(); - binaryTree.deleteChildrens(binaryTree.root); - out.print("\nIn order traversal after deleteChildrens: "); - binaryTree.inOrder(); - } - /** * Inserts a node into the binary tree such that * it always forms a complete binary tree. @@ -79,7 +44,7 @@ public BinaryNode put(BinaryNode node, E value) { } /** - * Traversals using recursions. + * Traversals. */ @@ -134,89 +99,6 @@ public void postOrder(BinaryNode node) { } - /** - * Traversals without recursions. - */ - - /** - * In-order traversal of tree using one stack and without recursion. - * - * @param node - */ - public void inOrderUsingStack(BinaryNode node) { - if (node == null) return; - - Stack> stack = new LinkedStack<>(); - - BinaryNode curr = node; // set root node as current node - stack.push(curr); // push current node - - while (!stack.isEmpty()) { - - while (curr != null) { - curr = curr.left; - if (curr != null) stack.push(curr); // push all left nodes of the current node - } - - BinaryNode top = stack.pop(); - out.print(top.value); // print top of stack - curr = top.right; - if (curr != null) stack.push(curr); // push right child of top node - } - } - - /** - * Using Morris Traversal, we can traverse the tree without using stack and - * recursion. The idea of Morris Traversal is based on Threaded Binary Tree. - * In this traversal, we first create links to Inorder successor and print the - * data using these links, and finally revert the changes to restore original tree. - *

- * A binary tree is THREADED by making all right child pointers that would normally - * be null point to the inorder successor of the node (if it exists), and all left - * child pointers that would normally be null point to the inorder predecessor of - * the node. - *

- * PSEUDOCODE: - * 1. Initialize current as root - * 2. While current is not NULL - * If current does not have left child - * a) Print current’s data - * b) Go to the right, i.e., current = current->right - * Else - * a) Make current as right child of the rightmost node in current's left subtree - * b) Go to this left child, i.e., current = current->left - * - * @param node - */ - public void inOrderWithoutStackAndRecursion(BinaryNode node) { - if (node == null) return; - - BinaryNode curr = node; - - while (curr != null) { - // print the leftmost node - if (curr.left == null) { - printValue(curr); - curr = curr.right; - } else { // make current as right child of the rightmost node in current's left subtree - BinaryNode pre = curr.left; - - while (pre.right != curr && pre.right != null) { - pre = pre.right; - } - if (pre.right != curr) { - pre.right = curr; - curr = curr.left; - } else { - printValue(curr); - curr = curr.right; - pre.right = null; // revert to the original tree structure - } - } - } - } - - /** * Prints the node of the tree breadth-wise. *

@@ -247,29 +129,6 @@ public void breadthFirstTraversal(BinaryNode node, int level) { breadthFirstTraversal(node.right, level); } - /** - * Breadth first traversal (Level-order traversal using Queue). - */ - public void breadthFirstTraversalUsingQueue() { - Queue> queue = new LinkedQueue<>(); - breadthFirstTraversalUsingQueue(root, queue); - } - - public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue> queue) { - - if (node != null) { - printValue(node); - queue.add(node.left); - queue.add(node.right); - } - - try { - breadthFirstTraversalUsingQueue(queue.remove(), queue); - } catch (NoSuchElementException e) { - return; - } - } - /** * Deletes the entire tree. */ @@ -344,98 +203,6 @@ public boolean isEmpty() { } - /** - * Converts a Tree to its Mirror Tree. - *

- * MIRROR OF A BINARY TREE T is another Binary Tree M(T) with - * left and right children of all non-leaf nodes interchanged. - *

- * TIP: In-order traversal of mirror tree is exactly the - * reverse of the in-order traversal of the original tree. - */ - public void mirror() { - mirror(root); - } - - public void mirror(BinaryNode node) { - if (node == null) return; - - BinaryNode tempNode; - - // mirror sub-trees - mirror(node.left); - mirror(node.right); - - // swap nodes - tempNode = node.left; - node.left = node.right; - node.right = tempNode; - } - - - /** - * Checks whether the binary tree is a BST or not. - *

- * Approach: Performs in-order traversal of the tree and if - * the result isn't in ascending order then returns false. - * - * @return - */ - public boolean isBST() { - //List> list = new ArrayList<>(); - BinaryNode prev = new BinaryNode<>(null); - return isBST(root, prev); - } - - /** - * Traverse the tree in in-order fashion and insert all nodes - * in a list and check for sort order of list. - * - * @param node - * @param list - * @return - */ - public boolean isBST(BinaryNode node, List> list) { - if (node == null) return true; - - boolean left = isBST(node.left, list); - - // while adding node to list, compare it with previous node in list - if (list.size() > 0 && list.get(list.size() - 1).value.compareTo(node.value) > 0) { - return false; - } - list.add(node); - - boolean right = isBST(node.right, list); - - return left && right; - } - - /** - * Traverse the tree in in-order fashion and keep track of prev node. - *

- * - * @param node - * @param prev - * @return - */ - public boolean isBST(BinaryNode node, BinaryNode prev) { - if (node == null) return true; - - boolean left = isBST(node.left, prev); - - // compare current node with previous node - if (prev.value != null && prev.value.compareTo(node.value) > 0) { - return false; - } - prev.value = node.value; - - boolean right = isBST(node.right, prev); - - return left && right; - } - - /** * The diameter of a tree (sometimes called the width) is the number * of nodes on the longest path between two leaves in the tree. @@ -478,101 +245,6 @@ public int width(BinaryNode node, int width) { return width; } - /** - * An empty tree is height-balanced. A non-empty binary tree T is balanced if: - * 1) Left subtree of T is balanced - * 2) Right subtree of T is balanced - * 3) The difference between heights of left subtree and right subtree is not more than 1. - * - * @return True if tree is height balanced otherwise false. - */ - public boolean isHeightBalanced() { - return isHeightBalanced(root); - } - - public boolean isHeightBalanced(BinaryNode node) { - if (node == null) return true; - - if (Math.abs(height(node.left) - height(node.right)) > 1) { - return false; - } - - return isHeightBalanced(node.left) && isHeightBalanced(node.right); - } - - /** - * Children Sum Invariant: For every node, the value must be equal to - * sum of values in the left and right child. - * Consider data value as 0 for NULL child. - * - * @return - */ - public boolean isChildrenSum() { - return isChildrenSum(root); - } - - public boolean isChildrenSum(BinaryNode node) { - if (node == null || node.left == null && node.right == null) return true; - - E leftChildValue = (E) (node.left == null ? 0 : node.left.value); - E rightChildValue = (E) (node.right == null ? 0 : node.right.value); - - if (!node.value.toString().equals( - String.valueOf(Integer.parseInt(leftChildValue.toString()) + - Integer.parseInt(rightChildValue.toString())) - )) { - return false; - } - - return isChildrenSum(node.left) && isChildrenSum(node.right); - } - - /** - * Converts a tree to hold the children sum invariant. - *

- * It only increments data values in any node (Does not - * change structure of tree and cannot decrement value of - * any node). - */ - public void toChildrenSum() { - toChildrenSum(root); - } - - public void toChildrenSum(BinaryNode node) { - - if (node == null || node.left == null && node.right == null) return; - - toChildrenSum(node.left); - toChildrenSum(node.right); - - Integer nodeValue = (Integer) (node == null ? 0 : node.value); - Integer leftChildValue = (Integer) (node.left == null ? 0 : node.left.value); - Integer rightChildValue = (Integer) (node.right == null ? 0 : node.right.value); - - int diff = (nodeValue - (leftChildValue + rightChildValue)); - - if (diff < 0) { - increment(node, diff); - } else if (diff > 0) { - if (node.left != null) { - increment(node.left, diff); - } else { - increment(node.right, diff); - } - } - } - - // TODO - private void increment(BinaryNode node, int diff) { - if (node.left != null) { - //node.value += Math.abs(diff); - increment(node.left, diff); - } else if (node.right != null) { - //node.value += Math.abs(diff); - increment(node.right, diff); - } - } - public void printValue(BinaryNode node) { if (node == null) return; diff --git a/src/me/ramswaroop/trees/BFSUsingQueue.java b/src/me/ramswaroop/trees/BFSUsingQueue.java new file mode 100644 index 00000000..7a161da0 --- /dev/null +++ b/src/me/ramswaroop/trees/BFSUsingQueue.java @@ -0,0 +1,52 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; +import me.ramswaroop.common.LinkedQueue; +import me.ramswaroop.common.Queue; + +import java.util.NoSuchElementException; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:34 PM + */ +public class BFSUsingQueue> extends BinaryTree { + + /** + * Breadth first traversal (Level-order traversal using Queue). + */ + public void breadthFirstTraversalUsingQueue() { + Queue> queue = new LinkedQueue<>(); + breadthFirstTraversalUsingQueue(root, queue); + } + + public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue> queue) { + + if (node != null) { + printValue(node); + queue.add(node.left); + queue.add(node.right); + } + + try { + breadthFirstTraversalUsingQueue(queue.remove(), queue); + } catch (NoSuchElementException e) { + return; + } + } + + public static void main(String a[]) { + BFSUsingQueue bt = new BFSUsingQueue<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + bt.breadthFirstTraversalUsingQueue(); + } +} diff --git a/src/me/ramswaroop/trees/CheckForBST.java b/src/me/ramswaroop/trees/CheckForBST.java new file mode 100644 index 00000000..7335ff63 --- /dev/null +++ b/src/me/ramswaroop/trees/CheckForBST.java @@ -0,0 +1,92 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +import java.util.List; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:14 PM + */ +public class CheckForBST> extends BinaryTree { + + /** + * Checks whether the binary tree is a BST or not. + *

+ * Approach: Performs in-order traversal of the tree and if + * the result isn't in ascending order then returns false. + * + * @return + */ + public boolean isBST() { + //List> list = new ArrayList<>(); + BinaryNode prev = new BinaryNode<>(null); + return isBST(root, prev); + } + + /** + * Traverse the tree in in-order fashion and insert all nodes + * in a list and check for sort order of list. + * + * @param node + * @param list + * @return + */ + public boolean isBST(BinaryNode node, List> list) { + if (node == null) return true; + + boolean left = isBST(node.left, list); + + // while adding node to list, compare it with previous node in list + if (list.size() > 0 && list.get(list.size() - 1).value.compareTo(node.value) > 0) { + return false; + } + list.add(node); + + boolean right = isBST(node.right, list); + + return left && right; + } + + /** + * Traverse the tree in in-order fashion and keep track of prev node. + *

+ * + * @param node + * @param prev + * @return + */ + public boolean isBST(BinaryNode node, BinaryNode prev) { + if (node == null) return true; + + boolean left = isBST(node.left, prev); + + // compare current node with previous node + if (prev.value != null && prev.value.compareTo(node.value) > 0) { + return false; + } + prev.value = node.value; + + boolean right = isBST(node.right, prev); + + return left && right; + } + + public static void main(String a[]) { + CheckForBST bt = new CheckForBST<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + out.println("Is BST: "); + out.println(bt.isBST()); + } +} diff --git a/src/me/ramswaroop/trees/ChildrenSum.java b/src/me/ramswaroop/trees/ChildrenSum.java new file mode 100644 index 00000000..8b0f8a36 --- /dev/null +++ b/src/me/ramswaroop/trees/ChildrenSum.java @@ -0,0 +1,104 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:01 PM + */ +public class ChildrenSum> extends BinaryTree { + + /** + * Children Sum Invariant: For every node, the value must be equal to + * sum of values in the left and right child. + * Consider data value as 0 for NULL child. + * + * @return + */ + public boolean isChildrenSum() { + return isChildrenSum(root); + } + + public boolean isChildrenSum(BinaryNode node) { + if (node == null || node.left == null && node.right == null) return true; + + E leftChildValue = (E) (node.left == null ? 0 : node.left.value); + E rightChildValue = (E) (node.right == null ? 0 : node.right.value); + + if (!node.value.toString().equals( + String.valueOf(Integer.parseInt(leftChildValue.toString()) + + Integer.parseInt(rightChildValue.toString())) + )) { + return false; + } + + return isChildrenSum(node.left) && isChildrenSum(node.right); + } + + /** + * Converts a tree to hold the children sum invariant. + *

+ * It only increments data values in any node (Does not + * change structure of tree and cannot decrement value of + * any node). + */ + public void toChildrenSum() { + toChildrenSum(root); + } + + public void toChildrenSum(BinaryNode node) { + + if (node == null || node.left == null && node.right == null) return; + + toChildrenSum(node.left); + toChildrenSum(node.right); + + Integer nodeValue = (Integer) (node == null ? 0 : node.value); + Integer leftChildValue = (Integer) (node.left == null ? 0 : node.left.value); + Integer rightChildValue = (Integer) (node.right == null ? 0 : node.right.value); + + int diff = (nodeValue - (leftChildValue + rightChildValue)); + + if (diff < 0) { + increment(node, diff); + } else if (diff > 0) { + if (node.left != null) { + increment(node.left, diff); + } else { + increment(node.right, diff); + } + } + } + + // TODO + private void increment(BinaryNode node, int diff) { + if (node.left != null) { + //node.value += Math.abs(diff); + increment(node.left, diff); + } else if (node.right != null) { + //node.value += Math.abs(diff); + increment(node.right, diff); + } + } + + public static void main(String a[]) { + ChildrenSum bt = new ChildrenSum<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + out.println("Is Children Sum : "); + out.println(bt.isChildrenSum()); + /*binaryTree.toChildrenSum(); + out.print("\nBreadth-first Traversal after to children sum: "); + binaryTree.breadthFirstTraversal();*/ + } +} diff --git a/src/me/ramswaroop/trees/HeightBalanced.java b/src/me/ramswaroop/trees/HeightBalanced.java new file mode 100644 index 00000000..10152c63 --- /dev/null +++ b/src/me/ramswaroop/trees/HeightBalanced.java @@ -0,0 +1,49 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:07 PM + */ +public class HeightBalanced> extends BinarySearchTree { + + /** + * An empty tree is height-balanced. A non-empty binary tree T is balanced if: + * 1) Left subtree of T is balanced + * 2) Right subtree of T is balanced + * 3) The difference between heights of left subtree and right subtree is not more than 1. + * + * @return True if tree is height balanced otherwise false. + */ + public boolean isHeightBalanced() { + return isHeightBalanced(root); + } + + public boolean isHeightBalanced(BinaryNode node) { + if (node == null) return true; + + if (Math.abs(height(node.left) - height(node.right)) > 1) { + return false; + } + + return isHeightBalanced(node.left) && isHeightBalanced(node.right); + } + + public static void main(String a[]) { + HeightBalanced bst = new HeightBalanced<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + out.print("\nIs height balanced: " + bst.isHeightBalanced()); + } +} diff --git a/src/me/ramswaroop/trees/InOrderUsingStack.java b/src/me/ramswaroop/trees/InOrderUsingStack.java new file mode 100644 index 00000000..ce580e99 --- /dev/null +++ b/src/me/ramswaroop/trees/InOrderUsingStack.java @@ -0,0 +1,60 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; +import me.ramswaroop.common.LinkedStack; +import me.ramswaroop.common.Stack; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:31 PM + */ +public class InOrderUsingStack> extends BinarySearchTree { + + public void inOrder() { + inOrderUsingStack(root); + } + + /** + * In-order traversal of tree using one stack and without recursion. + * + * @param node + */ + public void inOrderUsingStack(BinaryNode node) { + if (node == null) return; + + Stack> stack = new LinkedStack<>(); + + BinaryNode curr = node; // set root node as current node + stack.push(curr); // push current node + + while (!stack.isEmpty()) { + + while (curr != null) { + curr = curr.left; + if (curr != null) stack.push(curr); // push all left nodes of the current node + } + + BinaryNode top = stack.pop(); + out.print(top.value); // print top of stack + curr = top.right; + if (curr != null) stack.push(curr); // push right child of top node + } + } + + public static void main(String a[]) { + InOrderUsingStack bst = new InOrderUsingStack<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + bst.inOrder(); + } +} diff --git a/src/me/ramswaroop/trees/LeastCommonAncestor.java b/src/me/ramswaroop/trees/LeastCommonAncestor.java new file mode 100644 index 00000000..41a48828 --- /dev/null +++ b/src/me/ramswaroop/trees/LeastCommonAncestor.java @@ -0,0 +1,66 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; + +import java.util.NoSuchElementException; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:38 PM + */ +public class LeastCommonAncestor> extends BinarySearchTree { + + + public void leastCommonAncestor() { + /*int value1, value2; + Scanner in = new Scanner(System.in); + out.println("Enter value 1: "); + value1 = (E) Integer.valueOf(in.nextLine()); + out.println("Enter value 1: "); + value2 = (E) in.nextLine(); + out.println("LCA of " + value1 + " and " + value2 + " is: " + leastCommonAncestor(root, value1, value2).value);*/ + } + + /** + * Determines the LCA for a BST + *

+ * DEFINITION OF LCA: + * Let T be a rooted tree. The lowest + * common ancestor between two nodes n1 and + * n2 is defined as the lowest node in T that has + * both n1 and n2 as descendants (where we allow + * a node to be a descendant of itself). + * + * @param node + * @param value1 + * @param value2 + * @param + * @return + */ + public static > BinaryNode leastCommonAncestor(BinaryNode node, E value1, E value2) { + if (node == null || value1.compareTo(value2) > 0) throw new NoSuchElementException(); + + if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) { + return node; + } else if (value1.compareTo(node.value) > 0 && value2.compareTo(node.value) > 0) { + return leastCommonAncestor(node.right, value1, value2); + } else { + return leastCommonAncestor(node.left, value1, value2); + } + } + + public static void main(String a[]) { + BinarySearchTree bst = new BinarySearchTree<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + System.out.println(leastCommonAncestor(bst.root, 5, 6).value); + } +} diff --git a/src/me/ramswaroop/trees/MirrorTree.java b/src/me/ramswaroop/trees/MirrorTree.java new file mode 100644 index 00000000..f9b05c60 --- /dev/null +++ b/src/me/ramswaroop/trees/MirrorTree.java @@ -0,0 +1,57 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:03 PM + */ +public class MirrorTree> extends BinaryTree { + + /** + * Converts a Tree to its Mirror Tree. + *

+ * MIRROR OF A BINARY TREE T is another Binary Tree M(T) with + * left and right children of all non-leaf nodes interchanged. + *

+ * TIP: In-order traversal of mirror tree is exactly the + * reverse of the in-order traversal of the original tree. + */ + public void mirror() { + mirror(root); + } + + public void mirror(BinaryNode node) { + if (node == null) return; + + BinaryNode tempNode; + + // mirror sub-trees + mirror(node.left); + mirror(node.right); + + // swap nodes + tempNode = node.left; + node.left = node.right; + node.right = tempNode; + } + + public static void main(String a[]) { + MirrorTree bt = new MirrorTree<>(); + bt.put(6); + bt.put(3); + bt.put(5); + bt.put(7); + bt.put(8); + bt.put(9); + System.out.println("Original Tree"); + bt.breadthFirstTraversal(); + System.out.println("\nMirror Tree"); + bt.mirror(); + bt.breadthFirstTraversal(); + } +} From a9acb8d3a71f06c3a9bc5e203ed7d0989b85bace Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 26 Jun 2015 19:47:11 +0530 Subject: [PATCH 138/417] code refactoring for trees --- .../arrays/LargestSumContiguousSubArray.java | 19 +++++ .../ConstructTreeFromInorderAndPreorder.java | 19 +++++ .../InorderWithoutStackAndRecursion.java | 80 +++++++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java create mode 100644 src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java create mode 100644 src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java diff --git a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java new file mode 100644 index 00000000..770d61d6 --- /dev/null +++ b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java @@ -0,0 +1,19 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/28/15 + * @time: 12:44 PM + */ +public class LargestSumContiguousSubArray { + + public void largestSumContiguousSubArray(int a[]) { + + } + + public static void main(String a[]) { + + } +} diff --git a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java new file mode 100644 index 00000000..d7e0e311 --- /dev/null +++ b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java @@ -0,0 +1,19 @@ +package me.ramswaroop.trees; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 5:34 PM + */ +public class ConstructTreeFromInorderAndPreorder { + + public void ConstructTreeFromInorderAndPreorder() { + + } + + public static void main(String a[]) { + + } +} diff --git a/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java b/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java new file mode 100644 index 00000000..4e34dcff --- /dev/null +++ b/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java @@ -0,0 +1,80 @@ +package me.ramswaroop.trees; + +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/26/15 + * @time: 7:23 PM + */ +public class InOrderWithoutStackAndRecursion> extends BinarySearchTree { + + public void inOrder() { + inOrderWithoutStackAndRecursion(root); + } + + /** + * Using Morris Traversal, we can traverse the tree without using stack and + * recursion. The idea of Morris Traversal is based on Threaded Binary Tree. + * In this traversal, we first create links to Inorder successor and print the + * data using these links, and finally revert the changes to restore original tree. + *

+ * A binary tree is THREADED by making all right child pointers that would normally + * be null point to the inorder successor of the node (if it exists), and all left + * child pointers that would normally be null point to the inorder predecessor of + * the node. + *

+ * PSEUDOCODE: + * 1. Initialize current as root + * 2. While current is not NULL + * If current does not have left child + * a) Print current’s data + * b) Go to the right, i.e., current = current->right + * Else + * a) Make current as right child of the rightmost node in current's left subtree + * b) Go to this left child, i.e., current = current->left + * + * @param node + */ + public void inOrderWithoutStackAndRecursion(BinaryNode node) { + if (node == null) return; + + BinaryNode curr = node; + + while (curr != null) { + // print the leftmost node + if (curr.left == null) { + printValue(curr); + curr = curr.right; + } else { // make current as right child of the rightmost node in current's left subtree + BinaryNode pre = curr.left; + + while (pre.right != curr && pre.right != null) { + pre = pre.right; + } + if (pre.right != curr) { + pre.right = curr; + curr = curr.left; + } else { + printValue(curr); + curr = curr.right; + pre.right = null; // revert to the original tree structure + } + } + } + } + + public static void main(String a[]) { + InOrderWithoutStackAndRecursion bst = new InOrderWithoutStackAndRecursion<>(); + bst.put(6); + bst.put(3); + bst.put(5); + bst.put(7); + bst.put(8); + bst.put(9); + bst.inOrder(); + } +} From e511c2e37f9a2bf45dbe3f162ef05612ed0109b9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 27 Jun 2015 17:18:12 +0530 Subject: [PATCH 139/417] intersection of 2 sorted list done --- .../IntersectionOf2SortedLists.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java diff --git a/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java b/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java new file mode 100644 index 00000000..31036b9f --- /dev/null +++ b/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java @@ -0,0 +1,64 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/27/15 + * @time: 11:13 AM + */ +public class IntersectionOf2SortedLists> extends SingleLinkedList { + + /** + * Returns a linked list with elements common in + * both {@param list1} and {@param list2}. + * + * @param list1 + * @param list2 + * @param + * @return + */ + public static > SingleLinkedList getIntersectionList(SingleLinkedList list1, + SingleLinkedList list2) { + + SingleLinkedNode curr1 = list1.getNode(0), curr2 = list2.getNode(0); + SingleLinkedList intersectedList = new SingleLinkedList<>(); + while (curr1 != null && curr2 != null) { + // advance the current pointer of the list having smaller {@code item} + if (curr1.item.compareTo(curr2.item) < 0) { + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) > 0) { + curr2 = curr2.next; + } else { // both nodes are equal so add it to the result + intersectedList.add(curr1.item); + curr1 = curr1.next; + curr2 = curr2.next; + } + } + + return intersectedList; + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(21); + linkedList2.add(33); + linkedList2.add(44); + linkedList2.add(55); + linkedList2.add(67); + linkedList2.add(89); + linkedList2.printList(); + getIntersectionList(linkedList1, linkedList2).printList(); + } +} From eeb0967adffb9b234927d6cf752e859f8ae0e10e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 27 Jun 2015 17:33:50 +0530 Subject: [PATCH 140/417] delete alternate nodes: done --- .../linkedlists/DeleteAlternateNodes.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java diff --git a/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java b/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java new file mode 100644 index 00000000..4f9afb02 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java @@ -0,0 +1,40 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/27/15 + * @time: 5:27 PM + */ +public class DeleteAlternateNodes> extends SingleLinkedList { + + public static > void deleteAlternateNodes(SingleLinkedList list) { + deleteAlternateNodes(list.head); + } + + public static > void deleteAlternateNodes(SingleLinkedNode node) { + if (node == null || node.next == null) return; + + node.next = node.next.next; + + deleteAlternateNodes(node.next); + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.printList(); + deleteAlternateNodes(linkedList1); + linkedList1.printList(); + + } +} From 711ca8aaf92ca84dff0f614835b175de0b1d7fc4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 27 Jun 2015 17:34:08 +0530 Subject: [PATCH 141/417] pending --- .../trees/ConstructTreeFromInorderAndPreorder.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java index d7e0e311..cefee4b9 100644 --- a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java +++ b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java @@ -1,5 +1,10 @@ package me.ramswaroop.trees; +import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinaryTree; + +import java.util.List; + /** * Created by IntelliJ IDEA. * @@ -7,10 +12,12 @@ * @date: 6/26/15 * @time: 5:34 PM */ -public class ConstructTreeFromInorderAndPreorder { +public class ConstructTreeFromInorderAndPreorder> extends BinaryTree { - public void ConstructTreeFromInorderAndPreorder() { + public void constructTreeWithInOrderAndPreOrder(List> inOrder, List> preOrder) { + for (int i = 0; i < preOrder.size(); i++) { + } } public static void main(String a[]) { From b84866b9daecfad5a809a3eec3c827351bf5d788 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 28 Jun 2015 17:28:24 +0530 Subject: [PATCH 142/417] merge two lists: done --- .../linkedlists/DeleteAlternateNodes.java | 20 ++--- .../linkedlists/IntersectionOfTwoLists.java | 8 ++ .../linkedlists/MergeTwoSortedLists.java | 78 +++++++++++++++++++ 3 files changed, 96 insertions(+), 10 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java diff --git a/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java b/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java index 4f9afb02..4fc5124e 100644 --- a/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java +++ b/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java @@ -25,16 +25,16 @@ public static > void deleteAlternateNodes(SingleLinkedNo } public static void main(String a[]) { - SingleLinkedList linkedList1 = new SingleLinkedList<>(); - linkedList1.add(00); - linkedList1.add(11); - linkedList1.add(22); - linkedList1.add(33); - linkedList1.add(44); - linkedList1.add(55); - linkedList1.printList(); - deleteAlternateNodes(linkedList1); - linkedList1.printList(); + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.printList(); + deleteAlternateNodes(linkedList); + linkedList.printList(); } } diff --git a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java b/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java index 29c6fcac..df2101e3 100644 --- a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java +++ b/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java @@ -13,6 +13,14 @@ public class IntersectionOfTwoLists> extends SingleLinkedList { + /** + * Returns the node at which {@param list1} and {@param list2} intersect. + * + * @param list1 + * @param list2 + * @param + * @return + */ public static > SingleLinkedNode getIntersectionNode(SingleLinkedList list1, SingleLinkedList list2) { diff --git a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java new file mode 100644 index 00000000..6139140e --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java @@ -0,0 +1,78 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/27/15 + * @time: 8:47 PM + */ +public class MergeTwoSortedLists> extends SingleLinkedList { + + /** + * Merges two sorted list {@param list1} and {@param list2} into + * a list with values in ascending order. + * + * @param list1 + * @param list2 + * @param + * @return + */ + public static > SingleLinkedList mergeTwoSortedLists(SingleLinkedList list1, + SingleLinkedList list2) { + SingleLinkedNode curr1 = list1.getNode(0), curr2 = list2.getNode(0); + SingleLinkedList intersectedList = new SingleLinkedList<>(); + while (curr1 != null || curr2 != null) { + // handle cases where either of the list run out first + if (curr1 == null) { + intersectedList.add(curr2.item); + curr2 = curr2.next; + continue; + } + if (curr2 == null) { + intersectedList.add(curr1.item); + curr1 = curr1.next; + continue; + } + + // advance the current pointer of the list having smaller {@code item} + if (curr1.item.compareTo(curr2.item) < 0) { + intersectedList.add(curr1.item); + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) > 0) { + intersectedList.add(curr2.item); + curr2 = curr2.next; + } else { // both nodes are equal so add both to the result + intersectedList.add(curr1.item); + intersectedList.add(curr1.item); + curr1 = curr1.next; + curr2 = curr2.next; + } + } + + return intersectedList; + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(21); + linkedList2.add(33); + linkedList2.add(44); + linkedList2.add(55); + linkedList2.add(67); + linkedList2.add(89); + linkedList2.printList(); + mergeTwoSortedLists(linkedList1, linkedList2).printList(); + } +} From 439032ffef30abfc3629a253405063dea24ea556 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 29 Jun 2015 09:40:12 +0530 Subject: [PATCH 143/417] merge two lists: done (recursive way) --- .../linkedlists/MergeTwoSortedLists.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java index 6139140e..ecbb235e 100644 --- a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java +++ b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java @@ -56,6 +56,50 @@ public static > SingleLinkedList mergeTwoSortedLists( return intersectedList; } + /** + * Recursive method to merge two sorted lists into one sorted list. + * + * NOTE: You can make {@param mergedList} as static and not pass as params + * to this method. + * + * @param node1 + * @param node2 + * @param + */ + public static > SingleLinkedNode mergeTwoSortedLists(SingleLinkedList mergedList, + SingleLinkedNode node1, + SingleLinkedNode node2) { + + if (node1 == null && node2 == null) return null; + + // if either of the list runs out first + if (node1 == null) { + mergeTwoSortedLists(mergedList, node1, node2.next); + mergedList.addFirst(node2.item); + return node2; + } + if (node2 == null) { + mergeTwoSortedLists(mergedList, node1.next, node2); + mergedList.addFirst(node1.item); + return node1; + } + + if (node1.item.compareTo(node2.item) < 0) { // node1 is smaller, so add it and advance the pointer + mergeTwoSortedLists(mergedList, node1.next, node2); + mergedList.addFirst(node1.item); + return node1; + } else if (node1.item.compareTo(node2.item) > 0) { + mergeTwoSortedLists(mergedList, node1, node2.next); + mergedList.addFirst(node2.item); + return node2; + } else { // both nodes are equal so add both + mergeTwoSortedLists(mergedList, node1.next, node2.next); + mergedList.addFirst(node1.item); + mergedList.addFirst(node2.item); + return node1; + } + } + public static void main(String a[]) { SingleLinkedList linkedList1 = new SingleLinkedList<>(); linkedList1.add(00); @@ -72,7 +116,14 @@ public static void main(String a[]) { linkedList2.add(55); linkedList2.add(67); linkedList2.add(89); + linkedList2.add(99); linkedList2.printList(); mergeTwoSortedLists(linkedList1, linkedList2).printList(); + System.out.println("===================="); + linkedList1.printList(); + linkedList2.printList(); + SingleLinkedList mergedList = new SingleLinkedList<>(); + mergeTwoSortedLists(mergedList, linkedList1.head, linkedList2.head); + mergedList.printList(); } } From 1461c5ee32bef199b739a96bdc5c9ae53b3a0b2f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 29 Jun 2015 09:59:12 +0530 Subject: [PATCH 144/417] check identical lists: done --- .../ramswaroop/linkedlists/IsIdentical.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/IsIdentical.java diff --git a/src/me/ramswaroop/linkedlists/IsIdentical.java b/src/me/ramswaroop/linkedlists/IsIdentical.java new file mode 100644 index 00000000..877ec253 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/IsIdentical.java @@ -0,0 +1,69 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/29/15 + * @time: 9:42 AM + */ +public class IsIdentical> extends SingleLinkedList { + + /** + * Returns {@code true} if linked list {@param list1} and {@param list2} + * are identical i.e, the data in the nodes as well as their arrangements are + * similar. Ex: 1->2->3 and 1->2->3 are identical. + * + * @param list1 + * @param list2 + * @param + * @return + */ + public static > boolean isIdentical(SingleLinkedList list1, + SingleLinkedList list2) { + + // base cases + if (list1.size != list2.size) { + return false; + } else if (list1.size == 0 && list2.size == 0) { + return true; + } + + SingleLinkedNode curr1 = list1.getNode(0), curr2 = list2.getNode(0); + + while (curr1 != null && curr2 != null) { + if (!curr1.item.equals(curr2.item)) { + return false; + } + curr1 = curr1.next; + curr2 = curr2.next; + } + + return true; + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.add(66); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(00); + linkedList2.add(11); + linkedList2.add(22); + linkedList2.add(33); + linkedList2.add(44); + linkedList2.add(55); + linkedList2.add(66); + linkedList2.printList(); + System.out.println(isIdentical(linkedList1, linkedList2)); + } +} From 1fc829b903550e994262e20b793296d3a2363cda Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 29 Jun 2015 18:09:00 +0530 Subject: [PATCH 145/417] reverse linked list in groups: done --- .../ReverseLinkedListInGroups.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java diff --git a/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java b/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java new file mode 100644 index 00000000..adaa1ac6 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java @@ -0,0 +1,74 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/29/15 + * @time: 2:32 PM + */ +public class ReverseLinkedListInGroups> extends SingleLinkedList { + + /** + * Reverses the linked list in groups. + * + * Example: + * + * Inputs: 1->2->3->4->5->6->7->8 and k = 3 + * Output: 3->2->1->6->5->4->8->7. + * + * Inputs: 1->2->3->4->5->6->7->8 and k = 5 + * Output: 5->4->3->2->1->8->7->6. + * + * @param node + * @param k + * @return + */ + public SingleLinkedNode reverseLinkedListInGroups(SingleLinkedNode node, int k) { + + SingleLinkedNode curr = node, prev = null, next = null; + int i = 0; + + // reverse the 'next' pointer of nodes + while (curr != null && i < k) { + next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + i++; + } + + // update the head + if (node == head) { + head = prev; + } + + // recursively call for the rest of the nodes in the linked list + if (next != null) { + node.next = reverseLinkedListInGroups(next, k); + } + + return prev; + } + + public static void main(String a[]) { + ReverseLinkedListInGroups linkedList = new ReverseLinkedListInGroups<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.add(88); + linkedList.add(99); + linkedList.add(100); + linkedList.printList(); + linkedList.reverseLinkedListInGroups(linkedList.head, 3); + linkedList.printList(); + } +} From 1019bedc8d20a6827cdb0ea0bf79e275132f7dc3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 29 Jun 2015 18:43:04 +0530 Subject: [PATCH 146/417] insert in sorted list: improved --- ...ortedList.java => InsertInSortedList.java} | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) rename src/me/ramswaroop/linkedlists/{InsertionInSortedList.java => InsertInSortedList.java} (51%) diff --git a/src/me/ramswaroop/linkedlists/InsertionInSortedList.java b/src/me/ramswaroop/linkedlists/InsertInSortedList.java similarity index 51% rename from src/me/ramswaroop/linkedlists/InsertionInSortedList.java rename to src/me/ramswaroop/linkedlists/InsertInSortedList.java index 7e93fc6f..39a6c4d7 100644 --- a/src/me/ramswaroop/linkedlists/InsertionInSortedList.java +++ b/src/me/ramswaroop/linkedlists/InsertInSortedList.java @@ -10,7 +10,7 @@ * @date: 6/21/15 * @time: 10:20 PM */ -public class InsertionInSortedList> extends SingleLinkedList { +public class InsertInSortedList> extends SingleLinkedList { /** * Insert an element in the sorted linked list. @@ -18,24 +18,30 @@ public class InsertionInSortedList> extends SingleLinked * @param item */ public void insert(E item) { - int index = 0; SingleLinkedNode node = head; + while (node != null) { - if (item.compareTo(node.item) < 0) break; - index++; + if (node.item.compareTo(item) > 0) { // new node is to be inserted before head + head = new SingleLinkedNode<>(item, node); + return; + } else if (node.next == null || node.next.item.compareTo(item) > 0) { // new node to be inserted anywhere else + node.next = new SingleLinkedNode<>(item, node.next); + return; + } node = node.next; } - add(index, item); } public static void main(String a[]) { - InsertionInSortedList linkedList = new InsertionInSortedList<>(); + InsertInSortedList linkedList = new InsertInSortedList<>(); linkedList.add(00); linkedList.add(11); linkedList.add(22); linkedList.add(33); linkedList.printList(); - linkedList.insert(13); + linkedList.insert(-2); + linkedList.insert(9); + linkedList.insert(44); linkedList.printList(); } } \ No newline at end of file From a4005c13ca23c47fa8f464739bb4841da8c2ae89 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 30 Jun 2015 00:22:24 +0530 Subject: [PATCH 147/417] insert in sorted circular list: done --- .../linkedlists/CloneWithRandPointers.java | 2 +- .../linkedlists/DeleteAlternateNodes.java | 2 +- src/me/ramswaroop/linkedlists/DeleteNode.java | 2 +- src/me/ramswaroop/linkedlists/DetectLoop.java | 2 +- .../InsertInSortedCircularLinkedList.java | 56 +++++++++++++++++++ .../linkedlists/InsertInSortedList.java | 3 +- .../IntersectionOf2SortedLists.java | 2 +- .../linkedlists/IntersectionOfTwoLists.java | 2 +- .../ramswaroop/linkedlists/IsIdentical.java | 2 +- .../linkedlists/MergeTwoSortedLists.java | 2 +- src/me/ramswaroop/linkedlists/MiddleNode.java | 2 +- .../linkedlists/MoveLastNodeToFirst.java | 2 +- .../linkedlists/NthNodeFromLast.java | 2 +- .../linkedlists/RemoveDuplicates.java | 2 +- .../linkedlists/ReverseDoubleLinkedList.java | 2 +- 15 files changed, 71 insertions(+), 14 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/InsertInSortedCircularLinkedList.java diff --git a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java index a3cba37e..b8490ace 100644 --- a/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java +++ b/src/me/ramswaroop/linkedlists/CloneWithRandPointers.java @@ -11,7 +11,7 @@ * @time: 1:00 PM * @see: http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/ */ -public class CloneWithRandPointers> extends DoubleLinkedList { +public class CloneWithRandPointers { /** * Clones a linked list with next pointer pointing to the diff --git a/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java b/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java index 4fc5124e..0cde7dd1 100644 --- a/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java +++ b/src/me/ramswaroop/linkedlists/DeleteAlternateNodes.java @@ -10,7 +10,7 @@ * @date: 6/27/15 * @time: 5:27 PM */ -public class DeleteAlternateNodes> extends SingleLinkedList { +public class DeleteAlternateNodes { public static > void deleteAlternateNodes(SingleLinkedList list) { deleteAlternateNodes(list.head); diff --git a/src/me/ramswaroop/linkedlists/DeleteNode.java b/src/me/ramswaroop/linkedlists/DeleteNode.java index 9474c767..7f9248f6 100644 --- a/src/me/ramswaroop/linkedlists/DeleteNode.java +++ b/src/me/ramswaroop/linkedlists/DeleteNode.java @@ -10,7 +10,7 @@ * @date: 6/18/15 * @time: 2:35 PM */ -public class DeleteNode> extends SingleLinkedList { +public class DeleteNode { /** * Given a pointer to a node, delete it. diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index e1a750db..400c6849 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -12,7 +12,7 @@ * @date: 6/19/15 * @time: 9:24 AM */ -public class DetectLoop> extends SingleLinkedList { +public class DetectLoop { /** * Uses Flyod's Cycle Finding algorithm. diff --git a/src/me/ramswaroop/linkedlists/InsertInSortedCircularLinkedList.java b/src/me/ramswaroop/linkedlists/InsertInSortedCircularLinkedList.java new file mode 100644 index 00000000..94bad85d --- /dev/null +++ b/src/me/ramswaroop/linkedlists/InsertInSortedCircularLinkedList.java @@ -0,0 +1,56 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.CircularSingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/29/15 + * @time: 6:16 PM + */ +public class InsertInSortedCircularLinkedList> extends CircularSingleLinkedList { + + /** + * Inserts an element in the sorted circular + * linked list maintaining the sorted property. + * + * @param item + */ + public void insert(E item) { + SingleLinkedNode node = head, curr = node; + + do { + if (node.item.compareTo(item) > 0) { // new node is to be inserted before head + // last node should now point to the new head + while (curr.next != head) { + curr = curr.next; + } + head = new SingleLinkedNode<>(item, node); + curr.next = head; + return; + } else if (node.next.item.compareTo(item) > 0) { + node.next = new SingleLinkedNode<>(item, node.next); + return; + } else if (node.next == head) { + node.next = new SingleLinkedNode<>(item, head); + return; + } + node = node.next; + } while (node != head); + } + + public static void main(String a[]) { + InsertInSortedCircularLinkedList linkedList = new InsertInSortedCircularLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.printList(); + linkedList.insert(-2); + linkedList.insert(9); + linkedList.insert(44); + linkedList.printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/InsertInSortedList.java b/src/me/ramswaroop/linkedlists/InsertInSortedList.java index 39a6c4d7..00cd94af 100644 --- a/src/me/ramswaroop/linkedlists/InsertInSortedList.java +++ b/src/me/ramswaroop/linkedlists/InsertInSortedList.java @@ -13,7 +13,8 @@ public class InsertInSortedList> extends SingleLinkedList { /** - * Insert an element in the sorted linked list. + * Inserts an element in the sorted linked + * list maintaining the sorted property. * * @param item */ diff --git a/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java b/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java index 31036b9f..3f591564 100644 --- a/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java +++ b/src/me/ramswaroop/linkedlists/IntersectionOf2SortedLists.java @@ -10,7 +10,7 @@ * @date: 6/27/15 * @time: 11:13 AM */ -public class IntersectionOf2SortedLists> extends SingleLinkedList { +public class IntersectionOf2SortedLists { /** * Returns a linked list with elements common in diff --git a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java b/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java index df2101e3..9dae4518 100644 --- a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java +++ b/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java @@ -10,7 +10,7 @@ * @date: 6/18/15 * @time: 10:34 PM */ -public class IntersectionOfTwoLists> extends SingleLinkedList { +public class IntersectionOfTwoLists { /** diff --git a/src/me/ramswaroop/linkedlists/IsIdentical.java b/src/me/ramswaroop/linkedlists/IsIdentical.java index 877ec253..cc2ceae6 100644 --- a/src/me/ramswaroop/linkedlists/IsIdentical.java +++ b/src/me/ramswaroop/linkedlists/IsIdentical.java @@ -10,7 +10,7 @@ * @date: 6/29/15 * @time: 9:42 AM */ -public class IsIdentical> extends SingleLinkedList { +public class IsIdentical { /** * Returns {@code true} if linked list {@param list1} and {@param list2} diff --git a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java index ecbb235e..7bbc98b5 100644 --- a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java +++ b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java @@ -10,7 +10,7 @@ * @date: 6/27/15 * @time: 8:47 PM */ -public class MergeTwoSortedLists> extends SingleLinkedList { +public class MergeTwoSortedLists { /** * Merges two sorted list {@param list1} and {@param list2} into diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java index 5f0f2d8e..f794e39d 100644 --- a/src/me/ramswaroop/linkedlists/MiddleNode.java +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -10,7 +10,7 @@ * @date: 6/18/15 * @time: 10:34 PM */ -public class MiddleNode> extends SingleLinkedList { +public class MiddleNode { public static > SingleLinkedNode getMiddleNode(SingleLinkedList list) { SingleLinkedNode slow = list.getNode(0); diff --git a/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java b/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java index fe6c07ad..ed4b531f 100644 --- a/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java +++ b/src/me/ramswaroop/linkedlists/MoveLastNodeToFirst.java @@ -10,7 +10,7 @@ * @date: 6/23/15 * @time: 7:52 PM */ -public class MoveLastNodeToFirst> extends SingleLinkedList { +public class MoveLastNodeToFirst { public static > void moveLastNodeToFirst(SingleLinkedList list) { if (list.size <= 1) return; diff --git a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java index 64062092..b86a4194 100644 --- a/src/me/ramswaroop/linkedlists/NthNodeFromLast.java +++ b/src/me/ramswaroop/linkedlists/NthNodeFromLast.java @@ -10,7 +10,7 @@ * @date: 6/18/15 * @time: 6:49 PM */ -public class NthNodeFromLast> extends SingleLinkedList { +public class NthNodeFromLast { public static > SingleLinkedNode getNthNodeFromLast(SingleLinkedList list, int n) { SingleLinkedNode slow = list.getNode(0); diff --git a/src/me/ramswaroop/linkedlists/RemoveDuplicates.java b/src/me/ramswaroop/linkedlists/RemoveDuplicates.java index 297ec8da..c25f364f 100644 --- a/src/me/ramswaroop/linkedlists/RemoveDuplicates.java +++ b/src/me/ramswaroop/linkedlists/RemoveDuplicates.java @@ -13,7 +13,7 @@ * @date: 6/18/15 * @time: 2:35 PM */ -public class RemoveDuplicates> extends SingleLinkedList { +public class RemoveDuplicates { /** * Removes duplicates from a sorted linked list diff --git a/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java b/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java index 32cd0ea9..7608fbd7 100644 --- a/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/ReverseDoubleLinkedList.java @@ -10,7 +10,7 @@ * @date: 6/19/15 * @time: 9:24 AM */ -public class ReverseDoubleLinkedList> extends DoubleLinkedList { +public class ReverseDoubleLinkedList { /** * Reverses the doubly linked list. From ad59490893a811018a3e0e66602f02641d875717 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 30 Jun 2015 16:48:16 +0530 Subject: [PATCH 148/417] reverse list in alternate groups: done --- .../ReverseLinkedListInAlternateGroups.java | 80 +++++++++++++++++++ .../ReverseLinkedListInGroups.java | 2 +- 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java diff --git a/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java b/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java new file mode 100644 index 00000000..1c0e0585 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java @@ -0,0 +1,80 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/30/15 + * @time: 9:33 AM + */ +public class ReverseLinkedListInAlternateGroups> extends SingleLinkedList { + + /** + * Reverses the linked list in groups alternatively. + *

+ * It is similar to {@link me.ramswaroop.linkedlists.ReverseLinkedListInGroups} but + * does alternatively. + *

+ * Example: + * Inputs: 1->2->3->4->5->6->7->8->9 and k = 3 + * Output: 3->2->1->4->5->6->9->8->7. + * + * @param node + * @param k + * @return + */ + public SingleLinkedNode reverseLinkedListInAltGroups(SingleLinkedNode node, int k) { + int i = 0; + SingleLinkedNode curr = node, prev = null, next = null; + + // reverse the 'next' pointer of nodes with help of 3 pointers + while (curr != null && i < k) { + next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + i++; + } + + // update the head + if (node == head) { + head = prev; + } + + if (node != null) node.next = next; + + // move the pointer k steps ahead + i = 1; + while (curr != null && i < k) { + curr = curr.next; + i++; + } + + // recursively call on the next 2k set of nodes + if (curr != null) { + curr.next = reverseLinkedListInAltGroups(curr.next, k); + } + + return prev; + } + + public static void main(String a[]) { + ReverseLinkedListInAlternateGroups linkedList = new ReverseLinkedListInAlternateGroups<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.add(88); + linkedList.add(99); + linkedList.printList(); + linkedList.reverseLinkedListInAltGroups(linkedList.head, 2); + linkedList.printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java b/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java index adaa1ac6..709ae4ce 100644 --- a/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java +++ b/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java @@ -32,7 +32,7 @@ public SingleLinkedNode reverseLinkedListInGroups(SingleLinkedNode node, i SingleLinkedNode curr = node, prev = null, next = null; int i = 0; - // reverse the 'next' pointer of nodes + // reverse the 'next' pointer of nodes with help of 3 pointers while (curr != null && i < k) { next = curr.next; curr.next = prev; From 3612bbc86b78280855b5c91c8b2d131bb8b8b1c8 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 30 Jun 2015 18:36:54 +0530 Subject: [PATCH 149/417] delete lesser nodes: done --- .../linkedlists/DeleteLesserNodes.java | 71 +++++++++++++++++++ .../ReverseLinkedListInAlternateGroups.java | 4 +- .../linkedlists/ReverseSingleLinkedList.java | 6 +- 3 files changed, 75 insertions(+), 6 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/DeleteLesserNodes.java diff --git a/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java b/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java new file mode 100644 index 00000000..86a5a310 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java @@ -0,0 +1,71 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/30/15 + * @time: 5:13 PM + */ +public class DeleteLesserNodes { + + /** + * Delete a node from {@param list} if there are any nodes + * with values greater than node on the right hand side of the list. + * + * Example: + * + * Input: 12->15->10->11->5->6->2->3->NULL + * Output: 15->11->6->3->NULL + * + * Input: 10->20->30->40->50->60->NULL + * Output: 60->NULL + * + * Input: 60->50->40->30->20->10->NULL + * Output: 60->50->40->30->20->10->NULL + * + * @param list + * @param + */ + public static > void deleteLesserNodes(SingleLinkedList list) { + + // reverse the list + ReverseSingleLinkedList.reverseList(list); + + E max; + SingleLinkedNode curr = list.getNode(0), prev = curr; + + max = curr.item; + + while (curr != null) { + if (curr.item.compareTo(max) >= 0) { + max = curr.item; + prev = curr; + } else { + prev.next = curr.next; + } + + curr = curr.next; + } + + // reverse the list + ReverseSingleLinkedList.reverseList(list); + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.printList(); + deleteLesserNodes(linkedList); + linkedList.printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java b/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java index 1c0e0585..58e3b766 100644 --- a/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java +++ b/src/me/ramswaroop/linkedlists/ReverseLinkedListInAlternateGroups.java @@ -20,7 +20,7 @@ public class ReverseLinkedListInAlternateGroups> extends *

* Example: * Inputs: 1->2->3->4->5->6->7->8->9 and k = 3 - * Output: 3->2->1->4->5->6->9->8->7. + * Output: 3->2->1->4->5->6->9->8->7 * * @param node * @param k @@ -53,7 +53,7 @@ public SingleLinkedNode reverseLinkedListInAltGroups(SingleLinkedNode node i++; } - // recursively call on the next 2k set of nodes + // recursively call on the next set of nodes if (curr != null) { curr.next = reverseLinkedListInAltGroups(curr.next, k); } diff --git a/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java b/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java index c2a6911d..5728fcd2 100644 --- a/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java @@ -18,11 +18,9 @@ public class ReverseSingleLinkedList> extends SingleLink * @param list */ public static > void reverseList(SingleLinkedList list) { - SingleLinkedNode prev = list.getNode(0); - SingleLinkedNode curr = prev.next; - prev.next = null; // this will be the last node after reversal, so make next of node = null + SingleLinkedNode curr = list.getNode(0), prev = null, next; while (curr != null) { - SingleLinkedNode next = curr.next; + next = curr.next; curr.next = prev; prev = curr; curr = next; From 676fddf33f90fac50745b4ac41510053588ea25b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 30 Jun 2015 22:28:41 +0530 Subject: [PATCH 150/417] delete lesser nodes: done (recursive version) --- .../common/CircularSingleLinkedList.java | 6 ++- .../ramswaroop/common/DoubleLinkedList.java | 6 ++- .../ramswaroop/common/SingleLinkedList.java | 6 ++- .../linkedlists/DeleteLesserNodes.java | 38 +++++++++++++++++-- 4 files changed, 49 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/common/CircularSingleLinkedList.java b/src/me/ramswaroop/common/CircularSingleLinkedList.java index 4e4e3723..a496d347 100644 --- a/src/me/ramswaroop/common/CircularSingleLinkedList.java +++ b/src/me/ramswaroop/common/CircularSingleLinkedList.java @@ -181,7 +181,11 @@ public int size() { @Override public void printList() { - SingleLinkedNode curr = head; + printList(head); + } + + public void printList(SingleLinkedNode node) { + SingleLinkedNode curr = node; out.print("["); if (curr == null) { out.println("]"); diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index 3a2961d8..a5da9e52 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -175,7 +175,11 @@ public int size() { @Override public void printList() { - DoubleLinkedNode curr = head; + printList(head); + } + + public void printList(DoubleLinkedNode node) { + DoubleLinkedNode curr = node; out.print("["); if (curr == null) { out.println("]"); diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index ba5e4a51..35465f42 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -161,7 +161,11 @@ public int size() { @Override public void printList() { - SingleLinkedNode curr = head; + printList(head); + } + + public void printList(SingleLinkedNode node) { + SingleLinkedNode curr = node; out.print("["); if (curr == null) { out.println("]"); diff --git a/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java b/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java index 86a5a310..45edc0ab 100644 --- a/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java +++ b/src/me/ramswaroop/linkedlists/DeleteLesserNodes.java @@ -15,15 +15,15 @@ public class DeleteLesserNodes { /** * Delete a node from {@param list} if there are any nodes * with values greater than node on the right hand side of the list. - * + *

* Example: - * + *

* Input: 12->15->10->11->5->6->2->3->NULL * Output: 15->11->6->3->NULL - * + *

* Input: 10->20->30->40->50->60->NULL * Output: 60->NULL - * + *

* Input: 60->50->40->30->20->10->NULL * Output: 60->50->40->30->20->10->NULL * @@ -55,6 +55,27 @@ public static > void deleteLesserNodes(SingleLinkedList< ReverseSingleLinkedList.reverseList(list); } + + /** + * Recursive version of {@link #deleteLesserNodes(me.ramswaroop.common.SingleLinkedList)}. + * + * @param node + * @param + * @return + */ + public static > SingleLinkedNode deleteLesserNodes(SingleLinkedNode node) { + if (node == null) return null; + + SingleLinkedNode next = deleteLesserNodes(node.next); + node.next = next; + + if (next != null && node.item.compareTo(next.item) < 0) { + return next; + } else { + return node; + } + } + public static void main(String a[]) { SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); @@ -67,5 +88,14 @@ public static void main(String a[]) { linkedList.printList(); deleteLesserNodes(linkedList); linkedList.printList(); + // for recursive version + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.printList(); + linkedList.printList(deleteLesserNodes(linkedList.head)); } } From 8e8424edc3a5c35041126a9d3714030aa40c387c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 1 Jul 2015 12:26:56 +0530 Subject: [PATCH 151/417] segregate even odd valued nodes: done --- .../linkedlists/SegregateEvenOddNumbers.java | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java diff --git a/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java b/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java new file mode 100644 index 00000000..61ccb58b --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java @@ -0,0 +1,85 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/30/15 + * @time: 10:32 PM + */ +public class SegregateEvenOddNumbers { + + /** + * Modifies the linked list such that all even numbers appear + * before all the odd numbers in the linked list. + *

+ * Algorithm: + * ---------- + * 1) Make a pointer point the last node of the list. + *

+ * 2) Traverse the linked list from start and append all odd values + * nodes to the end the above pointer. + *

+ * 3) If the pointer in step 1 points to a odd valued node then move it + * to the end so that the relative order of nodes remains unchanged. + * + * @param list + * @param + */ + public static > void segregateEvenOddNumbers(SingleLinkedList list) { + SingleLinkedNode curr = list.head, prev = null, end = curr, separator; + + // a pointer to the last node + while (end.next != null) { + end = end.next; + } + separator = end; + + // move all odd valued nodes after the end node + while (curr != separator) { + if (Integer.parseInt(curr.item.toString()) % 2 != 0) { + end.next = curr; + curr = curr.next; + end = end.next; + end.next = null; + if (curr == list.head) { + list.head = curr; + } else { + prev.next = curr; + } + } else { + prev = curr; + curr = curr.next; + } + } + + // if separator is odd valued then move it to the end (if its not already in the end) + if (Integer.parseInt(separator.item.toString()) % 2 != 0 && separator.next != null) { + prev.next = curr.next; + while (curr.next != null) { + curr = curr.next; + } + curr.next = separator; + separator.next = null; + } + + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.printList(); + segregateEvenOddNumbers(linkedList); + linkedList.printList(); + } +} From 296eff2ae16944d8b0d80bb07df6730d8942cbda Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 2 Jul 2015 13:01:35 +0530 Subject: [PATCH 152/417] detect and remove loop: done --- .../linkedlists/DetectAndRemoveLoop.java | 85 +++++++++++++++++++ src/me/ramswaroop/linkedlists/DetectLoop.java | 13 ++- src/me/ramswaroop/practice/Threads.java | 4 + 3 files changed, 95 insertions(+), 7 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/DetectAndRemoveLoop.java diff --git a/src/me/ramswaroop/linkedlists/DetectAndRemoveLoop.java b/src/me/ramswaroop/linkedlists/DetectAndRemoveLoop.java new file mode 100644 index 00000000..e180d455 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DetectAndRemoveLoop.java @@ -0,0 +1,85 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/1/15 + * @time: 12:39 PM + */ +public class DetectAndRemoveLoop { + + /** + * Detects loop if any in {@param list} and removes it. + * + * Algorithm: + * + * 1) Use Floyd's cycle detection algorithm to detect loop. + * 2) Acc. to FCD, once the fast pointer meets the slow pointer we conclude that there is a loop. + * 3) Now compute the length 'l' of the loop. + * 4) Move the fast pointer length 'l' from head. + * 5) Now move both slow and fast pointer at same pace and where they meet is the starting point of the loop. + * 6) Lastly, to remove the loop make the next of the node (before the starting point of loop) to null. + * + * @param list + * @param + * @return {@code true} if loop exists {@code false} otherwise. + */ + public static > boolean detectAndRemoveLoop(SingleLinkedList list) { + int i = 0, length = 0; + boolean isLoopPresent = false; + SingleLinkedNode slow = list.head, fast = slow.next; + + while (fast != null && fast.next != null) { + if (slow == fast) { + isLoopPresent = true; + break; + } + slow = slow.next; + fast = fast.next.next; + } + + if (isLoopPresent == false) return false; + + // compute length of loop + while (fast.next != slow) { + fast = fast.next; + length++; + } + + // move fast pointer from head by the length of loop + slow = fast = list.head; + while (i <= length) { + fast = fast.next; + i++; + } + + // move both pointers at same pace to determine the starting node of loop + while (true) { + slow = slow.next; + fast = fast.next; + if (slow.next == fast.next) { + fast.next = null; + break; + } + } + + return isLoopPresent; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.getNode(1).next = linkedList.getNode(0); + System.out.println(detectAndRemoveLoop(linkedList)); + linkedList.printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/DetectLoop.java b/src/me/ramswaroop/linkedlists/DetectLoop.java index 400c6849..f2063f07 100644 --- a/src/me/ramswaroop/linkedlists/DetectLoop.java +++ b/src/me/ramswaroop/linkedlists/DetectLoop.java @@ -23,7 +23,7 @@ public class DetectLoop { * If these pointers meet at some node then * there is a loop. If pointers do not meet * then linked list does not have loop. - * + *

* Time: O(n) * Space: O(1) * @@ -31,14 +31,13 @@ public class DetectLoop { * @return */ public static > boolean isLoopPresent(SingleLinkedList list) { - SingleLinkedNode firstNode = list.getNode(0); - SingleLinkedNode prev = firstNode, curr = firstNode; - while (curr != null && curr.next != null) { - prev = prev.next; - curr = curr.next.next; - if (prev == curr) { + SingleLinkedNode slow = list.head, fast = slow.next; + while (fast != null && fast.next != null) { + if (slow == fast) { return true; } + slow = slow.next; + fast = fast.next.next; } return false; } diff --git a/src/me/ramswaroop/practice/Threads.java b/src/me/ramswaroop/practice/Threads.java index 4638fe95..ec54b347 100644 --- a/src/me/ramswaroop/practice/Threads.java +++ b/src/me/ramswaroop/practice/Threads.java @@ -27,6 +27,10 @@ public void run() { Thread t2 = new Thread(r); Thread t3 = new Thread(r); + t1.setName("T1"); + t2.setName("T2"); + t3.setName("T3"); + t1.start(); t2.start(); t3.start(); From e3d25e3a19d8489be161a42aaf85e2830bc13041 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 2 Jul 2015 15:14:38 +0530 Subject: [PATCH 153/417] add two no.s represented by lists: done --- .../linkedlists/AddNumbersInTwoLists.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java diff --git a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java new file mode 100644 index 00000000..c46da1a2 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java @@ -0,0 +1,79 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/2/15 + * @time: 1:20 PM + */ +public class AddNumbersInTwoLists { + + /** + * Adds two numbers represented by two linked lists {@param list1} + * and {@param list2} and stores them in another list. + *

+ * Example: + *

+ * Input: + * First List: 5->6->3 // represents number 365 + * Second List: 8->4->2 // represents number 248 + * Output: + * Resultant list: 3->1->6 // represents number 613 + *

+ * Input: + * First List: 7->5->9->4->6 // represents number 64957 + * Second List: 8->4 // represents number 48 + * Output: + * Resultant list: 5->0->0->5->6 // represents number 65005 + * + * @param list1 + * @param list2 + * @return list containing the sum of numbers in {@param list1} and {@param list2}. + */ + public static SingleLinkedList add(SingleLinkedList list1, + SingleLinkedList list2) { + + int sum, carry = 0; + SingleLinkedNode curr1 = list1.head, curr2 = list2.head; + SingleLinkedList resultList = new SingleLinkedList<>(); + + // loop till both of the list runs out + while (curr1 != null || curr2 != null) { + + // if either of the list runs out first + int a = (curr1 != null) ? curr1.item : 0; + int b = (curr2 != null) ? curr2.item : 0; + + sum = (a + b + carry) % 10; + carry = (a + b + carry) / 10; + resultList.add(sum); + + if (curr1 != null) curr1 = curr1.next; + if (curr2 != null) curr2 = curr2.next; + } + + // if there is any carry left over, add it to the result + if (carry != 0) resultList.addFirst(carry); + + return resultList; + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(7); + linkedList1.add(5); + linkedList1.add(9); + linkedList1.add(4); + linkedList1.add(6); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(8); + linkedList2.add(4); + linkedList2.printList(); + add(linkedList1, linkedList2).printList(); + } +} From 635eacba81bfa9088921cd82624bc2aa09517e74 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 3 Jul 2015 15:35:57 +0530 Subject: [PATCH 154/417] rotate linked list: done --- .../linkedlists/AddNumbersInTwoLists.java | 7 +- .../linkedlists/RotateLinkedList.java | 77 +++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/RotateLinkedList.java diff --git a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java index c46da1a2..6719513c 100644 --- a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java +++ b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java @@ -14,19 +14,20 @@ public class AddNumbersInTwoLists { /** * Adds two numbers represented by two linked lists {@param list1} - * and {@param list2} and stores them in another list. + * and {@param list2} (where first node is the least significant + * digit) and stores them in another list. *

* Example: *

* Input: * First List: 5->6->3 // represents number 365 - * Second List: 8->4->2 // represents number 248 + * Second List: 8->4->2 // represents number 248 * Output: * Resultant list: 3->1->6 // represents number 613 *

* Input: * First List: 7->5->9->4->6 // represents number 64957 - * Second List: 8->4 // represents number 48 + * Second List: 8->4 // represents number 48 * Output: * Resultant list: 5->0->0->5->6 // represents number 65005 * diff --git a/src/me/ramswaroop/linkedlists/RotateLinkedList.java b/src/me/ramswaroop/linkedlists/RotateLinkedList.java new file mode 100644 index 00000000..d40efa15 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/RotateLinkedList.java @@ -0,0 +1,77 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/3/15 + * @time: 3:07 PM + */ +public class RotateLinkedList { + + /** + * Rotates the {@param list} anti-clockwise by {@param k} nodes. + * + * @param list + * @param k + * @param + */ + public static > void rotateCounterClockwise(SingleLinkedList list, int k) { + int clockwiseK = list.size - k; + rotateClockwise(list, clockwiseK); + } + + + /** + * Rotates the {@param list} clockwise by {@param k} nodes. + * + * Example, + * + * Input: [0,11,22,33,44,55] and k =2 + * Output: [22,33,44,55,0,11] + * + * @param list + * @param k + * @param + */ + public static > void rotateClockwise(SingleLinkedList list, int k) { + int i = 0; + SingleLinkedNode curr = list.head, end = curr; + + // get a pointer to the last node + while (end.next != null) { + end = end.next; + } + + // start moving first k nodes from start to end + while (i < k && k < list.size) { + end.next = curr; + end = end.next; + curr = curr.next; + i++; + } + + // change head to k+1 node + list.head = curr; + end.next = null; + + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.printList(); + rotateClockwise(linkedList, 2); + linkedList.printList(); + rotateCounterClockwise(linkedList, 2); + linkedList.printList(); + } +} From bbff89ffd1290cdc1c0e789c445da2a2da2ec622 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 5 Jul 2015 00:02:49 +0530 Subject: [PATCH 155/417] add nos in linked list: modified --- src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java index 6719513c..995e7768 100644 --- a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java +++ b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java @@ -63,6 +63,11 @@ public static SingleLinkedList add(SingleLinkedList list1, return resultList; } + public static SingleLinkedList add_V1(SingleLinkedList list1, + SingleLinkedList list2) { + return null; + } + public static void main(String a[]) { SingleLinkedList linkedList1 = new SingleLinkedList<>(); linkedList1.add(7); From 254afa7ad1bb7d4d0192bd053d7cc6e174ad6fd2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 4 Jul 2015 18:21:46 +0530 Subject: [PATCH 156/417] add nos in linked list: modified --- src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java index 6719513c..995e7768 100644 --- a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java +++ b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java @@ -63,6 +63,11 @@ public static SingleLinkedList add(SingleLinkedList list1, return resultList; } + public static SingleLinkedList add_V1(SingleLinkedList list1, + SingleLinkedList list2) { + return null; + } + public static void main(String a[]) { SingleLinkedList linkedList1 = new SingleLinkedList<>(); linkedList1.add(7); From 70127c7a40fa9b7e5dd334e36ffe07767e0731a6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 5 Jul 2015 00:29:22 +0530 Subject: [PATCH 157/417] add nos in linked list: to be done --- .../linkedlists/AddNumbersInTwoLists.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java index 995e7768..0ac5069b 100644 --- a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java +++ b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java @@ -63,6 +63,29 @@ public static SingleLinkedList add(SingleLinkedList list1, return resultList; } + /** + * Adds two numbers represented by two linked lists {@param list1} + * and {@param list2} (where first node is the most significant + * digit) and stores them in another list. + *

+ * Example: + *

+ * Input: + * First List: 5->6->3 // represents number 563 + * Second List: 8->4->2 // represents number 842 + * Output: + * Resultant list: 1->4->0->5 // represents number 1405 + *

+ * Input: + * First List: 7->5->9->4->6 // represents number 75946 + * Second List: 8->4 // represents number 84 + * Output: + * Resultant list: 7->6->0->3->0 // represents number 76030 + * + * @param list1 + * @param list2 + * @return + */ public static SingleLinkedList add_V1(SingleLinkedList list1, SingleLinkedList list2) { return null; From 51255c8c3fce2555e209173e6de1d23ac035ceb4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 5 Jul 2015 00:43:49 +0530 Subject: [PATCH 158/417] add nos in linked list (node 1 as MSD): done --- .../linkedlists/AddNumbersInTwoLists.java | 20 +++++++++++++------ .../linkedlists/RotateLinkedList.java | 6 +++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java index 0ac5069b..5abf935f 100644 --- a/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java +++ b/src/me/ramswaroop/linkedlists/AddNumbersInTwoLists.java @@ -35,8 +35,8 @@ public class AddNumbersInTwoLists { * @param list2 * @return list containing the sum of numbers in {@param list1} and {@param list2}. */ - public static SingleLinkedList add(SingleLinkedList list1, - SingleLinkedList list2) { + public static SingleLinkedList addWithNode1LSD(SingleLinkedList list1, + SingleLinkedList list2) { int sum, carry = 0; SingleLinkedNode curr1 = list1.head, curr2 = list2.head; @@ -86,9 +86,16 @@ public static SingleLinkedList add(SingleLinkedList list1, * @param list2 * @return */ - public static SingleLinkedList add_V1(SingleLinkedList list1, - SingleLinkedList list2) { - return null; + public static SingleLinkedList addWithNode1MSD(SingleLinkedList list1, + SingleLinkedList list2) { + ReverseSingleLinkedList.reverseList(list1); + ReverseSingleLinkedList.reverseList(list2); + + SingleLinkedList resultList = addWithNode1LSD(list1, list2); + + ReverseSingleLinkedList.reverseList(resultList); + + return resultList; } public static void main(String a[]) { @@ -103,6 +110,7 @@ public static void main(String a[]) { linkedList2.add(8); linkedList2.add(4); linkedList2.printList(); - add(linkedList1, linkedList2).printList(); + addWithNode1LSD(linkedList1, linkedList2).printList(); + addWithNode1MSD(linkedList1, linkedList2).printList(); } } diff --git a/src/me/ramswaroop/linkedlists/RotateLinkedList.java b/src/me/ramswaroop/linkedlists/RotateLinkedList.java index d40efa15..8bbdbe84 100644 --- a/src/me/ramswaroop/linkedlists/RotateLinkedList.java +++ b/src/me/ramswaroop/linkedlists/RotateLinkedList.java @@ -27,10 +27,10 @@ public static > void rotateCounterClockwise(SingleLinked /** * Rotates the {@param list} clockwise by {@param k} nodes. - * + *

* Example, - * - * Input: [0,11,22,33,44,55] and k =2 + *

+ * Input: [0,11,22,33,44,55] and k = 2 * Output: [22,33,44,55,0,11] * * @param list From b25982e364db714bf6ec34af15c295e4ec7afa6b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 5 Jul 2015 13:59:49 +0530 Subject: [PATCH 159/417] sort a linked list of 0s 1s and 2s: done --- .../linkedlists/SortLinkedListOf0s1s2s.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/SortLinkedListOf0s1s2s.java diff --git a/src/me/ramswaroop/linkedlists/SortLinkedListOf0s1s2s.java b/src/me/ramswaroop/linkedlists/SortLinkedListOf0s1s2s.java new file mode 100644 index 00000000..c1dc3a9e --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SortLinkedListOf0s1s2s.java @@ -0,0 +1,55 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/5/15 + * @time: 1:47 PM + */ +public class SortLinkedListOf0s1s2s { + + /** + * Sorts {@param list} consisting of only 0s, 1s and 2s as their node values. + *

+ * Time complexity: O(n) + * Space complexity: O(1) + * + * @param list + */ + public static void sort(SingleLinkedList list) { + int[] count = new int[3]; + SingleLinkedNode curr = list.head; + + // keep count of 0s, 1s and 2s + while (curr != null) { + count[curr.item]++; + curr = curr.next; + } + + // make a linked list of that many 0s, 1s and 2s + list.clear(); + for (int i = 0; i < count.length; i++) { + for (int j = 0; j < count[i]; j++) { + list.add(i); + } + } + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(0); + linkedList.add(1); + linkedList.add(2); + linkedList.add(0); + linkedList.add(1); + linkedList.add(2); + linkedList.add(1); + linkedList.printList(); + sort(linkedList); + linkedList.printList(); + } +} From b8a7126ff271ce99bb111d663e1e85e803edc576 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 5 Jul 2015 14:39:22 +0530 Subject: [PATCH 160/417] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f22212d9..5a408201 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Algorithms and Data Structures in Java -The repo consists of solutions to various problems invloving different data structures and algorithms. All solutions are coded in Java. +The repo consists of solutions to numerous problems invloving different data structures and algorithms. All solutions are coded in Java. ## Environment From 26e5144bc20899f90d89366bed50217d1c3fa06f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 6 Jul 2015 20:10:41 +0530 Subject: [PATCH 161/417] delete n nodes after every m nodes: done --- .../linkedlists/DeleteMnodesAfterNnodes.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/DeleteMnodesAfterNnodes.java diff --git a/src/me/ramswaroop/linkedlists/DeleteMnodesAfterNnodes.java b/src/me/ramswaroop/linkedlists/DeleteMnodesAfterNnodes.java new file mode 100644 index 00000000..991139e5 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/DeleteMnodesAfterNnodes.java @@ -0,0 +1,67 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/6/15 + * @time: 7:43 PM + */ +public class DeleteMnodesAfterNnodes { + + /** + * Deletes {@param n} nodes after every {@param m} nodes in {@param list} + * till it reaches the end of {@param list}. + * + * @param list + * @param m + * @param n + * @param + */ + public static > void deleteMnodesAfterNnodes(SingleLinkedList list, + int m, int n) { + + SingleLinkedNode curr1 = list.head, curr2; + + while (curr1 != null) { + + // skip m nodes + for (int i = 1; curr1.next != null && i < m; i++) { + curr1 = curr1.next; + } + + // delete n nodes + curr2 = curr1; + for (int i = 0; curr2 != null && i <= n; i++) { + curr2 = curr2.next; + } + curr1.next = curr2; + + curr1 = curr1.next; + } + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(7); + linkedList.add(5); + linkedList.add(9); + linkedList.add(4); + linkedList.add(6); + linkedList.add(1); + linkedList.add(2); + linkedList.add(7); + linkedList.add(5); + linkedList.add(9); + linkedList.add(4); + linkedList.add(6); + linkedList.add(1); + linkedList.add(2); + linkedList.printList(); + deleteMnodesAfterNnodes(linkedList, 3, 2); + linkedList.printList(); + } +} From 5bb2fd2a33c30b98c6622e80f405f5f1f6199b6a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 7 Jul 2015 13:03:40 +0530 Subject: [PATCH 162/417] code refactoring --- ...woLists.java => IntersectionPointOfTwoLists.java} | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) rename src/me/ramswaroop/linkedlists/{IntersectionOfTwoLists.java => IntersectionPointOfTwoLists.java} (89%) diff --git a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java b/src/me/ramswaroop/linkedlists/IntersectionPointOfTwoLists.java similarity index 89% rename from src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java rename to src/me/ramswaroop/linkedlists/IntersectionPointOfTwoLists.java index 9dae4518..c2276c20 100644 --- a/src/me/ramswaroop/linkedlists/IntersectionOfTwoLists.java +++ b/src/me/ramswaroop/linkedlists/IntersectionPointOfTwoLists.java @@ -10,7 +10,7 @@ * @date: 6/18/15 * @time: 10:34 PM */ -public class IntersectionOfTwoLists { +public class IntersectionPointOfTwoLists { /** @@ -29,11 +29,11 @@ public static > SingleLinkedNode getIntersectionNode( // forward the pointer in the longer list by their diff. in length if (list1.size > list2.size) { - curr1 = list1.getNode(0); - curr2 = list2.getNode(0); + curr1 = list1.head; + curr2 = list2.head; } else { - curr1 = list2.getNode(0); - curr2 = list1.getNode(0); + curr1 = list2.head; + curr2 = list1.head; } while (diffLength > 0) { curr1 = curr1.next; @@ -68,7 +68,7 @@ public static void main(String a[]) { linkedList2.add(45); linkedList2.add(23); linkedList2.getNode(3).next = linkedList1.getNode(5); // join 2 lists at some point - linkedList2.size = 8; // update size after joining + linkedList2.size = 8; // IMP: update size after joining System.out.println(getIntersectionNode(linkedList1, linkedList2) != null ? getIntersectionNode(linkedList1, linkedList2).item : "List don't intersect!"); } From 3252c5f6e9333c37b3c1789306c8bce84588bab4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 7 Jul 2015 19:01:01 +0530 Subject: [PATCH 163/417] merge sort in linked list: done --- .../ramswaroop/common/DoubleLinkedList.java | 2 +- .../ramswaroop/common/SingleLinkedList.java | 2 +- .../IntersectionAndUnionOf2Lists.java | 42 +++++++ src/me/ramswaroop/linkedlists/MergeSort.java | 114 ++++++++++++++++++ .../linkedlists/MergeTwoSortedLists.java | 15 +-- src/me/ramswaroop/linkedlists/MiddleNode.java | 3 +- 6 files changed, 164 insertions(+), 14 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java create mode 100644 src/me/ramswaroop/linkedlists/MergeSort.java diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index a5da9e52..d3f456ef 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -178,7 +178,7 @@ public void printList() { printList(head); } - public void printList(DoubleLinkedNode node) { + public static > void printList(DoubleLinkedNode node) { DoubleLinkedNode curr = node; out.print("["); if (curr == null) { diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index 35465f42..829b2397 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -164,7 +164,7 @@ public void printList() { printList(head); } - public void printList(SingleLinkedNode node) { + public static > void printList(SingleLinkedNode node) { SingleLinkedNode curr = node; out.print("["); if (curr == null) { diff --git a/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java b/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java new file mode 100644 index 00000000..0f80ead5 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java @@ -0,0 +1,42 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/7/15 + * @time: 1:04 PM + */ +public class IntersectionAndUnionOf2Lists { + + public static > SingleLinkedList[] getIntersectionAndUnion(SingleLinkedList list1, + SingleLinkedList list2) { + + + + return null; + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(21); + linkedList2.add(33); + linkedList2.add(44); + linkedList2.add(55); + linkedList2.add(67); + linkedList2.add(89); + linkedList2.printList(); + getIntersectionAndUnion(linkedList1, linkedList2)[0].printList(); + getIntersectionAndUnion(linkedList1, linkedList2)[1].printList(); + } +} diff --git a/src/me/ramswaroop/linkedlists/MergeSort.java b/src/me/ramswaroop/linkedlists/MergeSort.java new file mode 100644 index 00000000..38b13d6a --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MergeSort.java @@ -0,0 +1,114 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/7/15 + * @time: 4:34 PM + */ +public class MergeSort { + + public static > SingleLinkedNode mergeSort(SingleLinkedNode node) { + if (node == null || node.next == null) return null; + + SingleLinkedNode middleNode = divideInTwoHalves(node); + + mergeSort(node); + mergeSort(middleNode); + + return mergeTwoSortedLists(node, middleNode); + + } + + + public static > SingleLinkedNode divideInTwoHalves(SingleLinkedNode node) { + SingleLinkedNode slow = node, fast = node, prev = slow; + + if (node == null || node.next == null) { + return null; + } + + while (fast != null && fast.next != null) { + prev = slow; + slow = slow.next; + fast = fast.next.next; + } + prev.next = null; + return slow; + } + + /** + * Merges two sorted lists starting at {@param node1} and {@param node2} + * into one and returns its {@code head} reference. + * + * @param node1 + * @param node2 + * @param + * @return + */ + public static > SingleLinkedNode mergeTwoSortedLists(SingleLinkedNode node1, + SingleLinkedNode node2) { + SingleLinkedNode curr1 = node1, curr2 = node2, head, curr; + + if (node1 == null && node2 == null) return null; + + if (node1 == null) { + head = node2; + curr2 = curr2.next; + } else if (node2 == null) { + head = node1; + curr1 = curr1.next; + } else if (node1.item.compareTo(node2.item) < 0) { + head = node1; + curr1 = curr1.next; + } else { + head = node2; + curr2 = curr2.next; + } + + curr = head; + while (curr1 != null || curr2 != null) { + // handle cases where either of the list run out first + if (curr1 == null) { + curr.next = curr2; + curr2 = curr2.next; + } else if (curr2 == null) { + curr.next = curr1; + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) < 0) { // advance the current pointer of the + // list having smaller {@code item} + curr.next = curr1; + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) > 0) { + curr.next = curr2; + curr2 = curr2.next; + } else { // both nodes are equal so add both to the result + curr.next = curr1; + curr = curr.next; + curr1 = curr1.next; + curr.next = curr2; + curr2 = curr2.next; + } + + curr = curr.next; + } + + return head; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(33); + linkedList.add(21); + linkedList.add(89); + linkedList.add(55); + linkedList.add(44); + linkedList.add(67); + linkedList.printList(); + linkedList.printList(mergeSort(linkedList.head)); + } +} diff --git a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java index 7bbc98b5..aaf3c235 100644 --- a/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java +++ b/src/me/ramswaroop/linkedlists/MergeTwoSortedLists.java @@ -23,23 +23,18 @@ public class MergeTwoSortedLists { */ public static > SingleLinkedList mergeTwoSortedLists(SingleLinkedList list1, SingleLinkedList list2) { - SingleLinkedNode curr1 = list1.getNode(0), curr2 = list2.getNode(0); + SingleLinkedNode curr1 = list1.head, curr2 = list2.head; SingleLinkedList intersectedList = new SingleLinkedList<>(); while (curr1 != null || curr2 != null) { // handle cases where either of the list run out first if (curr1 == null) { intersectedList.add(curr2.item); curr2 = curr2.next; - continue; - } - if (curr2 == null) { + } else if (curr2 == null) { intersectedList.add(curr1.item); curr1 = curr1.next; - continue; - } - - // advance the current pointer of the list having smaller {@code item} - if (curr1.item.compareTo(curr2.item) < 0) { + } else if (curr1.item.compareTo(curr2.item) < 0) { // advance the current pointer of + // the list having smaller {@code item} intersectedList.add(curr1.item); curr1 = curr1.next; } else if (curr1.item.compareTo(curr2.item) > 0) { @@ -58,7 +53,7 @@ public static > SingleLinkedList mergeTwoSortedLists( /** * Recursive method to merge two sorted lists into one sorted list. - * + *

* NOTE: You can make {@param mergedList} as static and not pass as params * to this method. * diff --git a/src/me/ramswaroop/linkedlists/MiddleNode.java b/src/me/ramswaroop/linkedlists/MiddleNode.java index f794e39d..1a8a07af 100644 --- a/src/me/ramswaroop/linkedlists/MiddleNode.java +++ b/src/me/ramswaroop/linkedlists/MiddleNode.java @@ -13,8 +13,7 @@ public class MiddleNode { public static > SingleLinkedNode getMiddleNode(SingleLinkedList list) { - SingleLinkedNode slow = list.getNode(0); - SingleLinkedNode fast = list.getNode(0); + SingleLinkedNode slow = list.head, fast = list.head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; From 6a77d0dbe367908874b59a25c502644c4f0513b6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 8 Jul 2015 12:52:09 +0530 Subject: [PATCH 164/417] merge sort in linked list: done --- src/me/ramswaroop/linkedlists/MergeSort.java | 29 ++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/MergeSort.java b/src/me/ramswaroop/linkedlists/MergeSort.java index 38b13d6a..71bb0802 100644 --- a/src/me/ramswaroop/linkedlists/MergeSort.java +++ b/src/me/ramswaroop/linkedlists/MergeSort.java @@ -12,19 +12,36 @@ */ public class MergeSort { + /** + * Merge sort for linked list starting at {@param node}. + * + * @param node + * @param + * @return + */ public static > SingleLinkedNode mergeSort(SingleLinkedNode node) { - if (node == null || node.next == null) return null; + if (node == null || node.next == null) return node; + + SingleLinkedNode middleNode, head1, head2; - SingleLinkedNode middleNode = divideInTwoHalves(node); + middleNode = divideInTwoHalves(node); - mergeSort(node); - mergeSort(middleNode); + head1 = mergeSort(node); + head2 = mergeSort(middleNode); - return mergeTwoSortedLists(node, middleNode); + return mergeTwoSortedLists(head1, head2); } + /** + * Divides a linked list starting from {@param node} into 2 halves + * and returns the starting {@code node} of the second half. + * + * @param node + * @param + * @return + */ public static > SingleLinkedNode divideInTwoHalves(SingleLinkedNode node) { SingleLinkedNode slow = node, fast = node, prev = slow; @@ -44,6 +61,8 @@ public static > SingleLinkedNode divideInTwoHalves(Si /** * Merges two sorted lists starting at {@param node1} and {@param node2} * into one and returns its {@code head} reference. + *

+ * This method is similar to {@link me.ramswaroop.linkedlists.MergeTwoSortedLists#mergeTwoSortedLists} * * @param node1 * @param node2 From c2badc3fed90c9120f4db6d3e84d78c308365bc7 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 8 Jul 2015 14:24:38 +0530 Subject: [PATCH 165/417] merge sort in linked list: optimized --- src/me/ramswaroop/linkedlists/MergeSort.java | 24 +++++--------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/MergeSort.java b/src/me/ramswaroop/linkedlists/MergeSort.java index 71bb0802..6b9c618e 100644 --- a/src/me/ramswaroop/linkedlists/MergeSort.java +++ b/src/me/ramswaroop/linkedlists/MergeSort.java @@ -58,9 +58,10 @@ public static > SingleLinkedNode divideInTwoHalves(Si return slow; } + /** * Merges two sorted lists starting at {@param node1} and {@param node2} - * into one and returns its {@code head} reference. + * into one and returns its starting node. *

* This method is similar to {@link me.ramswaroop.linkedlists.MergeTwoSortedLists#mergeTwoSortedLists} * @@ -75,21 +76,8 @@ public static > SingleLinkedNode mergeTwoSortedLists( if (node1 == null && node2 == null) return null; - if (node1 == null) { - head = node2; - curr2 = curr2.next; - } else if (node2 == null) { - head = node1; - curr1 = curr1.next; - } else if (node1.item.compareTo(node2.item) < 0) { - head = node1; - curr1 = curr1.next; - } else { - head = node2; - curr2 = curr2.next; - } + head = curr = new SingleLinkedNode<>(null); // dummy node - curr = head; while (curr1 != null || curr2 != null) { // handle cases where either of the list run out first if (curr1 == null) { @@ -116,15 +104,15 @@ public static > SingleLinkedNode mergeTwoSortedLists( curr = curr.next; } - return head; + return head.next; } public static void main(String a[]) { SingleLinkedList linkedList = new SingleLinkedList<>(); - linkedList.add(33); linkedList.add(21); + linkedList.add(33); linkedList.add(89); - linkedList.add(55); + linkedList.add(21); linkedList.add(44); linkedList.add(67); linkedList.printList(); From 2a9063151b267b379af3363a819a26f122418daa Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 8 Jul 2015 14:57:40 +0530 Subject: [PATCH 166/417] intersection and union of linked list: done --- .../IntersectionAndUnionOf2Lists.java | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java b/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java index 0f80ead5..c7ca3502 100644 --- a/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java +++ b/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java @@ -1,6 +1,7 @@ package me.ramswaroop.linkedlists; import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; /** * Created by IntelliJ IDEA. @@ -11,12 +12,45 @@ */ public class IntersectionAndUnionOf2Lists { + /** + * + * @param list1 + * @param list2 + * @param + * @return an array of list consisting of intersection and union of {@param list1} and {@param list2} respectively. + */ public static > SingleLinkedList[] getIntersectionAndUnion(SingleLinkedList list1, SingleLinkedList list2) { + SingleLinkedNode curr1 = list1.head, curr2 = list2.head; + SingleLinkedList intersectionList = new SingleLinkedList<>(), + unionList = new SingleLinkedList<>(); + MergeSort.mergeSort(curr1); + MergeSort.mergeSort(curr2); - return null; + while (curr1 != null || curr2 != null) { + if (curr1 == null) { + unionList.add(curr2.item); + curr2 = curr2.next; + } else if (curr2 == null) { + unionList.add(curr1.item); + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) < 0) { + unionList.add(curr1.item); + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) > 0) { + unionList.add(curr2.item); + curr2=curr2.next; + } else { + unionList.add(curr1.item); + intersectionList.add(curr1.item); + curr1 = curr1.next; + curr2 = curr2.next; + } + } + + return new SingleLinkedList[]{intersectionList, unionList}; } public static void main(String a[]) { @@ -36,7 +70,9 @@ public static void main(String a[]) { linkedList2.add(67); linkedList2.add(89); linkedList2.printList(); + System.out.println("Intersection:"); getIntersectionAndUnion(linkedList1, linkedList2)[0].printList(); + System.out.println("Union:"); getIntersectionAndUnion(linkedList1, linkedList2)[1].printList(); } } From d382265b5983bddc12cf521f7d566f4792a2766d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 9 Jul 2015 12:24:08 +0530 Subject: [PATCH 167/417] lru cache using linkedhashmap: done --- src/me/ramswaroop/linkedlists/LRUCache.java | 63 +++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/LRUCache.java diff --git a/src/me/ramswaroop/linkedlists/LRUCache.java b/src/me/ramswaroop/linkedlists/LRUCache.java new file mode 100644 index 00000000..c7192260 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/LRUCache.java @@ -0,0 +1,63 @@ +package me.ramswaroop.linkedlists; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Created by IntelliJ IDEA. + *

+ * A simple LRU cache using {@link java.util.LinkedHashMap}. + * + * @author: ramswaroop + * @date: 7/8/15 + * @time: 5:40 PM + * @see: http://javarticles.com/2012/06/linkedhashmap.html + */ +public class LRUCache { + + LinkedHashMap linkedHashMap; + + // initialize cache + LRUCache(final int size) { + this.linkedHashMap = new LinkedHashMap(size, .75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > size; + } + }; + } + + void add(E item) { + linkedHashMap.put(item, null); + printCache(); + } + + E get(E item) { + E itemFromCache = (E) linkedHashMap.get(item); + if (itemFromCache == null) { + add(item); + return item; + } + printCache(); + return itemFromCache; + } + + void printCache() { + Iterator iterator = linkedHashMap.keySet().iterator(); + while (iterator.hasNext()) { + System.out.print(iterator.next() + ((iterator.hasNext()) ? "," : "\n")); + } + } + + public static void main(String a[]) { + LRUCache cache = new LRUCache<>(3); + cache.add(1); + cache.add(2); + cache.add(3); + cache.get(null); + cache.add(4); + cache.add(5); + cache.get(null); + } +} From d90e8844125945b06b40cae34bac5533d4dd007e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 10 Jul 2015 15:12:21 +0530 Subject: [PATCH 168/417] reverse linked list (recursive): code improved --- .../linkedlists/ReverseSingleLinkedList.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java b/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java index 5728fcd2..ce6fb603 100644 --- a/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java +++ b/src/me/ramswaroop/linkedlists/ReverseSingleLinkedList.java @@ -10,7 +10,7 @@ * @date: 6/19/15 * @time: 9:24 AM */ -public class ReverseSingleLinkedList> extends SingleLinkedList { +public class ReverseSingleLinkedList { /** * Reverses the linked list using 3 references prev, curr and next. @@ -34,19 +34,18 @@ public static > void reverseList(SingleLinkedList lis * @param node * @return */ - public SingleLinkedNode recursiveReverseList(SingleLinkedNode node) { - if (node == null) return null; + public static > SingleLinkedNode recursiveReverseList(SingleLinkedNode node) { + if (node == null || node.next == null) return node; - SingleLinkedNode nextNode = recursiveReverseList(node.next); + SingleLinkedNode nextNode = node.next; - if (nextNode == null) { - head.next = null; // head will be the last node so head.next = null; - head = node; - } else { - nextNode.next = node; - } + node.next = null; + + SingleLinkedNode newHead = recursiveReverseList(nextNode); - return node; + nextNode.next = node; + + return newHead; } /** @@ -67,7 +66,7 @@ public static > void printListInReverse(SingleLinkedNode } public static void main(String a[]) { - ReverseSingleLinkedList linkedList = new ReverseSingleLinkedList<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(11); linkedList.add(22); linkedList.add(33); @@ -76,8 +75,8 @@ public static void main(String a[]) { linkedList.printList(); reverseList(linkedList); linkedList.printList(); - linkedList.recursiveReverseList(linkedList.getNode(0)); - linkedList.printList(); - printListInReverse(linkedList.getNode(0)); + printListInReverse(linkedList.head); + System.out.println(); + SingleLinkedList.printList(recursiveReverseList(linkedList.head)); } } From e69fc84786386c38576c4c074d58e207398f8f8d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 10 Jul 2015 15:28:21 +0530 Subject: [PATCH 169/417] triplet from 3 linked list: done --- .../TripletFromThreeLinkedLists.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/TripletFromThreeLinkedLists.java diff --git a/src/me/ramswaroop/linkedlists/TripletFromThreeLinkedLists.java b/src/me/ramswaroop/linkedlists/TripletFromThreeLinkedLists.java new file mode 100644 index 00000000..350518d7 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/TripletFromThreeLinkedLists.java @@ -0,0 +1,75 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/9/15 + * @time: 4:00 PM + */ +public class TripletFromThreeLinkedLists { + + public static SingleLinkedNode findTripletWithSumEqualsTo(SingleLinkedNode node1, + SingleLinkedNode node2, + SingleLinkedNode node3, + int sum) { + node2 = MergeSort.mergeSort(node2); + node3 = MergeSort.mergeSort(node3); + node3 = ReverseSingleLinkedList.recursiveReverseList(node3); + + SingleLinkedNode curr1 = node1, curr2, curr3; + int s; + + while (curr1 != null) { + + curr2 = node2; + curr3 = node3; + + while (curr2 != null && curr3 != null) { + s = curr1.item + curr2.item + curr3.item; + + if (s == sum) { + curr1.next = curr2; + curr2.next = curr3; + curr3.next = null; + return curr1; + } + + if (s < sum) { + curr2 = curr2.next; + } else { + curr3 = curr3.next; + } + } + + curr1 = curr1.next; + + } + + return null; + + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(2); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(6); + linkedList2.add(8); + linkedList2.add(7); + SingleLinkedList linkedList3 = new SingleLinkedList<>(); + linkedList3.add(9); + linkedList3.add(6); + linkedList3.add(12); + linkedList1.printList(); + linkedList2.printList(); + linkedList3.printList(); + SingleLinkedList.printList(findTripletWithSumEqualsTo(linkedList1.head, + linkedList2.head, + linkedList3.head, + 18)); + } +} From 4476b303f3e816d3af25e596e099313fda227bbe Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 11 Jul 2015 19:34:26 +0530 Subject: [PATCH 170/417] pairwise swap: code improved --- .../ramswaroop/linkedlists/PairWiseSwap.java | 35 +++++-------------- 1 file changed, 9 insertions(+), 26 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/PairWiseSwap.java b/src/me/ramswaroop/linkedlists/PairWiseSwap.java index bc8462fb..9daee72e 100644 --- a/src/me/ramswaroop/linkedlists/PairWiseSwap.java +++ b/src/me/ramswaroop/linkedlists/PairWiseSwap.java @@ -10,7 +10,7 @@ * @date: 6/24/15 * @time: 3:48 PM */ -public class PairWiseSwap> extends SingleLinkedList { +public class PairWiseSwap { /** * Recursively swaps adjacent nodes of a linked list. @@ -18,35 +18,19 @@ public class PairWiseSwap> extends SingleLinkedList { * * @param node */ - public void pairWiseSwap(SingleLinkedNode node) { - if (node == null || node.next == null) return; + public static > SingleLinkedNode pairWiseSwap(SingleLinkedNode node) { + if (node == null || node.next == null) return node; - // the trick is to swap the next two nodes of {@param node} - // but if {@param node} is head then swap itself with the next node - SingleLinkedNode firstNode = (node == head) ? node : node.next, - secondNode = (node == head) ? node.next : node.next.next; + SingleLinkedNode nextNode = node.next, nextOfNextNode = nextNode.next; - if (firstNode == null || secondNode == null) return; + nextNode.next = node; + node.next = pairWiseSwap(nextOfNextNode); - firstNode.next = secondNode.next; - secondNode.next = firstNode; - - if (node == head) { - head = secondNode; - } else { - node.next = secondNode; - } - - // pass firstNode as the next two nodes are swapped - pairWiseSwap(firstNode); - } - - public void pairWiseSwap() { - pairWiseSwap(head); + return nextNode; } public static void main(String a[]) { - PairWiseSwap linkedList = new PairWiseSwap<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(11); linkedList.add(22); linkedList.add(33); @@ -55,7 +39,6 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.printList(); - linkedList.pairWiseSwap(); - linkedList.printList(); + linkedList.printList(pairWiseSwap(linkedList.head)); } } \ No newline at end of file From 6735c606c564dfb578222a2854c0a629c0aa66ca Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 11 Jul 2015 19:36:44 +0530 Subject: [PATCH 171/417] pairwise swap: refactoring --- src/me/ramswaroop/linkedlists/PairWiseSwap.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/linkedlists/PairWiseSwap.java b/src/me/ramswaroop/linkedlists/PairWiseSwap.java index 9daee72e..3cb3bc66 100644 --- a/src/me/ramswaroop/linkedlists/PairWiseSwap.java +++ b/src/me/ramswaroop/linkedlists/PairWiseSwap.java @@ -14,9 +14,9 @@ public class PairWiseSwap { /** * Recursively swaps adjacent nodes of a linked list. - * The swapping is done in place. * * @param node + * @return new starting node after swapping adjacent nodes. */ public static > SingleLinkedNode pairWiseSwap(SingleLinkedNode node) { if (node == null || node.next == null) return node; From ebbf92a923cdd69c65114cda28ebf24c604fed5d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 12 Jul 2015 17:52:28 +0530 Subject: [PATCH 172/417] swap any 2 nodes in linked list: done --- .../ramswaroop/linkedlists/PairWiseSwap.java | 4 ++ src/me/ramswaroop/linkedlists/SwapNodes.java | 70 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/SwapNodes.java diff --git a/src/me/ramswaroop/linkedlists/PairWiseSwap.java b/src/me/ramswaroop/linkedlists/PairWiseSwap.java index 3cb3bc66..67b45bf7 100644 --- a/src/me/ramswaroop/linkedlists/PairWiseSwap.java +++ b/src/me/ramswaroop/linkedlists/PairWiseSwap.java @@ -14,6 +14,10 @@ public class PairWiseSwap { /** * Recursively swaps adjacent nodes of a linked list. + *

+ * Example: + * Input: 11->22->33->44->55 + * Output: 22->11->44->33->55 * * @param node * @return new starting node after swapping adjacent nodes. diff --git a/src/me/ramswaroop/linkedlists/SwapNodes.java b/src/me/ramswaroop/linkedlists/SwapNodes.java new file mode 100644 index 00000000..17e3c4f7 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SwapNodes.java @@ -0,0 +1,70 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/12/15 + * @time: 1:23 PM + */ +public class SwapNodes { + + /** + * Swap nodes with value {@param item1} with {@param item2} in linked list + * starting at {@param node}. + * + * @param node + * @param item1 + * @param item2 + * @param + * @return + */ + public static > SingleLinkedNode swap(SingleLinkedNode node, + E item1, + E item2) { + + // dummy node needed to swap the very first node + SingleLinkedNode head = new SingleLinkedNode<>(null), + curr1 = head, + curr2 = head, + temp; + + head.next = node; + + while (curr1.next.item != item1) { + curr1 = curr1.next; + } + + while (curr2.next.item != item2) { + curr2 = curr2.next; + } + + // swap nodes + temp = curr1.next; + curr1.next = curr2.next; + curr2.next = temp; + + // update their next nodes + temp = curr1.next.next; + curr1.next.next = curr2.next.next; + curr2.next.next = temp; + + return head.next; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.printList(); + linkedList.printList(swap(linkedList.head, 11, 77)); + } +} From a55337c9d13af77ca847c85b8afd8156365afca0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 12 Jul 2015 18:00:07 +0530 Subject: [PATCH 173/417] swap any 2 nodes in linked list: improved --- src/me/ramswaroop/linkedlists/SwapNodes.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/SwapNodes.java b/src/me/ramswaroop/linkedlists/SwapNodes.java index 17e3c4f7..80d712a0 100644 --- a/src/me/ramswaroop/linkedlists/SwapNodes.java +++ b/src/me/ramswaroop/linkedlists/SwapNodes.java @@ -34,14 +34,17 @@ public static > SingleLinkedNode swap(SingleLinkedNod head.next = node; - while (curr1.next.item != item1) { + while (curr1.next != null && curr1.next.item != item1) { curr1 = curr1.next; } - while (curr2.next.item != item2) { + while (curr2.next != null && curr2.next.item != item2) { curr2 = curr2.next; } + // if either of the node isn't present in the list then do nothing + if (curr1.next == null || curr2.next == null) return head.next; + // swap nodes temp = curr1.next; curr1.next = curr2.next; @@ -65,6 +68,6 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.printList(); - linkedList.printList(swap(linkedList.head, 11, 77)); + linkedList.printList(swap(linkedList.head, 111, 77)); } } From 09bb070298c8ac95a0d9262b11bd0a768a8a0b4b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 13 Jul 2015 12:46:32 +0530 Subject: [PATCH 174/417] swap kth node from start with kth node from end in linked list: done --- .../ramswaroop/linkedlists/SwapKthNode.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/SwapKthNode.java diff --git a/src/me/ramswaroop/linkedlists/SwapKthNode.java b/src/me/ramswaroop/linkedlists/SwapKthNode.java new file mode 100644 index 00000000..6cd05ad7 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SwapKthNode.java @@ -0,0 +1,75 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/13/15 + * @time: 12:25 PM + */ +public class SwapKthNode { + + public static > SingleLinkedNode swapKthNodeFromStartWithKthNodeFromEnd(SingleLinkedNode node, + int k) { + + + int i = 1; + + // dummy node needed to swap the very first node + SingleLinkedNode head = new SingleLinkedNode<>(null), + curr = head, + slow = head, + fast = head, + temp; + + head.next = node; + + // find kth node from start + while (i < k && curr.next != null) { + curr = curr.next; + fast = fast.next; + i++; + } + + // move the fast pointer k steps ahead of slow + fast = fast.next; + + // find kth node from end + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + + // if either of the node isn't present in the list then do nothing + if (curr.next == null || slow.next == null) return head.next; + + // swap nodes + temp = curr.next; + curr.next = slow.next; + slow.next = temp; + + // update their next nodes + temp = curr.next.next; + curr.next.next = slow.next.next; + slow.next.next = temp; + + return head.next; + + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.printList(); + linkedList.printList(swapKthNodeFromStartWithKthNodeFromEnd(linkedList.head, 2)); + } +} From ca85448c57d33de33dacfa102d0a13b74eba9dd2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 13 Jul 2015 13:25:58 +0530 Subject: [PATCH 175/417] merge two linked list alternatively: done --- .../MergeTwoLinkedListAlternatively.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/MergeTwoLinkedListAlternatively.java diff --git a/src/me/ramswaroop/linkedlists/MergeTwoLinkedListAlternatively.java b/src/me/ramswaroop/linkedlists/MergeTwoLinkedListAlternatively.java new file mode 100644 index 00000000..29418da2 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MergeTwoLinkedListAlternatively.java @@ -0,0 +1,74 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/13/15 + * @time: 12:54 PM + */ +public class MergeTwoLinkedListAlternatively { + + /** + * Given two linked lists, insert nodes of second list into first list at + * alternate positions of first list till there are no more positions to + * insert in first list. + *

+ * Example, + * Input: L1: 5->7->17->13->11 and L2: 12->10->2->4->6 + * Output: L1: 5->12->7->10->17->2->13->4->11->6 and L2: empty + *

+ * Input: L1: 1->2->3 and L2: 4->5->6->7->8 + * Output: L1: 1->4->2->5->3->6 and L2: 7->8 + * + * @param node1 + * @param node2 + * @param + * @return + */ + public static > SingleLinkedNode mergeTwoLinkedListAlternatively(SingleLinkedNode node1, + SingleLinkedNode node2) { + + SingleLinkedNode curr1 = node1, curr2 = node2, temp1, temp2; + + while (curr1 != null && curr2 != null) { + temp1 = curr1.next; + temp2 = curr2.next; + + curr1.next = curr2; + curr2.next = temp1; + + curr1 = temp1; + curr2 = temp2; + } + + return curr2; + + } + + public static void main(String a[]) { + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(21); + linkedList2.add(33); + linkedList2.add(44); + linkedList2.add(55); + linkedList2.add(67); + linkedList2.add(89); + linkedList2.add(99); + linkedList2.printList(); + SingleLinkedNode list2 = mergeTwoLinkedListAlternatively(linkedList1.head, linkedList2.head); + linkedList1.printList(); + SingleLinkedList.printList(list2); + } +} From 4eaddaf0b187f9e2ed198ecf91d3ee8dc47c18b9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 14 Jul 2015 15:51:04 +0530 Subject: [PATCH 176/417] reverse alternate nodes and append at end: done --- .../ReverseAlternateNodesAndAppendAtEnd.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java diff --git a/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java b/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java new file mode 100644 index 00000000..f522a787 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java @@ -0,0 +1,48 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/14/15 + * @time: 12:16 PM + */ +public class ReverseAlternateNodesAndAppendAtEnd { + + public static > SingleLinkedNode reverseAlternateNodesAndAppendAtEnd(SingleLinkedNode node) { + SingleLinkedNode curr = node, end = node, currNext, endNext; + + while (end.next != null) { + end = end.next; + } + + while (curr != end && curr.next != end) { + + currNext = curr.next.next; + endNext = end.next; + + end.next = curr.next; + end.next.next = endNext; + + curr.next = currNext; + curr = curr.next; + } + + return node; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.printList(); + SingleLinkedList.printList(reverseAlternateNodesAndAppendAtEnd(linkedList.head)); + } +} From 85680b34da51ab6b4d7b852827e095435c64ebae Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 14 Jul 2015 23:50:16 +0530 Subject: [PATCH 177/417] reverse alternate nodes and append at end: comments added --- .../ReverseAlternateNodesAndAppendAtEnd.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java b/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java index f522a787..ba9b752c 100644 --- a/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java +++ b/src/me/ramswaroop/linkedlists/ReverseAlternateNodesAndAppendAtEnd.java @@ -12,6 +12,21 @@ */ public class ReverseAlternateNodesAndAppendAtEnd { + /** + * Reverse alternate nodes and append them to end of the list. + * + * Example, + * + * Input List: 1->2->3->4->5->6 + * Output List: 1->3->5->6->4->2 + * + * Input List: 12->14->16->18->20 + * Output List: 12->16->20->18->14 + * + * @param node + * @param + * @return + */ public static > SingleLinkedNode reverseAlternateNodesAndAppendAtEnd(SingleLinkedNode node) { SingleLinkedNode curr = node, end = node, currNext, endNext; From c7017d0f38cc26cdca6e2614e24fe307e3d9ca24 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 15 Jul 2015 00:24:59 +0530 Subject: [PATCH 178/417] maximum sum path: 50% done --- .../linkedlists/MaximumSumLinkedList.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java diff --git a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java new file mode 100644 index 00000000..b7213660 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java @@ -0,0 +1,51 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/15/15 + * @time: 12:12 AM + */ +public class MaximumSumLinkedList { + + /** + * Constructs a linked list that contains maximum sum path from start to end + * from two linked lists starting at {@param node1} and {@param node2}. + * + * Example, + * Input: + * List1 = 1->3->30->90->120->240->511 + * List2 = 0->3->12->32->90->125->240->249 + * + * Output: Following is maximum sum linked list out of two input lists + * List = 1->3->12->32->90->125->240->511 + * + * NOTE: We switch at 3 and 240 to get above maximum sum linked list + * + * @param node1 + * @param node2 + * @param + * @return + */ + public static > SingleLinkedNode maximumSumLinkedList(SingleLinkedNode node1, + SingleLinkedNode node2) { + + SingleLinkedNode node = node1, curr1 = node1, curr2 = node2; + + while (curr1 != null && curr2 != null) { + + + curr1 = curr1.next; + curr2 = curr2.next; + } + + return node; + } + + public static void main(String a[]) { + + } +} From 3bdf19202c18da5b83d0cbebbaace9465a84b018 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 16 Jul 2015 23:08:46 +0530 Subject: [PATCH 179/417] maximum sum path: done --- .../linkedlists/MaximumSumLinkedList.java | 41 +++++++++++++++---- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java index b7213660..c4b03bb2 100644 --- a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java +++ b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java @@ -1,5 +1,6 @@ package me.ramswaroop.linkedlists; +import me.ramswaroop.common.SingleLinkedList; import me.ramswaroop.common.SingleLinkedNode; /** @@ -14,15 +15,15 @@ public class MaximumSumLinkedList { /** * Constructs a linked list that contains maximum sum path from start to end * from two linked lists starting at {@param node1} and {@param node2}. - * + *

* Example, * Input: * List1 = 1->3->30->90->120->240->511 * List2 = 0->3->12->32->90->125->240->249 - * + *

* Output: Following is maximum sum linked list out of two input lists * List = 1->3->12->32->90->125->240->511 - * + *

* NOTE: We switch at 3 and 240 to get above maximum sum linked list * * @param node1 @@ -33,19 +34,43 @@ public class MaximumSumLinkedList { public static > SingleLinkedNode maximumSumLinkedList(SingleLinkedNode node1, SingleLinkedNode node2) { - SingleLinkedNode node = node1, curr1 = node1, curr2 = node2; + boolean isList1 = true; + SingleLinkedNode head = node1, node = node1, curr1 = node1.next, curr2 = node2.next; while (curr1 != null && curr2 != null) { - - + if (curr1.item.compareTo(curr2.item) == 0) { + isList1 = !isList1; + } + if (isList1) { + node.next = curr1; + } else { + node.next = curr2; + } + node = node.next; curr1 = curr1.next; curr2 = curr2.next; } - return node; + return head; } public static void main(String a[]) { - + SingleLinkedList linkedList1 = new SingleLinkedList<>(); + linkedList1.add(00); + linkedList1.add(11); + linkedList1.add(22); + linkedList1.add(33); + linkedList1.add(44); + linkedList1.add(55); + linkedList1.printList(); + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(12); + linkedList2.add(21); + linkedList2.add(26); + linkedList2.add(33); + linkedList2.add(34); + linkedList2.add(67); + linkedList2.printList(); + SingleLinkedList.printList(maximumSumLinkedList(linkedList1.head, linkedList2.head)); } } From aa2fc20552fe5bff6816075f5aa6ea54e413cb51 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 17 Jul 2015 14:11:18 +0530 Subject: [PATCH 180/417] maximum sum path: code improved --- .../linkedlists/MaximumSumLinkedList.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java index c4b03bb2..c2360ab8 100644 --- a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java +++ b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java @@ -37,7 +37,21 @@ public static > SingleLinkedNode maximumSumLinkedList boolean isList1 = true; SingleLinkedNode head = node1, node = node1, curr1 = node1.next, curr2 = node2.next; - while (curr1 != null && curr2 != null) { + while (curr1 != null || curr2 != null) { + // if either of the list runs out first + if (curr1 == null) { + node.next = curr2; + node = node.next; + curr2 = curr2.next; + continue; + } + if (curr2 == null) { + node.next = curr1; + node = node.next; + curr1 = curr1.next; + continue; + } + if (curr1.item.compareTo(curr2.item) == 0) { isList1 = !isList1; } @@ -70,6 +84,8 @@ public static void main(String a[]) { linkedList2.add(33); linkedList2.add(34); linkedList2.add(67); + linkedList2.add(88); + linkedList2.add(90); linkedList2.printList(); SingleLinkedList.printList(maximumSumLinkedList(linkedList1.head, linkedList2.head)); } From 0c797277d5d3322e7ce11b6d585d440bf6cd243a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 18 Jul 2015 16:19:51 +0530 Subject: [PATCH 181/417] maximum sum path: minor fix --- .../ramswaroop/linkedlists/MaximumSumLinkedList.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java index c2360ab8..b58725f4 100644 --- a/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java +++ b/src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java @@ -40,18 +40,25 @@ public static > SingleLinkedNode maximumSumLinkedList while (curr1 != null || curr2 != null) { // if either of the list runs out first if (curr1 == null) { + // check whether we are in list 1 currently + if (isList1) break; + node.next = curr2; node = node.next; curr2 = curr2.next; continue; } if (curr2 == null) { + // check whether we are in list 2 currently + if (!isList1) break; + node.next = curr1; node = node.next; curr1 = curr1.next; continue; } + // switch lists once both node values match if (curr1.item.compareTo(curr2.item) == 0) { isList1 = !isList1; } @@ -76,6 +83,8 @@ public static void main(String a[]) { linkedList1.add(33); linkedList1.add(44); linkedList1.add(55); + linkedList1.add(88); + linkedList1.add(90); linkedList1.printList(); SingleLinkedList linkedList2 = new SingleLinkedList<>(); linkedList2.add(12); @@ -84,8 +93,6 @@ public static void main(String a[]) { linkedList2.add(33); linkedList2.add(34); linkedList2.add(67); - linkedList2.add(88); - linkedList2.add(90); linkedList2.printList(); SingleLinkedList.printList(maximumSumLinkedList(linkedList1.head, linkedList2.head)); } From 1d726b2f826b055cb9c17b8603309c1dc0ada631 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 20 Jul 2015 13:09:44 +0530 Subject: [PATCH 182/417] merge sort for double linked list: done --- src/me/ramswaroop/linkedlists/MergeSort.java | 1 + .../MergeSortDoubleLinkedList.java | 131 ++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/MergeSortDoubleLinkedList.java diff --git a/src/me/ramswaroop/linkedlists/MergeSort.java b/src/me/ramswaroop/linkedlists/MergeSort.java index 6b9c618e..b5a2bc32 100644 --- a/src/me/ramswaroop/linkedlists/MergeSort.java +++ b/src/me/ramswaroop/linkedlists/MergeSort.java @@ -104,6 +104,7 @@ public static > SingleLinkedNode mergeTwoSortedLists( curr = curr.next; } + // return the node next to the dummy node return head.next; } diff --git a/src/me/ramswaroop/linkedlists/MergeSortDoubleLinkedList.java b/src/me/ramswaroop/linkedlists/MergeSortDoubleLinkedList.java new file mode 100644 index 00000000..d4899567 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/MergeSortDoubleLinkedList.java @@ -0,0 +1,131 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.DoubleLinkedList; +import me.ramswaroop.common.DoubleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/7/15 + * @time: 4:34 PM + */ +public class MergeSortDoubleLinkedList { + + /** + * Merge sort for linked list starting at {@param node}. + * + * @param node + * @param + * @return + */ + public static > DoubleLinkedNode mergeSort(DoubleLinkedNode node) { + if (node == null || node.next == null) return node; + + DoubleLinkedNode middleNode, head1, head2; + + middleNode = divideInTwoHalves(node); + + head1 = mergeSort(node); + head2 = mergeSort(middleNode); + + return mergeTwoSortedLists(head1, head2); + + } + + + /** + * Divides a linked list starting from {@param node} into 2 halves + * and returns the starting {@code node} of the second half. + * + * @param node + * @param + * @return + */ + public static > DoubleLinkedNode divideInTwoHalves(DoubleLinkedNode node) { + DoubleLinkedNode slow = node, fast = node, prev = slow; + + if (node == null || node.next == null) { + return null; + } + + while (fast != null && fast.next != null) { + prev = slow; + slow = slow.next; + fast = fast.next.next; + } + prev.next = null; + return slow; + } + + + /** + * Merges two sorted lists starting at {@param node1} and {@param node2} + * into one and returns its starting node. + *

+ * This method is similar to {@link MergeTwoSortedLists#mergeTwoSortedLists} + * + * @param node1 + * @param node2 + * @param + * @return + */ + public static > DoubleLinkedNode mergeTwoSortedLists(DoubleLinkedNode node1, + DoubleLinkedNode node2) { + DoubleLinkedNode curr1 = node1, curr2 = node2, head, curr; + + if (node1 == null && node2 == null) return null; + + head = curr = new DoubleLinkedNode<>(null); // dummy node + + while (curr1 != null || curr2 != null) { + // handle cases where either of the list run out first + if (curr1 == null) { + curr.next = curr2; + curr2.prev = curr; + curr2 = curr2.next; + } else if (curr2 == null) { + curr.next = curr1; + curr1.prev = curr; + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) < 0) { // advance the current pointer of the + // list having smaller {@code item} + curr.next = curr1; + curr1.prev = curr; + curr1 = curr1.next; + } else if (curr1.item.compareTo(curr2.item) > 0) { + curr.next = curr2; + curr2.prev = curr; + curr2 = curr2.next; + } else { // both nodes are equal so add both to the result + curr.next = curr1; + curr = curr.next; + curr1 = curr1.next; + curr1.prev = curr; + curr.next = curr2; + curr2.prev = curr; + curr2 = curr2.next; + } + + curr = curr.next; + } + + // the dummy node should be unlinked + head.next.prev = null; + + // return the node next to the dummy node + return head.next; + } + + public static void main(String a[]) { + DoubleLinkedList linkedList = new DoubleLinkedList<>(); + linkedList.add(21); + linkedList.add(33); + linkedList.add(89); + linkedList.add(21); + linkedList.add(44); + linkedList.add(67); + linkedList.printList(); + linkedList.printList(mergeSort(linkedList.head)); + } +} From 6495b7cc5e58bfe35f88dcf19b06fb3ba8626cd3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 19 Jul 2015 12:40:00 +0530 Subject: [PATCH 183/417] Sort Alternatively Sorted LinkedList : done --- .../SortAlternativelySortedLinkedList.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/SortAlternativelySortedLinkedList.java diff --git a/src/me/ramswaroop/linkedlists/SortAlternativelySortedLinkedList.java b/src/me/ramswaroop/linkedlists/SortAlternativelySortedLinkedList.java new file mode 100644 index 00000000..6fcfb671 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SortAlternativelySortedLinkedList.java @@ -0,0 +1,57 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/20/15 + * @time: 3:03 PM + */ +public class SortAlternativelySortedLinkedList { + + /** + * Given a Linked List which is in alternating ascending and descending orders. In other words, nodes + * at even indexes are in ascending order whereas the nodes at odd indexes are in descending order. + * Sort the list efficiently in O(n) time complexity. + * + * Example: + * + * Input List: 10->40->53->30->67->12->89->NULL + * Output List: 10->12->30->43->53->67->89->NULL + * + * @param node + * @param + * @return + */ + public static > SingleLinkedNode sort(SingleLinkedNode node) { + SingleLinkedNode secondList = node.next, curr = node, next; + + // separate even and odd nodes into two separate lists + while (curr != null && curr.next != null) { + next = curr.next; + curr.next = next.next; + next.next = (curr.next == null) ? null : curr.next.next; + curr = curr.next; + } + + // reverse the descending ordered list + secondList = ReverseSingleLinkedList.recursiveReverseList(secondList); + + // now merge two sorted lists + return MergeSort.mergeTwoSortedLists(node, secondList); + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(21); + linkedList.add(67); + linkedList.add(44); + linkedList.add(33); + linkedList.add(89); + linkedList.printList(); + linkedList.printList(sort(linkedList.head)); + } +} From 2b5e2ad49c8569a55e3e46a5b926f785e8698ee9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 21 Jul 2015 15:13:21 +0530 Subject: [PATCH 184/417] reservoir sampling: done --- .../ramswaroop/arrays/ReservoirSampling.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/me/ramswaroop/arrays/ReservoirSampling.java diff --git a/src/me/ramswaroop/arrays/ReservoirSampling.java b/src/me/ramswaroop/arrays/ReservoirSampling.java new file mode 100644 index 00000000..4b64177c --- /dev/null +++ b/src/me/ramswaroop/arrays/ReservoirSampling.java @@ -0,0 +1,57 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; +import java.util.Random; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/21/15 + * @time: 2:52 PM + */ +public class ReservoirSampling { + + /** + * Returns {@param k} non-repeating random numbers from {@param stream} + * using reservoir sampling method. + *

+ * Explanation: + * 1) Create an array reservoir[0..k-1] and copy first k items of stream[] to it. + * 2) Now one by one consider all items from (k+1)th item to nth item. + * a) Generate a random number from 0 to i where i is index of current item in + * stream[]. Let the generated random number is j. + * b) If j is in range 0 to k-1, replace reservoir[j] with arr[i]. + * + * In the above procedure, we are computing random number for each of the indexes greater than k + * thereby giving all items an equal probability. + * + * @param stream + * @param k + * @return + */ + public static int[] getKRandomNumbers(int[] stream, int k) { + int i; + int[] reservoir = new int[k]; + + for (i = 0; i < k; i++) { + reservoir[i] = stream[i]; + } + + for (; i < stream.length; i++) { + int rand = new Random().nextInt(i); + + if (rand < k) { + reservoir[rand] = stream[i]; + } + } + + return reservoir; + + } + + public static void main(String a[]) { + int[] stream = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + System.out.println(Arrays.toString(getKRandomNumbers(stream, 4))); + } +} From fda8a94a7b8bd3726d642d3c2ced6a39c434cff4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 21 Jul 2015 15:13:40 +0530 Subject: [PATCH 185/417] spelling error: fixed --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a408201..a7afded1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Algorithms and Data Structures in Java -The repo consists of solutions to numerous problems invloving different data structures and algorithms. All solutions are coded in Java. +The repo consists of solutions to numerous problems involving different data structures and algorithms. All solutions are coded in Java. ## Environment From a16a34620b1e9f27987255dfd557b808c2589fd1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 21 Jul 2015 15:22:52 +0530 Subject: [PATCH 186/417] random node: done --- .../ramswaroop/arrays/ReservoirSampling.java | 8 +++ src/me/ramswaroop/linkedlists/RandomNode.java | 54 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/RandomNode.java diff --git a/src/me/ramswaroop/arrays/ReservoirSampling.java b/src/me/ramswaroop/arrays/ReservoirSampling.java index 4b64177c..b0b6c34d 100644 --- a/src/me/ramswaroop/arrays/ReservoirSampling.java +++ b/src/me/ramswaroop/arrays/ReservoirSampling.java @@ -26,6 +26,14 @@ public class ReservoirSampling { * In the above procedure, we are computing random number for each of the indexes greater than k * thereby giving all items an equal probability. * + * NOTE: When {@param k} is small enough we can use a simpler method as follows: + * Create an array reservoir[] of maximum size k. One by one randomly select an + * item from stream[0..n-1]. If the selected item is not previously selected, then + * put it in reservoir[]. To check if an item is previously selected or not, we + * need to search the item in reservoir[]. + * The time complexity of this algorithm will be O(k^2). This can be costly + * if k is big. Also, this is not efficient if the input is in the form of a stream. + * * @param stream * @param k * @return diff --git a/src/me/ramswaroop/linkedlists/RandomNode.java b/src/me/ramswaroop/linkedlists/RandomNode.java new file mode 100644 index 00000000..19f0e768 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/RandomNode.java @@ -0,0 +1,54 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +import java.util.Random; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/21/15 + * @time: 12:57 PM + */ +public class RandomNode { + + /** + * Returns a random node from linked list with each node having an equal probability. + * + * This method uses the simplified version of Reservoir Sampling ({@link me.ramswaroop.arrays.ReservoirSampling}) + * where k = 1. + * + * @param node + * @param + * @return + */ + public static > SingleLinkedNode getRandomNode(SingleLinkedNode node) { + SingleLinkedNode result = node, curr = node; + for (int i = 2; curr != null; i++) { + + int rand = new Random().nextInt(i); + + if (rand % i == 0) result = curr; + + curr = curr.next; + } + + return result; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(00); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.add(88); + System.out.println(getRandomNode(linkedList.head).item); + } +} From 4bf77a6e021c94448dc418e81cbb1ca5d94398b0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 21 Jul 2015 15:23:08 +0530 Subject: [PATCH 187/417] power of 2: new method added --- src/me/ramswaroop/bits/PowerOf2.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/bits/PowerOf2.java b/src/me/ramswaroop/bits/PowerOf2.java index 32a2af92..a796a086 100644 --- a/src/me/ramswaroop/bits/PowerOf2.java +++ b/src/me/ramswaroop/bits/PowerOf2.java @@ -30,17 +30,31 @@ public static boolean isPowerOf2UsingANDoperator(long n) { return n != 0 && (n & (n - 1)) == 0; // n != 0 check added for input 0 } + /** + * The following code can be found in {@link java.util.Random#nextInt(int)}. + * + * @param n + * @return + */ + public static boolean isPowerOf2FromRandomClass(long n) { + return n != 0 && (n & -n) == n; + } + public static void main(String a[]) { System.out.println(isPowerOf2(18)); System.out.println(isPowerOf2UsingANDoperator(18)); + System.out.println(isPowerOf2FromRandomClass(18)); System.out.println(isPowerOf2(16)); System.out.println(isPowerOf2UsingANDoperator(16)); + System.out.println(isPowerOf2FromRandomClass(16)); System.out.println(isPowerOf2(0)); // works for 0 - System.out.println(isPowerOf2UsingANDoperator(0)); // works for 0 + System.out.println(isPowerOf2UsingANDoperator(0)); // works for 0 with a check + System.out.println(isPowerOf2FromRandomClass(0)); // works for 0 with a check System.out.println(isPowerOf2(-2)); // doesn't work for -ve no.s System.out.println(isPowerOf2UsingANDoperator(-2)); // doesn't work for -ve no.s + System.out.println(isPowerOf2FromRandomClass(-2)); // doesn't work for -ve no.s } } From a4a2242b5e8aebd9e9b4252adbfbfb13162abc62 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 21 Jul 2015 18:06:25 +0530 Subject: [PATCH 188/417] quick sort: done --- src/me/ramswaroop/arrays/QuickSort.java | 74 +++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/me/ramswaroop/arrays/QuickSort.java diff --git a/src/me/ramswaroop/arrays/QuickSort.java b/src/me/ramswaroop/arrays/QuickSort.java new file mode 100644 index 00000000..ac603303 --- /dev/null +++ b/src/me/ramswaroop/arrays/QuickSort.java @@ -0,0 +1,74 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/21/15 + * @time: 4:12 PM + * @see: http://www.csanimated.com/animation.php?t=Quicksort + */ +public class QuickSort { + + /** + * In-place partition method which moves all elements smaller than + * the pivot element to its left and all elements larger than the + * pivot element to its right. + * + * @param ar + * @param low + * @param high + * @return + */ + public static int partition(int[] ar, int low, int high) { + int pivot = high, temp; + + for (int i = low; i < high; i++) { + /** + * if ith element is smaller than pivot element then + * swap it with the last larger element known. + */ + if (ar[i] < ar[pivot]) { + temp = ar[low]; + ar[low] = ar[i]; + ar[i] = temp; + low++; + } + } + + // place the pivot element in its correct position + temp = ar[low]; + ar[low] = ar[pivot]; + ar[pivot] = temp; + + return low; + } + + /** + * Recursive Quick sort. + *

+ * Time complexity: + * Best Case: O(nlogn) + * Worst Case: O(n*n) + * + * @param ar + * @param low + * @param high + */ + public static void sort(int[] ar, int low, int high) { + if (low < high) { + int partition = partition(ar, low, high); + sort(ar, low, partition - 1); + sort(ar, partition + 1, high); + } + } + + public static void main(String a[]) { + int[] ar = {3, 2, 1, 6, 4, 9, 7, 8}; + System.out.println(Arrays.toString(ar)); + sort(ar, 0, ar.length - 1); + System.out.println(Arrays.toString(ar)); + } +} From e44825584fcbe14ba0b54bd08fc427de86269101 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 22 Jul 2015 13:11:15 +0530 Subject: [PATCH 189/417] count set bits from -n to n : done --- .../bits/CountSetBitsFromMinusNtoN.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/me/ramswaroop/bits/CountSetBitsFromMinusNtoN.java diff --git a/src/me/ramswaroop/bits/CountSetBitsFromMinusNtoN.java b/src/me/ramswaroop/bits/CountSetBitsFromMinusNtoN.java new file mode 100644 index 00000000..4ef484cc --- /dev/null +++ b/src/me/ramswaroop/bits/CountSetBitsFromMinusNtoN.java @@ -0,0 +1,38 @@ +package me.ramswaroop.bits; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/22/15 + * @time: 12:42 PM + */ +public class CountSetBitsFromMinusNtoN { + + /** + * Explanation: + * + * -3: 101 + * -2: 110 + * -1: 111 + * 0: 000 + * 1: 001 + * 2: 010 + * 3: 110 + * + * If you fold the above representation between -1 and 0, the total no. of set bits from -3 to 2 + * will be equal to the total no. of bits in nos. from -3 to 2. + * + * @param n + * @return + */ + public static int countSetBitsFromMinusNtoN(int n) { + return n * 32 + CountSetBits.countSetBits((long) n); // 32 because int is of 32 bits in java + } + + public static void main(String a[]) { + System.out.println(countSetBitsFromMinusNtoN(3)); + System.out.println(countSetBitsFromMinusNtoN(0)); + System.out.println(countSetBitsFromMinusNtoN(9)); + } +} From f29a337b9d002f0d29e7f3be325d5b99a9c7dc1b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 22 Jul 2015 19:05:28 +0530 Subject: [PATCH 190/417] quick sort: code refactoring --- src/me/ramswaroop/arrays/QuickSort.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/arrays/QuickSort.java b/src/me/ramswaroop/arrays/QuickSort.java index ac603303..b016fc51 100644 --- a/src/me/ramswaroop/arrays/QuickSort.java +++ b/src/me/ramswaroop/arrays/QuickSort.java @@ -57,18 +57,18 @@ public static int partition(int[] ar, int low, int high) { * @param low * @param high */ - public static void sort(int[] ar, int low, int high) { + public static void quickSort(int[] ar, int low, int high) { if (low < high) { int partition = partition(ar, low, high); - sort(ar, low, partition - 1); - sort(ar, partition + 1, high); + quickSort(ar, low, partition - 1); + quickSort(ar, partition + 1, high); } } public static void main(String a[]) { int[] ar = {3, 2, 1, 6, 4, 9, 7, 8}; System.out.println(Arrays.toString(ar)); - sort(ar, 0, ar.length - 1); + quickSort(ar, 0, ar.length - 1); System.out.println(Arrays.toString(ar)); } } From 8420940c06e6dc1b3cca1f838311b5584b2d50a7 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 22 Jul 2015 23:45:22 +0530 Subject: [PATCH 191/417] quick sort for linked list: done --- src/me/ramswaroop/linkedlists/QuickSort.java | 88 ++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/QuickSort.java diff --git a/src/me/ramswaroop/linkedlists/QuickSort.java b/src/me/ramswaroop/linkedlists/QuickSort.java new file mode 100644 index 00000000..5f6cb957 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/QuickSort.java @@ -0,0 +1,88 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/21/15 + * @time: 11:43 PM + */ +public class QuickSort { + + public static > SingleLinkedNode[] partition(SingleLinkedNode firstNode, + SingleLinkedNode lastNode) { + + SingleLinkedNode[] partition = new SingleLinkedNode[4]; + SingleLinkedNode pivot = lastNode, curr = new SingleLinkedNode<>(null, firstNode), currNext, pivotNext; + + while (curr.next != null && curr.next != lastNode) { + if (curr.next.item.compareTo(pivot.item) > 0) { + currNext = curr.next; + curr.next = currNext.next; + pivotNext = pivot.next; + pivot.next = currNext; + currNext.next = pivotNext; + continue; + } + curr = curr.next; + } + + partition[0] = curr; + + while (curr.next != pivot) { + curr = curr.next; + } + partition[1] = curr; + + partition[2] = pivot.next; + + while (curr.next != null) { + curr = curr.next; + } + partition[3] = curr; + + return partition; + + } + + public static > SingleLinkedNode quickSort(SingleLinkedNode firstNode, + SingleLinkedNode lastNode) { + + SingleLinkedNode head = firstNode; + if (firstNode != lastNode) { + SingleLinkedNode partition[] = partition(firstNode, lastNode); + head = quickSort(partition[0], partition[1]); + quickSort(partition[2], partition[3]); + } + + return head; + } + + public static > SingleLinkedNode quickSort(SingleLinkedNode node) { + return quickSort(node, getLastNode(node)); + } + + public static > SingleLinkedNode getLastNode(SingleLinkedNode node) { + SingleLinkedNode curr = node; + + while (curr != null && curr.next != null) { + curr = curr.next; + } + + return curr; + } + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(23); + linkedList.add(4); + linkedList.add(45); + linkedList.add(11); + linkedList.add(7); + linkedList.printList(); + linkedList.printList(quickSort(linkedList.head)); + } +} From f4e20cdcd31fc243c6d143983e3bda07cea9f387 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 23 Jul 2015 23:30:43 +0530 Subject: [PATCH 192/417] printlist: code refactoring --- src/me/ramswaroop/arrays/QuickSort.java | 1 + .../ramswaroop/common/DoubleLinkedList.java | 8 +-- .../ramswaroop/common/SingleLinkedList.java | 4 +- .../RemoveMiddlePointsFromLineSegments.java | 53 +++++++++++++++++++ 4 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java diff --git a/src/me/ramswaroop/arrays/QuickSort.java b/src/me/ramswaroop/arrays/QuickSort.java index b016fc51..35271753 100644 --- a/src/me/ramswaroop/arrays/QuickSort.java +++ b/src/me/ramswaroop/arrays/QuickSort.java @@ -48,6 +48,7 @@ public static int partition(int[] ar, int low, int high) { /** * Recursive Quick sort. + * NOTE: This function is tail-recursive. *

* Time complexity: * Best Case: O(nlogn) diff --git a/src/me/ramswaroop/common/DoubleLinkedList.java b/src/me/ramswaroop/common/DoubleLinkedList.java index d3f456ef..73c5191c 100644 --- a/src/me/ramswaroop/common/DoubleLinkedList.java +++ b/src/me/ramswaroop/common/DoubleLinkedList.java @@ -187,17 +187,17 @@ public static > void printList(DoubleLinkedNode node) } // prints the list from first node while (curr.next != null) { - out.print(curr.item + ","); + out.print(curr.item.toString() + ","); curr = curr.next; } - out.println(curr.item + "]"); + out.println(curr.item.toString() + "]"); // prints the list from last node out.print("["); while (curr.prev != null) { - out.print(curr.item + ","); + out.print(curr.item.toString() + ","); curr = curr.prev; } - out.println(curr.item + "]"); + out.println(curr.item.toString() + "]"); } public static > DoubleLinkedList getLinkedList(DoubleLinkedNode node) { diff --git a/src/me/ramswaroop/common/SingleLinkedList.java b/src/me/ramswaroop/common/SingleLinkedList.java index 829b2397..4b5b09e1 100644 --- a/src/me/ramswaroop/common/SingleLinkedList.java +++ b/src/me/ramswaroop/common/SingleLinkedList.java @@ -172,10 +172,10 @@ public static > void printList(SingleLinkedNode node) return; } while (curr.next != null) { - out.print(curr.item + ","); + out.print(curr.item.toString() + ","); curr = curr.next; } - out.println(curr.item + "]"); + out.println(curr.item.toString() + "]"); } public static > SingleLinkedList getLinkedList(SingleLinkedNode node) { diff --git a/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java b/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java new file mode 100644 index 00000000..fc402995 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java @@ -0,0 +1,53 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.SingleLinkedList; +import me.ramswaroop.common.SingleLinkedNode; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/23/15 + * @time: 11:18 PM + */ +public class RemoveMiddlePointsFromLineSegments { + + public static > void removeMiddlePointsFromLineSegments(SingleLinkedNode node) { + + } + + + public static void main(String a[]) { + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.add(new Point(0, 10)); + linkedList.add(new Point(1, 10)); + linkedList.add(new Point(3, 10)); + linkedList.add(new Point(10, 10)); + linkedList.add(new Point(10, 8)); + linkedList.add(new Point(10, 5)); + linkedList.add(new Point(20, 5)); + linkedList.add(new Point(40, 5)); + linkedList.printList(); + removeMiddlePointsFromLineSegments(linkedList.head); + linkedList.printList(); + } +} + +class Point implements Comparable { + int x, y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public String toString() { + return "(" + x + "," + y + ")"; + } + + @Override + public int compareTo(Point o) { + return 0; + } +} From de2a295f9459f2e4a0fc9bbae96b89263a08a932 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 23 Jul 2015 23:55:01 +0530 Subject: [PATCH 193/417] remove middle points from line segments: done --- .../RemoveMiddlePointsFromLineSegments.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java b/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java index fc402995..2c708fec 100644 --- a/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java +++ b/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java @@ -12,10 +12,28 @@ */ public class RemoveMiddlePointsFromLineSegments { - public static > void removeMiddlePointsFromLineSegments(SingleLinkedNode node) { + public static void removeMiddlePointsFromLineSegments(SingleLinkedNode node) { - } + SingleLinkedNode curr1 = node, curr2 = node; + while (curr1 != null && curr1.next != null) { + // vertical line + if (curr1.item.x == curr1.next.item.x) { + while (curr2.next != null && curr2.next.item.x == curr1.item.x) { + curr2 = curr2.next; + } + curr1.next = curr2; + } else if (curr1.item.y == curr1.next.item.y) { // horizontal line + while (curr2.next != null && curr2.next.item.y == curr1.item.y) { + curr2 = curr2.next; + } + curr1.next = curr2; + } else { + return; + } + curr1 = curr1.next; + } + } public static void main(String a[]) { SingleLinkedList linkedList = new SingleLinkedList<>(); @@ -34,6 +52,7 @@ public static void main(String a[]) { } class Point implements Comparable { + int x, y; Point(int x, int y) { From 207f582e69e8a2e3001e6c8ac2bb318701d3bdb5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 24 Jul 2015 10:55:32 +0530 Subject: [PATCH 194/417] remove middle points in line segments: comments + test case added --- .../RemoveMiddlePointsFromLineSegments.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java b/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java index 2c708fec..43905c5d 100644 --- a/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java +++ b/src/me/ramswaroop/linkedlists/RemoveMiddlePointsFromLineSegments.java @@ -12,6 +12,23 @@ */ public class RemoveMiddlePointsFromLineSegments { + /** + * Given a linked list of co-ordinates representing line segments, we have + * to remove those nodes which represent the middle points. + *

+ * Example: + * Input: + * (0,10)-> (1,10)-> (3,10)-> (10,10)-> (10,8)-> (10,5)-> (20,5)-> (40,5) + * Output: + * (0,10)-> (10,10)-> (10,5)-> (40,5) + *

+ * Input: + * (2,3)->(4,3)->(6,3)->(10,3)->(12,3) + * Output: + * (2,3)->(12,3) + * + * @param node + */ public static void removeMiddlePointsFromLineSegments(SingleLinkedNode node) { SingleLinkedNode curr1 = node, curr2 = node; @@ -29,6 +46,7 @@ public static void removeMiddlePointsFromLineSegments(SingleLinkedNode no } curr1.next = curr2; } else { + System.out.println("Linked list doesn't represent line segments!"); return; } curr1 = curr1.next; @@ -36,6 +54,7 @@ public static void removeMiddlePointsFromLineSegments(SingleLinkedNode no } public static void main(String a[]) { + // test case 1 SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(new Point(0, 10)); linkedList.add(new Point(1, 10)); @@ -48,6 +67,17 @@ public static void main(String a[]) { linkedList.printList(); removeMiddlePointsFromLineSegments(linkedList.head); linkedList.printList(); + + // test case 2 + SingleLinkedList linkedList2 = new SingleLinkedList<>(); + linkedList2.add(new Point(2, 3)); + linkedList2.add(new Point(4, 3)); + linkedList2.add(new Point(6, 3)); + linkedList2.add(new Point(10, 3)); + linkedList2.add(new Point(12, 3)); + linkedList2.printList(); + removeMiddlePointsFromLineSegments(linkedList2.head); + linkedList2.printList(); } } From 16d0372d504d37493d575855aa839e6b5957d6e4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 24 Jul 2015 14:42:46 +0530 Subject: [PATCH 195/417] stack with operations on middle element: done --- .../StackWithOperationOnMiddleElement.java | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/StackWithOperationOnMiddleElement.java diff --git a/src/me/ramswaroop/linkedlists/StackWithOperationOnMiddleElement.java b/src/me/ramswaroop/linkedlists/StackWithOperationOnMiddleElement.java new file mode 100644 index 00000000..6c6d48b7 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/StackWithOperationOnMiddleElement.java @@ -0,0 +1,118 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.DoubleLinkedNode; + +import java.util.EmptyStackException; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/24/15 + * @time: 1:06 PM + *

+ *

+ * Implement a stack with below operations in O(1) time complexity: + * 1) push() which adds an element to the top of stack. + * 2) pop() which removes an element from top of stack. + * 3) findMiddle() which will return middle element of the stack. + * 4) deleteMiddle() which will delete the middle element. + * Push and pop are standard stack operations. + * + * The idea is to use a double linked list to represent a stack with pointer pointing to the middle node. + */ +public class StackWithOperationOnMiddleElement> { + + int i = -1; + DoubleLinkedNode top, mid; + + public void push(E item) { + + top = new DoubleLinkedNode<>(null, item, top); + if (top.next != null) { + top.next.prev = top; + } else { + mid = top; + } + + if (i % 2 == 0) { + mid = mid.prev; + } + i++; + } + + public E pop() { + if (top == null) { + throw new EmptyStackException(); + } + + DoubleLinkedNode topNode = top; + if (top.next != null) { + top.next.prev = null; + } + top = top.next; + + i++; + if (i % 2 == 0) { + mid = mid.next; + } + + return topNode.item; + } + + public E getMiddleElement() { + if (mid == null) { + throw new EmptyStackException(); + } + return mid.item; + } + + /** + * Prints the content of the stack. + */ + public void print() { + DoubleLinkedNode curr = top; + out.print("["); + if (curr == null) { + out.println("]"); + return; + } + // prints the list from first node + while (curr.next != null) { + out.print(curr.item.toString() + ","); + curr = curr.next; + } + out.println(curr.item.toString() + "]"); + // prints the list from last node + out.print("["); + while (curr.prev != null) { + out.print(curr.item.toString() + ","); + curr = curr.prev; + } + out.println(curr.item.toString() + "]"); + } + + public static void main(String a[]) { + StackWithOperationOnMiddleElement stack = new StackWithOperationOnMiddleElement<>(); + stack.push(2); + stack.push(3); + stack.push(4); + stack.push(5); + stack.push(6); + stack.print(); + System.out.println("Mid: " + stack.getMiddleElement()); + stack.pop(); + stack.print(); + System.out.println("Mid: " + stack.getMiddleElement()); + stack.push(7); + stack.print(); + System.out.println("Mid: " + stack.getMiddleElement()); + stack.pop(); + stack.pop(); + stack.pop(); + stack.print(); + System.out.println("Mid: " + stack.getMiddleElement()); + } +} From 4c8b524978d01c50cf6cedab9ef9a979f8b4555e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 25 Jul 2015 15:32:12 +0530 Subject: [PATCH 196/417] sorted LL to BBST : initial commit --- .../linkedlists/SortedSLLToBBST.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/me/ramswaroop/linkedlists/SortedSLLToBBST.java diff --git a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java new file mode 100644 index 00000000..e6e824e7 --- /dev/null +++ b/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java @@ -0,0 +1,19 @@ +package me.ramswaroop.linkedlists; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/24/15 + * @time: 3:16 PM + */ +public class SortedSLLToBBST { + + public void SortedSLLToBBST() { + + } + + public static void main(String a[]) { + + } +} From 4e8c916c14176f8648cc102d6ee03d58e50ee2d8 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 25 Jul 2015 17:12:15 +0530 Subject: [PATCH 197/417] sorted SLL to B BST: almost done --- .../linkedlists/SortedSLLToBBST.java | 53 ++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java index e6e824e7..e8abf50f 100644 --- a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java @@ -1,5 +1,8 @@ package me.ramswaroop.linkedlists; +import me.ramswaroop.common.DoubleLinkedList; +import me.ramswaroop.common.DoubleLinkedNode; + /** * Created by IntelliJ IDEA. * @@ -9,11 +12,57 @@ */ public class SortedSLLToBBST { - public void SortedSLLToBBST() { + static > int getLength(DoubleLinkedNode node) { + int l = 0; + DoubleLinkedNode curr = node; + while (curr != null) { + curr = curr.next; + l++; + } + return l; + } + static > void inOrder(DoubleLinkedNode node) { + if (node == null) return; + inOrder(node.prev); + System.out.print(node.item.toString()); + inOrder(node.next); } - public static void main(String a[]) { + public static > DoubleLinkedNode sortedSLLToBBST(DoubleLinkedNode node) { + return sortedSLLToBBST(node, getLength(node)); + } + + public static > DoubleLinkedNode sortedSLLToBBST(DoubleLinkedNode node, int n) { + if (n <= 0) { + return null; + } + + DoubleLinkedNode left = sortedSLLToBBST(node, n / 2); + DoubleLinkedNode root = node; + root.prev = left; + + node = node.next; + + DoubleLinkedNode right = sortedSLLToBBST(node, n - n / 2 - 1); + root.next = right; + + return root; + } + + public static void main(String a[]) { + DoubleLinkedList linkedList = new DoubleLinkedList<>(); + linkedList.add(11); + linkedList.add(22); + linkedList.add(33); + linkedList.add(44); + linkedList.add(55); + linkedList.add(66); + linkedList.add(77); + linkedList.printList(); + inOrder(sortedSLLToBBST(linkedList.head)); + System.out.println(); + linkedList.printList(); } } From 498b197a4e7f6ef34f60289854aaa4ec06fbd2c6 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 25 Jul 2015 17:28:19 +0530 Subject: [PATCH 198/417] file renamed --- .../linkedlists/{SortedSLLToBBST.java => SortedDLLToBBST.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/me/ramswaroop/linkedlists/{SortedSLLToBBST.java => SortedDLLToBBST.java} (98%) diff --git a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java similarity index 98% rename from src/me/ramswaroop/linkedlists/SortedSLLToBBST.java rename to src/me/ramswaroop/linkedlists/SortedDLLToBBST.java index e8abf50f..da9726f7 100644 --- a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java @@ -10,7 +10,7 @@ * @date: 7/24/15 * @time: 3:16 PM */ -public class SortedSLLToBBST { +public class SortedDLLToBBST { static > int getLength(DoubleLinkedNode node) { int l = 0; From 46cdb7ed1e9c17b2b6d66421864267178cc2aaeb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 25 Jul 2015 23:41:14 +0530 Subject: [PATCH 199/417] file renamed --- .../linkedlists/{SortedSLLToBBST.java => SortedDLLToBBST.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/me/ramswaroop/linkedlists/{SortedSLLToBBST.java => SortedDLLToBBST.java} (98%) diff --git a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java similarity index 98% rename from src/me/ramswaroop/linkedlists/SortedSLLToBBST.java rename to src/me/ramswaroop/linkedlists/SortedDLLToBBST.java index e8abf50f..da9726f7 100644 --- a/src/me/ramswaroop/linkedlists/SortedSLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java @@ -10,7 +10,7 @@ * @date: 7/24/15 * @time: 3:16 PM */ -public class SortedSLLToBBST { +public class SortedDLLToBBST { static > int getLength(DoubleLinkedNode node) { int l = 0; From fda97924dc427d30be6be3720336ee48a6480298 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 25 Jul 2015 23:47:35 +0530 Subject: [PATCH 200/417] testing 2FA --- src/me/ramswaroop/linkedlists/SortedDLLToBBST.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java index da9726f7..8e2ea5e4 100644 --- a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java @@ -29,6 +29,13 @@ static > void inOrder(DoubleLinkedNode node) { inOrder(node.next); } + /** + * Converts a sorted doubly linked list to a balanced binary tree in-place. + * + * @param node + * @param + * @return + */ public static > DoubleLinkedNode sortedSLLToBBST(DoubleLinkedNode node) { return sortedSLLToBBST(node, getLength(node)); } From b959967286492e99311fe5bb56738f14aaa8f61b Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 25 Jul 2015 23:53:36 +0530 Subject: [PATCH 201/417] testing 2FA --- src/me/ramswaroop/linkedlists/SortedDLLToBBST.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java index 8e2ea5e4..db15402c 100644 --- a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java @@ -12,6 +12,12 @@ */ public class SortedDLLToBBST { + /** + * + * @param node + * @param + * @return + */ static > int getLength(DoubleLinkedNode node) { int l = 0; DoubleLinkedNode curr = node; @@ -22,6 +28,11 @@ static > int getLength(DoubleLinkedNode node) { return l; } + /** + * + * @param node + * @param + */ static > void inOrder(DoubleLinkedNode node) { if (node == null) return; inOrder(node.prev); From 1d02f36a26b730b9cf2e418cfd4b9841fe5873c3 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 25 Jul 2015 23:55:23 +0530 Subject: [PATCH 202/417] testing 2FA --- src/me/ramswaroop/linkedlists/SortedDLLToBBST.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java index db15402c..dbf89005 100644 --- a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java @@ -13,6 +13,7 @@ public class SortedDLLToBBST { /** + * Returns the number of nodes in the doubly linked list. * * @param node * @param From 573264ef8dcb093faffe81a8e49045e756342588 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 26 Jul 2015 12:45:18 +0530 Subject: [PATCH 203/417] flatten multi level linked list: done --- .../ramswaroop/common/DoubleLinkedNode.java | 4 + .../ramswaroop/common/SingleLinkedNode.java | 4 + .../FlattenMultiLevelLinkedList.java | 94 +++++++++++++++++++ .../linkedlists/SortedDLLToBBST.java | 12 +-- 4 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java diff --git a/src/me/ramswaroop/common/DoubleLinkedNode.java b/src/me/ramswaroop/common/DoubleLinkedNode.java index caebe339..6790f532 100644 --- a/src/me/ramswaroop/common/DoubleLinkedNode.java +++ b/src/me/ramswaroop/common/DoubleLinkedNode.java @@ -13,6 +13,10 @@ public class DoubleLinkedNode> { public DoubleLinkedNode next; public DoubleLinkedNode prev; + public DoubleLinkedNode(E item) { + this(null, item, null); + } + public DoubleLinkedNode(DoubleLinkedNode prev, E item, DoubleLinkedNode next) { this.item = item; this.next = next; diff --git a/src/me/ramswaroop/common/SingleLinkedNode.java b/src/me/ramswaroop/common/SingleLinkedNode.java index e1b006e6..ce5b09c1 100644 --- a/src/me/ramswaroop/common/SingleLinkedNode.java +++ b/src/me/ramswaroop/common/SingleLinkedNode.java @@ -12,6 +12,10 @@ public class SingleLinkedNode> { public E item; public SingleLinkedNode next; + public SingleLinkedNode(E item) { + this(item, null); + } + public SingleLinkedNode(E item, SingleLinkedNode next) { this.item = item; this.next = next; diff --git a/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java b/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java new file mode 100644 index 00000000..aef02aff --- /dev/null +++ b/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java @@ -0,0 +1,94 @@ +package me.ramswaroop.linkedlists; + +import me.ramswaroop.common.DoubleLinkedNode; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/26/15 + * @time: 12:08 PM + */ +public class FlattenMultiLevelLinkedList { + + /** + * Flattens a multilevel linked list into a single level linked list. You can + * {@see http://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/} for + * clarity on question. + * + * @param node + * @param + * @return + */ + public static > DoubleLinkedNode flatten(DoubleLinkedNode node) { + DoubleLinkedNode curr = node, tail; + + // set tail to last node in 1st level + while (curr.next != null) { + curr = curr.next; + } + tail = curr; + + curr = node; + while (curr != null) { + if (curr.prev != null) { + // append child to tail + tail.next = curr.prev; + // update tail + while (tail.next != null) { + tail = tail.next; + } + } + curr = curr.next; + } + return node; + } + + /** + * Prints the list. + * + * @param node + * @param + */ + public static > void printList(DoubleLinkedNode node) { + DoubleLinkedNode curr = node; + out.print("["); + if (curr == null) { + out.println("]"); + return; + } + while (curr.next != null) { + out.print(curr.item.toString() + ","); + curr = curr.next; + } + out.println(curr.item.toString() + "]"); + } + + public static void main(String a[]) { + // 1st level + DoubleLinkedNode head = new DoubleLinkedNode<>(1); + head.next = new DoubleLinkedNode<>(5); + head.next.next = new DoubleLinkedNode<>(4); + head.next.next.next = new DoubleLinkedNode<>(8); + head.next.next.next.next = new DoubleLinkedNode<>(9); + // 2nd level under node 1 + head.prev = new DoubleLinkedNode<>(10); + head.prev.next = new DoubleLinkedNode<>(10); + head.prev.next.next = new DoubleLinkedNode<>(12); + head.prev.next.next.next = new DoubleLinkedNode<>(14); + // 2nd level under node 2 + head.next.prev = new DoubleLinkedNode<>(16); + head.next.prev.next = new DoubleLinkedNode<>(17); + head.next.prev.next.next = new DoubleLinkedNode<>(18); + head.next.prev.next.next.next = new DoubleLinkedNode<>(20); + // 3rd level under node 2 + head.next.prev.prev = new DoubleLinkedNode<>(22); + head.next.prev.prev.next = new DoubleLinkedNode<>(24); + head.next.prev.prev.next.next = new DoubleLinkedNode<>(26); + head.next.prev.prev.next.next.next = new DoubleLinkedNode<>(28); + // after flattening + printList(flatten(head)); + } +} diff --git a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java index 8e2ea5e4..86dacc02 100644 --- a/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java +++ b/src/me/ramswaroop/linkedlists/SortedDLLToBBST.java @@ -36,23 +36,23 @@ static > void inOrder(DoubleLinkedNode node) { * @param * @return */ - public static > DoubleLinkedNode sortedSLLToBBST(DoubleLinkedNode node) { - return sortedSLLToBBST(node, getLength(node)); + public static > DoubleLinkedNode sortedDLLToBBST(DoubleLinkedNode node) { + return sortedDLLToBBST(node, getLength(node)); } - public static > DoubleLinkedNode sortedSLLToBBST(DoubleLinkedNode node, int n) { + public static > DoubleLinkedNode sortedDLLToBBST(DoubleLinkedNode node, int n) { if (n <= 0) { return null; } - DoubleLinkedNode left = sortedSLLToBBST(node, n / 2); + DoubleLinkedNode left = sortedDLLToBBST(node, n / 2); DoubleLinkedNode root = node; root.prev = left; node = node.next; - DoubleLinkedNode right = sortedSLLToBBST(node, n - n / 2 - 1); + DoubleLinkedNode right = sortedDLLToBBST(node, n - n / 2 - 1); root.next = right; return root; @@ -68,7 +68,7 @@ public static void main(String a[]) { linkedList.add(66); linkedList.add(77); linkedList.printList(); - inOrder(sortedSLLToBBST(linkedList.head)); + inOrder(sortedDLLToBBST(linkedList.head)); System.out.println(); linkedList.printList(); } From b1b453330cf8961db00b7b334790988491a4294c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 26 Jul 2015 12:50:16 +0530 Subject: [PATCH 204/417] flatten multi level linked list: comments added --- .../linkedlists/FlattenMultiLevelLinkedList.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java b/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java index aef02aff..eb600bbf 100644 --- a/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java +++ b/src/me/ramswaroop/linkedlists/FlattenMultiLevelLinkedList.java @@ -18,6 +18,19 @@ public class FlattenMultiLevelLinkedList { * {@see http://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/} for * clarity on question. * + * Solution: + * 1) Take "cur" pointer, which will point to head of the fist level of the list + * 2) Take "tail" pointer, which will point to end of the first level of the list + * 3) Repeat the below procedure while "curr" is not NULL. + * I) if current node has a child then + * a) append this new child list to the "tail" + * tail->next = cur->child + * b) find the last node of new child list and update "tail" + * while (tail->next != null) { + * tail = tail->next; + * } + * II) move to the next node. i.e. cur = cur->next + * * @param node * @param * @return From 405c9ed778a0f44c9354b23e62ca5660eddcba7e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 27 Jul 2015 16:14:45 +0530 Subject: [PATCH 205/417] merge array n into array of m+n: done --- .../MergeArrayOfNintoArrayOfMplusN.java | 66 +++++++++++++++++++ .../arrays/PivotedBinarySearch.java | 20 ++++++ 2 files changed, 86 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MergeArrayOfNintoArrayOfMplusN.java diff --git a/src/me/ramswaroop/arrays/MergeArrayOfNintoArrayOfMplusN.java b/src/me/ramswaroop/arrays/MergeArrayOfNintoArrayOfMplusN.java new file mode 100644 index 00000000..51c1b72a --- /dev/null +++ b/src/me/ramswaroop/arrays/MergeArrayOfNintoArrayOfMplusN.java @@ -0,0 +1,66 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/27/15 + * @time: 12:15 PM + */ +public class MergeArrayOfNIntoArrayOfMPlusN { + + private static final int NA = -1; + + /** + * Move non {@code NA} elements to the end of array leaving everything else unchanged. + *

+ * For example, + * Input: {2, NA, 7, NA, NA, 10, NA}; + * Output: {2, NA, 7, NA, 2, 7, 10} + * + * @param arrayMPlusN + */ + public static void moveElementsToEnd(int[] arrayMPlusN) { + int i = arrayMPlusN.length - 1, j = i; + for (; i >= 0; i--) { + if (arrayMPlusN[i] != NA) { + arrayMPlusN[j] = arrayMPlusN[i]; + j--; + } + } + } + + /** + * Merge {@param n} into {@param mPlusN} + * + * @param mPlusN + * @param n + */ + public static void merge(int[] mPlusN, int[] n) { + moveElementsToEnd(mPlusN); + + int i = n.length, // current index in mPlusN[] + j = 0, // current index in n[] + k = 0; // current index in final result + + while (k < mPlusN.length) { + if (j == n.length || (i < mPlusN.length && mPlusN[i] < n[j])) { + mPlusN[k] = mPlusN[i]; + i++; + } else { + mPlusN[k] = n[j]; + j++; + } + k++; + } + } + + public static void main(String a[]) { + int[] mPlusN = {2, NA, 12, NA, NA, 14, NA}; + int[] n = {5, 7, 8, 10}; + merge(mPlusN, n); + System.out.println(Arrays.toString(mPlusN)); + } +} diff --git a/src/me/ramswaroop/arrays/PivotedBinarySearch.java b/src/me/ramswaroop/arrays/PivotedBinarySearch.java index edb79772..aa5b5a98 100644 --- a/src/me/ramswaroop/arrays/PivotedBinarySearch.java +++ b/src/me/ramswaroop/arrays/PivotedBinarySearch.java @@ -11,6 +11,17 @@ */ public class PivotedBinarySearch { + /** + * Search an element in a sorted pivoted array {@param a}. + *

+ * Example, + * 1) For array [3,4,5,1,2] pivot is 5 + * 2) For array [6,7,8,5,4] pivot is 8 + * + * @param a + * @param n + * @return + */ public static int pivotedBinarySearch(int a[], int n) { int pivot = findPivot(a, 0, a.length - 1); @@ -23,6 +34,15 @@ public static int pivotedBinarySearch(int a[], int n) { } } + /** + * Finds the pivot element in array {@param a}. Pivot element is the only + * element for which next element to it is smaller than it. + * + * @param a + * @param low + * @param high + * @return + */ public static int findPivot(int a[], int low, int high) { if (low > high) return -1; if (low == high) return low; From 8e1136405ab74c4275177cd16936413c53995814 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 27 Jul 2015 20:39:42 +0530 Subject: [PATCH 206/417] median of 2 sorted arrays: done --- .../arrays/MedianOfTwoSortedArrays.java | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MedianOfTwoSortedArrays.java diff --git a/src/me/ramswaroop/arrays/MedianOfTwoSortedArrays.java b/src/me/ramswaroop/arrays/MedianOfTwoSortedArrays.java new file mode 100644 index 00000000..24995176 --- /dev/null +++ b/src/me/ramswaroop/arrays/MedianOfTwoSortedArrays.java @@ -0,0 +1,104 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/27/15 + * @time: 5:50 PM + */ +public class MedianOfTwoSortedArrays { + + /** + * Returns the median of a sorted array {@param a}. + * + * @param a + * @return + */ + public static int median(int a[]) { + int l = a.length; + if (l % 2 == 0) { + return (a[l / 2] + a[l / 2 - 1]) / 2; + } else { + return a[l / 2]; + } + } + + /** + * Returns the median of two sorted arrays {@param a1} and {@param a2} having same length. + * In case of any error, it returns {@code -1}. + *

+ * Example: + *

+ *

+ * ar1[] = {1, 12, 15, 26, 38} + * ar2[] = {2, 13, 17, 30, 45} + * For above two arrays m1 = 15 and m2 = 17 + *

+ * For the above ar1[] and ar2[], m1 is smaller than m2. So median is present in one of + * the following two sub-arrays: + *

+ * [15, 26, 38] and [2, 13, 17] + * Let us repeat the process for above two sub-arrays: + *

+ * m1 = 26 m2 = 13. + * m1 is greater than m2. So the sub-arrays become + *

+ * [15, 26] and [13, 17] + * Now size is 2, so median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2 + * = (max(15, 13) + min(26, 17))/2 + * = (15 + 17)/2 + * = 16 + * + * @param a1 + * @param a2 + * @return + */ + public static int median(int[] a1, int[] a2) { + + int l1 = a1.length, l2 = a2.length, m1, m2; + + if (l1 != l2 || l1 <= 0) { + return -1; + } + + if (l1 == 1) { + return (a1[0] + a2[0]) / 2; + } + + if (l1 == 2) { + return (Math.max(a1[0], a2[0]) + Math.min(a1[1], a2[1])) / 2; + } + + m1 = median(a1); + m2 = median(a2); + + if (m1 == m2) { + return m1; + } + + if (m1 < m2) { // median exists in a1[m1....] and a2[....m2] + if (l1 % 2 == 0) { + return median(Arrays.copyOfRange(a1, l1 / 2 - 1, l1), Arrays.copyOfRange(a2, 0, l2 / 2 + 1)); + } else { + return median(Arrays.copyOfRange(a1, l1 / 2, l1), Arrays.copyOfRange(a2, 0, l2 / 2 + 1)); + } + } else { + if (l1 % 2 == 0) { // median exists in a1[....m1] and a2 [m2....] + return median(Arrays.copyOfRange(a1, 0, l1 / 2 + 1), Arrays.copyOfRange(a2, l2 / 2 - 1, l2)); + } else { + return median(Arrays.copyOfRange(a1, 0, l1 / 2 + 1), Arrays.copyOfRange(a2, l2 / 2, l2)); + } + } + } + + public static void main(String a[]) { + // test cases + System.out.println(median(new int[]{1, 2, 3, 6}, new int[]{4, 6, 8, 9})); + System.out.println(median(new int[]{4, 6, 8, 9}, new int[]{1, 2, 3, 6})); + System.out.println(median(new int[]{1, 2}, new int[]{3, 4})); + System.out.println(median(new int[]{2, 2}, new int[]{2, 2})); + } +} From 5c745a7233df6c70ee16d08abd30d90bf3f9c2e0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 27 Jul 2015 21:02:47 +0530 Subject: [PATCH 207/417] reverse array: done --- src/me/ramswaroop/arrays/ReverseArray.java | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/me/ramswaroop/arrays/ReverseArray.java diff --git a/src/me/ramswaroop/arrays/ReverseArray.java b/src/me/ramswaroop/arrays/ReverseArray.java new file mode 100644 index 00000000..244812c5 --- /dev/null +++ b/src/me/ramswaroop/arrays/ReverseArray.java @@ -0,0 +1,41 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/27/15 + * @time: 8:40 PM + */ +public class ReverseArray { + + public static void reverse(int[] a) { + int temp; + for (int i = 0, j = a.length - 1; i < j; i++, j--) { + // swap elements + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + + public static void reverseRecursive(int[] a, int i, int j) { + if (i > j) return; + + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + reverseRecursive(a, ++i, --j); + } + + public static void main(String a[]) { + int[] ar = new int[]{1, 2, 3, 4, 5}; + System.out.println(Arrays.toString(ar)); + reverse(ar); + System.out.println(Arrays.toString(ar)); + reverseRecursive(ar, 0, ar.length - 1); + System.out.println(Arrays.toString(ar)); + } +} From 5de5bb663e23a79bbe9fcc02403a96fa329199da Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 28 Jul 2015 12:16:41 +0530 Subject: [PATCH 208/417] rotate array: done (naive method) --- src/me/ramswaroop/arrays/RotateArray.java | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/me/ramswaroop/arrays/RotateArray.java diff --git a/src/me/ramswaroop/arrays/RotateArray.java b/src/me/ramswaroop/arrays/RotateArray.java new file mode 100644 index 00000000..b903ca6c --- /dev/null +++ b/src/me/ramswaroop/arrays/RotateArray.java @@ -0,0 +1,45 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/28/15 + * @time: 10:53 AM + */ +public class RotateArray { + + /** + * Naive approach which stores the elements to be shifted in a temp array. + * Time complexity: O(n) + * Space complexity: O(k) + * + * @param a + * @param k + */ + public static void rotate(int[] a, int k) { + int[] temp = new int[k]; + int i, j; + // store elements to be shifted in temp array + for (i = 0; i < k; i++) { + temp[i] = a[i]; + } + // shift elements to left + for (j = 0; i < a.length; i++, j++) { + a[j] = a[i]; + } + // move elements to end + for (i = 0; j < a.length; i++, j++) { + a[j] = temp[i]; + } + } + + public static void main(String a[]) { + int[] ar = {1, 2, 3, 4, 5, 6, 7}; + System.out.println(Arrays.toString(ar)); + rotate(ar, 2); + System.out.println(Arrays.toString(ar)); + } +} From 59b9f5f7b22df7f03c5cf550af909d0ede1eff8e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 28 Jul 2015 17:28:38 +0530 Subject: [PATCH 209/417] rotate array: done (reversal method) --- src/me/ramswaroop/arrays/ReverseArray.java | 13 +++++ src/me/ramswaroop/arrays/RotateArray.java | 63 +++++++++++++++++++++- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/ReverseArray.java b/src/me/ramswaroop/arrays/ReverseArray.java index 244812c5..eb9fabdc 100644 --- a/src/me/ramswaroop/arrays/ReverseArray.java +++ b/src/me/ramswaroop/arrays/ReverseArray.java @@ -11,6 +11,11 @@ */ public class ReverseArray { + /** + * Iterative method to reverse the entire array. + * + * @param a + */ public static void reverse(int[] a) { int temp; for (int i = 0, j = a.length - 1; i < j; i++, j--) { @@ -21,6 +26,14 @@ public static void reverse(int[] a) { } } + /** + * Recursive method to reverse the array elements from + * {@param i} index to {@param j} index (both inclusive). + * + * @param a + * @param i + * @param j + */ public static void reverseRecursive(int[] a, int i, int j) { if (i > j) return; diff --git a/src/me/ramswaroop/arrays/RotateArray.java b/src/me/ramswaroop/arrays/RotateArray.java index b903ca6c..57a168bb 100644 --- a/src/me/ramswaroop/arrays/RotateArray.java +++ b/src/me/ramswaroop/arrays/RotateArray.java @@ -19,7 +19,7 @@ public class RotateArray { * @param a * @param k */ - public static void rotate(int[] a, int k) { + public static void rotateNaiveApproach(int[] a, int k) { int[] temp = new int[k]; int i, j; // store elements to be shifted in temp array @@ -36,10 +36,69 @@ public static void rotate(int[] a, int k) { } } + /** + * Reversal algorithm for array rotation. + *

+ * Example: + * For arr[] = [1, 2, 3, 4, 5, 6, 7], k = 2 and arr.length = 7 + * A = [1, 2] and B = [3, 4, 5, 6, 7] + * Reverse A, we get ArB = [2, 1, 3, 4, 5, 6, 7] + * Reverse B, we get ArBr = [2, 1, 7, 6, 5, 4, 3] + * Reverse all, we get (ArBr)r = [3, 4, 5, 6, 7, 1, 2] + * NOTE: Ar = Reverse of A + * + * @param a + * @param k + * @see: http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/ + */ + public static void rotateReversal(int[] a, int k) { + ReverseArray.reverseRecursive(a, 0, k - 1); + ReverseArray.reverseRecursive(a, k, a.length - 1); + ReverseArray.reverseRecursive(a, 0, a.length - 1); + } + + /** + * Juggling algorithm for array rotation. + * + * @param a + * @param k + * @see: http://www.geeksforgeeks.org/array-rotation/ + */ + public static void rotateGCD(int[] a, int k) { + int gcd = gcd(a.length, k), temp, i, j, p; + + for (i = 0; i < gcd; i++) { + temp = a[i]; + j = i; + while (true) { + p = j + k; + if (p >= a.length) + p = p - a.length; + if (p == i) + break; + a[j] = a[p]; + j = p; + } + a[j] = temp; + } + } + + public static int gcd(int a, int b) { + if (b == 0) { + return a; + } else { + return gcd(b, a % b); + } + } + public static void main(String a[]) { int[] ar = {1, 2, 3, 4, 5, 6, 7}; System.out.println(Arrays.toString(ar)); - rotate(ar, 2); + rotateNaiveApproach(ar, 2); + System.out.println(Arrays.toString(ar)); + rotateGCD(ar, 2); + System.out.println(Arrays.toString(ar)); + rotateReversal(ar, 2); System.out.println(Arrays.toString(ar)); } } From 2a8247dd7d9615dd0e091ee17722e7483698c3f7 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 29 Jul 2015 10:27:39 +0530 Subject: [PATCH 210/417] max sum non adjacent subsequence : done --- .../MaximumSumNonAdjacentSubsequence.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java diff --git a/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java b/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java new file mode 100644 index 00000000..3a348306 --- /dev/null +++ b/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java @@ -0,0 +1,42 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/29/15 + * @time: 9:18 AM + */ +public class MaximumSumNonAdjacentSubsequence { + + /** + * Given an array of positive numbers, finds the maximum sum of a sub-sequence + * with the constraint that no 2 numbers in the sub-sequence should be adjacent + * in the array. + *

+ * Example: + * 1) 3 2 7 10 should return 13 (sum of 3 and 10) + * 2) 3 2 5 10 7 should return 15 (sum of 3, 5 and 7). + * + * Here we maintain 2 variables incl and excl which is max sum till now (satisfying the constraint) + * including the current element and excluding the current element respectively. + * + * @param a + * @return + */ + public static int maximumSumNonAdjacentSubsequence(int[] a) { + int incl = a[0], excl = 0, prevIncl = incl; // incl is max sum including the current element + // and excl is max sum excluding the current element + for (int i = 1; i < a.length; i++) { + incl = excl + a[i]; // because we have to exclude the previous element if we consider the current element + excl = Math.max(prevIncl, excl); // we are excluding the current element so we can consider the previous element or dont + prevIncl = incl; + } + return Math.max(incl, excl); + } + + public static void main(String a[]) { + System.out.println(maximumSumNonAdjacentSubsequence(new int[]{3, 2, 7, 10})); + System.out.println(maximumSumNonAdjacentSubsequence(new int[]{3, 2, 5, 10, 7})); + } +} From 431635079d528d66636e8bac0c4171d68a6c508f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 29 Jul 2015 12:31:08 +0530 Subject: [PATCH 211/417] leaders in array : done --- src/me/ramswaroop/arrays/LeadersInArray.java | 45 ++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/me/ramswaroop/arrays/LeadersInArray.java diff --git a/src/me/ramswaroop/arrays/LeadersInArray.java b/src/me/ramswaroop/arrays/LeadersInArray.java new file mode 100644 index 00000000..837da57c --- /dev/null +++ b/src/me/ramswaroop/arrays/LeadersInArray.java @@ -0,0 +1,45 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/29/15 + * @time: 12:06 PM + */ +public class LeadersInArray { + + /** + * Returns an array containing all leaders present in {@param a}. + * An element is a LEADER if its greater than all elements to + * the right of it in the array. + * + * @param a + * @return + */ + public static int[] getAllLeaders(int[] a) { + + int i = a.length - 2, j = 0; + int[] leaders = new int[a.length]; + + // rightmost element is always a leader + leaders[0] = a[a.length - 1]; + + for (; i >= 0; i--) { + if (a[i] > leaders[j]) { + leaders[++j] = a[i]; + } + } + + // omit the extra space which aren't filled with leaders + return Arrays.copyOfRange(leaders, 0, j + 1); + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getAllLeaders(new int[]{16, 17, 4, 3, 5, 2}))); + System.out.println(Arrays.toString(getAllLeaders(new int[]{16, 1, 4, 3, 5, 12}))); + System.out.println(Arrays.toString(getAllLeaders(new int[]{16, 15, 14, 13, 12, 10}))); + } +} From 9d2e74ded3d80b154b79b74571989ce9d47839cb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 29 Jul 2015 20:46:57 +0530 Subject: [PATCH 212/417] inversions in array: done (simple/naive way) --- .../ramswaroop/arrays/InversionsInArray.java | 44 +++++++++++++++++++ src/me/ramswaroop/arrays/QuickSort.java | 11 ++++- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/arrays/InversionsInArray.java diff --git a/src/me/ramswaroop/arrays/InversionsInArray.java b/src/me/ramswaroop/arrays/InversionsInArray.java new file mode 100644 index 00000000..cf435f4f --- /dev/null +++ b/src/me/ramswaroop/arrays/InversionsInArray.java @@ -0,0 +1,44 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/29/15 + * @time: 8:37 PM + */ +public class InversionsInArray { + + /** + * Naive approach. + *

+ * INVERSION COUNT for an array indicates how far (or close) the array is from being + * sorted. If array is already sorted then inversion count is 0. If array is sorted in + * reverse order then inversion count is the maximum. + *

+ * Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j. + *

+ * Example: + * The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3). + * + * @param a + * @return + */ + public static int getInversionCountNaive(int[] a) { + int count = 0; + for (int i = 0; i < a.length - 2; i++) { + for (int j = 1; j < a.length - 1; j++) { + if (a[i] > a[j]) count++; + } + } + return count; + } + + public static int getInversionCount(int[] a) { + return 0; + } + + public static void main(String a[]) { + System.out.println(getInversionCountNaive(new int[]{2, 4, 1, 3, 5})); + } +} diff --git a/src/me/ramswaroop/arrays/QuickSort.java b/src/me/ramswaroop/arrays/QuickSort.java index 35271753..f0df4f35 100644 --- a/src/me/ramswaroop/arrays/QuickSort.java +++ b/src/me/ramswaroop/arrays/QuickSort.java @@ -66,10 +66,19 @@ public static void quickSort(int[] ar, int low, int high) { } } + /** + * Wrapper method to quick sort the entire array. + * + * @param a + */ + public static void quickSort(int[] a) { + quickSort(a, 0, a.length - 1); + } + public static void main(String a[]) { int[] ar = {3, 2, 1, 6, 4, 9, 7, 8}; System.out.println(Arrays.toString(ar)); - quickSort(ar, 0, ar.length - 1); + quickSort(ar); System.out.println(Arrays.toString(ar)); } } From aab245fd59a06a9bbe724a30cb2a5e242c593b30 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 29 Jul 2015 21:12:28 +0530 Subject: [PATCH 213/417] reverse linked list in groups : modified --- .../linkedlists/ReverseLinkedListInGroups.java | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java b/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java index 709ae4ce..4dbfa08b 100644 --- a/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java +++ b/src/me/ramswaroop/linkedlists/ReverseLinkedListInGroups.java @@ -10,7 +10,7 @@ * @date: 6/29/15 * @time: 2:32 PM */ -public class ReverseLinkedListInGroups> extends SingleLinkedList { +public class ReverseLinkedListInGroups { /** * Reverses the linked list in groups. @@ -27,7 +27,7 @@ public class ReverseLinkedListInGroups> extends SingleLi * @param k * @return */ - public SingleLinkedNode reverseLinkedListInGroups(SingleLinkedNode node, int k) { + public static > SingleLinkedNode reverseLinkedListInGroups(SingleLinkedNode node, int k) { SingleLinkedNode curr = node, prev = null, next = null; int i = 0; @@ -41,11 +41,6 @@ public SingleLinkedNode reverseLinkedListInGroups(SingleLinkedNode node, i i++; } - // update the head - if (node == head) { - head = prev; - } - // recursively call for the rest of the nodes in the linked list if (next != null) { node.next = reverseLinkedListInGroups(next, k); @@ -55,7 +50,7 @@ public SingleLinkedNode reverseLinkedListInGroups(SingleLinkedNode node, i } public static void main(String a[]) { - ReverseLinkedListInGroups linkedList = new ReverseLinkedListInGroups<>(); + SingleLinkedList linkedList = new SingleLinkedList<>(); linkedList.add(00); linkedList.add(11); linkedList.add(22); @@ -68,7 +63,6 @@ public static void main(String a[]) { linkedList.add(99); linkedList.add(100); linkedList.printList(); - linkedList.reverseLinkedListInGroups(linkedList.head, 3); - linkedList.printList(); + linkedList.printList(reverseLinkedListInGroups(linkedList.head, 3)); } } From 3f5b5bd691bd6053c228be1fd9d40c6e525d0042 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 29 Jul 2015 21:33:11 +0530 Subject: [PATCH 214/417] merge sort for arrays : done --- src/me/ramswaroop/arrays/MergeSort.java | 59 +++++++++++++++++++ .../ramswaroop/common/DoubleLinkedNode.java | 8 --- .../ramswaroop/common/SingleLinkedNode.java | 6 -- src/me/ramswaroop/linkedlists/MergeSort.java | 3 + 4 files changed, 62 insertions(+), 14 deletions(-) create mode 100644 src/me/ramswaroop/arrays/MergeSort.java diff --git a/src/me/ramswaroop/arrays/MergeSort.java b/src/me/ramswaroop/arrays/MergeSort.java new file mode 100644 index 00000000..4195cd6a --- /dev/null +++ b/src/me/ramswaroop/arrays/MergeSort.java @@ -0,0 +1,59 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/29/15 + * @time: 8:47 PM + */ +public class MergeSort { + + /** + * Merge sort. + *

+ * Time complexity: O(n log n) + * Space complexity: O(n) (also needs O(log n) stack space as it is recursive) + * + * @param a + * @return + */ + public static int[] mergeSort(int[] a) { + if (a.length == 1) return a; + + int[] x = mergeSort(Arrays.copyOfRange(a, 0, a.length / 2)); + int[] y = mergeSort(Arrays.copyOfRange(a, a.length / 2, a.length)); + + return merge(x, y); + } + + /** + * Merges two sorted arrays {@param a} and {@param b}. + * + * @param a + * @param b + * @return + */ + public static int[] merge(int[] a, int[] b) { + int lenA = a.length, lenB = b.length, k = 0; + int[] sortedArray = new int[lenA + lenB]; + + for (int i = 0, j = 0; i < lenA || j < lenB; ) { + if (j == lenB || (i < lenA && a[i] < b[j])) { + sortedArray[k++] = a[i++]; + } else { + sortedArray[k++] = b[j++]; + } + } + + return sortedArray; + } + + public static void main(String a[]) { + int[] ar = new int[]{3, 5, 1, 6, 9, 8}; + System.out.println(Arrays.toString(ar)); + System.out.println(Arrays.toString(mergeSort(ar))); + } +} diff --git a/src/me/ramswaroop/common/DoubleLinkedNode.java b/src/me/ramswaroop/common/DoubleLinkedNode.java index 6790f532..9ad9ec35 100644 --- a/src/me/ramswaroop/common/DoubleLinkedNode.java +++ b/src/me/ramswaroop/common/DoubleLinkedNode.java @@ -22,12 +22,4 @@ public DoubleLinkedNode(DoubleLinkedNode prev, E item, DoubleLinkedNode ne this.next = next; this.prev = prev; } - - public DoubleLinkedNode(DoubleLinkedNode node) { - if (node == null) return; - - this.item = node.item; - this.next = node.next; - this.prev = node.prev; - } } diff --git a/src/me/ramswaroop/common/SingleLinkedNode.java b/src/me/ramswaroop/common/SingleLinkedNode.java index ce5b09c1..3e8076d7 100644 --- a/src/me/ramswaroop/common/SingleLinkedNode.java +++ b/src/me/ramswaroop/common/SingleLinkedNode.java @@ -21,10 +21,4 @@ public SingleLinkedNode(E item, SingleLinkedNode next) { this.next = next; } - public SingleLinkedNode(SingleLinkedNode node) { - if (node == null) return; - - this.item = node.item; - this.next = node.next; - } } diff --git a/src/me/ramswaroop/linkedlists/MergeSort.java b/src/me/ramswaroop/linkedlists/MergeSort.java index b5a2bc32..d168d247 100644 --- a/src/me/ramswaroop/linkedlists/MergeSort.java +++ b/src/me/ramswaroop/linkedlists/MergeSort.java @@ -15,6 +15,9 @@ public class MergeSort { /** * Merge sort for linked list starting at {@param node}. * + * Time complexity: O(n log n) + * Space complexity: O(log n) stack space as it is recursive + * * @param node * @param * @return From 17354ee64039fb35cbbd0ef1e51c99fb9daaf34d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 30 Jul 2015 17:37:44 +0530 Subject: [PATCH 215/417] inversions in array: done --- .../ramswaroop/arrays/InversionsInArray.java | 64 ++++++++++++++++++- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/arrays/InversionsInArray.java b/src/me/ramswaroop/arrays/InversionsInArray.java index cf435f4f..60a1a6dd 100644 --- a/src/me/ramswaroop/arrays/InversionsInArray.java +++ b/src/me/ramswaroop/arrays/InversionsInArray.java @@ -1,5 +1,7 @@ package me.ramswaroop.arrays; +import java.util.Arrays; + /** * Created by IntelliJ IDEA. * @@ -9,6 +11,8 @@ */ public class InversionsInArray { + static int inversionCount = 0; + /** * Naive approach. *

@@ -24,7 +28,7 @@ public class InversionsInArray { * @param a * @return */ - public static int getInversionCountNaive(int[] a) { + public static int getInversionCountNaiveApproach(int[] a) { int count = 0; for (int i = 0; i < a.length - 2; i++) { for (int j = 1; j < a.length - 1; j++) { @@ -34,11 +38,65 @@ public static int getInversionCountNaive(int[] a) { return count; } + /** + * Optimized approach. + * + * Explanation: In merge() if a[i] > b[j] then all elements in array a starting + * from i are greater than b[j] which equals to the number of inversions for + * the two sub-arrays. + * + * @param a + * @return + * @see: http://www.geeksforgeeks.org/counting-inversions/ + */ public static int getInversionCount(int[] a) { - return 0; + mergeSort(a); + return inversionCount; + } + + /** + * Merge sort. + *

+ * Time complexity: O(n log n) + * Space complexity: O(n) (also needs O(log n) stack space as it is recursive) + * + * @param a + * @return + */ + public static int[] mergeSort(int[] a) { + if (a.length == 1) return a; + + int[] x = mergeSort(Arrays.copyOfRange(a, 0, a.length / 2)); + int[] y = mergeSort(Arrays.copyOfRange(a, a.length / 2, a.length)); + + return merge(x, y); + } + + /** + * Merges two sorted arrays {@param a} and {@param b}. + * + * @param a + * @param b + * @return + */ + public static int[] merge(int[] a, int[] b) { + int lenA = a.length, lenB = b.length, k = 0; + int[] sortedArray = new int[lenA + lenB]; + + for (int i = 0, j = 0; i < lenA || j < lenB; ) { + if (j == lenB || (i < lenA && a[i] < b[j])) { + sortedArray[k++] = a[i++]; + } else { + sortedArray[k++] = b[j++]; + inversionCount += lenA - i; + } + } + + return sortedArray; } public static void main(String a[]) { - System.out.println(getInversionCountNaive(new int[]{2, 4, 1, 3, 5})); + System.out.println(getInversionCountNaiveApproach(new int[]{2, 4, 1, 3, 5})); + System.out.println(getInversionCount(new int[]{2, 4, 1, 3, 5})); } } From 2580854fad6ac6ade9cf0ca9a0b3b5bfe2a00224 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 30 Jul 2015 23:04:57 +0530 Subject: [PATCH 216/417] two elements sum closest to zero : done --- .../arrays/TwoElementsSumClosestToZero.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java diff --git a/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java b/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java new file mode 100644 index 00000000..8e3cf0ad --- /dev/null +++ b/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java @@ -0,0 +1,44 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/30/15 + * @time: 5:44 PM + */ +public class TwoElementsSumClosestToZero { + + /** + * An array of integers is given containing both +ve and -ve numbers. You + * need to find two elements such that their sum is closest to zero. + * + * @param a + * @return + */ + public static int[] getTwoElementsWhoseSumIsClosestToZero(int[] a) { + QuickSort.quickSort(a); + + int minDiff = Math.abs(0 - (a[0] + a[a.length - 1])), n1 = a[0], n2 = a[a.length - 1]; + + for (int i = 1, j = a.length - 2; i < j; ) { + if (Math.abs(0 - (a[i] + a[j])) < minDiff) { + minDiff = Math.abs(0 - (a[i] + a[j])); + n1 = a[i]; + n2 = a[j]; + i++; + } else { + j--; + } + } + + return new int[]{n1, n2}; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getTwoElementsWhoseSumIsClosestToZero(new int[]{1, 60, -10, -80, 85, 70}))); + System.out.println(Arrays.toString(getTwoElementsWhoseSumIsClosestToZero(new int[]{-3, -100, -10, -80, 85, 70}))); + } +} From b384abf7e498315af449e971b565258f497982be Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 30 Jul 2015 23:23:57 +0530 Subject: [PATCH 217/417] smallest and second smallest no in array : done --- .../arrays/SmallestAndSecondSmallest.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SmallestAndSecondSmallest.java diff --git a/src/me/ramswaroop/arrays/SmallestAndSecondSmallest.java b/src/me/ramswaroop/arrays/SmallestAndSecondSmallest.java new file mode 100644 index 00000000..4519a539 --- /dev/null +++ b/src/me/ramswaroop/arrays/SmallestAndSecondSmallest.java @@ -0,0 +1,33 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/30/15 + * @time: 11:13 PM + */ +public class SmallestAndSecondSmallest { + + public static int[] getSmallestAndSecondSmallest(int[] a) { + int smallest = Integer.MAX_VALUE, secondSmallest = Integer.MAX_VALUE; + + for (int i = 0; i < a.length; i++) { + if (a[i] < smallest) { + secondSmallest = smallest; + smallest = a[i]; + } else if (a[i] < secondSmallest && a[i] != smallest) { // a[i] != smallest; if numbers are repeated in array + secondSmallest = a[i]; + } + } + + return new int[]{smallest, secondSmallest}; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getSmallestAndSecondSmallest(new int[]{100, 1, 60, -10, -80, 85, 70, -80}))); + System.out.println(Arrays.toString(getSmallestAndSecondSmallest(new int[]{100, 1, 60, 10, 80, 85, 70, 0}))); + } +} From fca10d2037fb132d8807ce8ce524b63932635f59 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 31 Jul 2015 14:21:48 +0530 Subject: [PATCH 218/417] majority element in sorted array : done --- .../arrays/MajorityElementInSortedArray.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MajorityElementInSortedArray.java diff --git a/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java b/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java new file mode 100644 index 00000000..257429fe --- /dev/null +++ b/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java @@ -0,0 +1,69 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/31/15 + * @time: 10:02 AM + */ +public class MajorityElementInSortedArray { + + /** + * Checks if {@param n} is a majority element in array {@param a} + * by performing a binary search. + *

+ * Time complexity: O(log n) + * + * @param a + * @param n + * @return + */ + public static boolean isMajorityElement(int[] a, int n) { + int l = a.length; + int startIndex = getIndexOf(a, 0, l - 1, n); + + if (startIndex + l / 2 < l && a[startIndex + l / 2] == n) { + return true; + } else { + return false; + } + + } + + /** + * Returns the index of first occurrence of {@param n} in array {@param a}. + * + * @param a + * @param low + * @param high + * @param n + * @return + */ + public static int getIndexOf(int[] a, int low, int high, int n) { + int mid = (low + high) / 2; + if (low < high) { + /** + * Check if a[mid] is the first occurrence of n: + * a[mid] is first occurrence if n is one of the following + * is true: + * (i) mid == 0 and a[mid] == n + * (ii) n > a[mid-1] and a[mid] == n + */ + if ((mid == 0 || n > a[mid - 1]) && (a[mid] == n)) { + return mid; + } else if (n < a[mid]) { + getIndexOf(a, low, mid - 1, n); + } else { + getIndexOf(a, mid + 1, high, n); + } + } + return -1; + } + + public static void main(String a[]) { + System.out.println(isMajorityElement(new int[]{1, 2}, 2)); + System.out.println(isMajorityElement(new int[]{1, 2, 2, 2, 2, 2, 3, 3}, 2)); + System.out.println(isMajorityElement(new int[]{1, 2, 2, 2, 2, 2, 3, 3}, 3)); + } +} From 8b3ddc28d84ef451a9c7dee3276e4fd40d447fd8 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 31 Jul 2015 14:54:12 +0530 Subject: [PATCH 219/417] majority element in sorted array : minor fix --- .../arrays/MajorityElementInSortedArray.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java b/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java index 257429fe..9588a658 100644 --- a/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java +++ b/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java @@ -23,6 +23,9 @@ public static boolean isMajorityElement(int[] a, int n) { int l = a.length; int startIndex = getIndexOf(a, 0, l - 1, n); + // element not found + if (startIndex == -1) return false; + if (startIndex + l / 2 < l && a[startIndex + l / 2] == n) { return true; } else { @@ -41,8 +44,8 @@ public static boolean isMajorityElement(int[] a, int n) { * @return */ public static int getIndexOf(int[] a, int low, int high, int n) { - int mid = (low + high) / 2; - if (low < high) { + if (low <= high) { + int mid = (low + high) / 2; /** * Check if a[mid] is the first occurrence of n: * a[mid] is first occurrence if n is one of the following @@ -52,18 +55,19 @@ public static int getIndexOf(int[] a, int low, int high, int n) { */ if ((mid == 0 || n > a[mid - 1]) && (a[mid] == n)) { return mid; - } else if (n < a[mid]) { - getIndexOf(a, low, mid - 1, n); + } else if (n <= a[mid]) { + return getIndexOf(a, low, mid - 1, n); } else { - getIndexOf(a, mid + 1, high, n); + return getIndexOf(a, mid + 1, high, n); } } return -1; } public static void main(String a[]) { + System.out.println(isMajorityElement(new int[]{2, 2}, 2)); System.out.println(isMajorityElement(new int[]{1, 2}, 2)); System.out.println(isMajorityElement(new int[]{1, 2, 2, 2, 2, 2, 3, 3}, 2)); - System.out.println(isMajorityElement(new int[]{1, 2, 2, 2, 2, 2, 3, 3}, 3)); + System.out.println(isMajorityElement(new int[]{1, 2, 2, 2, 2, 3, 3, 3}, 2)); } } From 85d4bfa661d6e115bc92429417ea2db38e6f0068 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 31 Jul 2015 17:09:41 +0530 Subject: [PATCH 220/417] max and min with min comparisons : done --- .../arrays/MaxMinWithMinComparisons.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MaxMinWithMinComparisons.java diff --git a/src/me/ramswaroop/arrays/MaxMinWithMinComparisons.java b/src/me/ramswaroop/arrays/MaxMinWithMinComparisons.java new file mode 100644 index 00000000..7aaf304d --- /dev/null +++ b/src/me/ramswaroop/arrays/MaxMinWithMinComparisons.java @@ -0,0 +1,59 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/31/15 + * @time: 3:16 PM + */ +public class MaxMinWithMinComparisons { + + /** + * Finds the minimum and maximum number in array {@param a} + * with minimum no. of comparisons. + *

+ * If length of array is even: + * No. of comparisons = 1+3*(n-2)/2 + * and if length is odd: + * No. of comparisons = 3*(n-1)/2 + * + * @param a + * @return + */ + public static int[] getMaxMinWithMinComparisons(int[] a) { + int min, max, i; + + if (a.length % 2 == 0) { // this is not a comparison + if (a[0] < a[1]) { // this is a comparison + min = a[0]; + max = a[1]; + } else { + min = a[1]; + max = a[0]; + } + i = 2; + } else { + min = max = a[0]; + i = 1; + } + + for (; i < a.length - 1; i += 2) { + if (a[i] < a[i + 1]) { // 1st comparison + if (a[i] < min) min = a[i]; // 2nd comparison + if (a[i + 1] > max) max = a[i + 1]; // 3rd comparison + } else { + if (a[i] > max) max = a[i]; // 2nd comparison + if (a[i + 1] < min) min = a[i + 1]; // 3rd comparison + } + } + + return new int[]{min, max}; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getMaxMinWithMinComparisons(new int[]{2, 5, 1, 6, 7, 9, 0, 8, 10}))); + } +} From 292118c05a0aa97b1a9f58b41817fdf8bfb1e23b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 31 Jul 2015 17:18:38 +0530 Subject: [PATCH 221/417] segregate 0s and 1s by traversing only once : done --- .../ramswaroop/arrays/Segregate0sAnd1s.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/me/ramswaroop/arrays/Segregate0sAnd1s.java diff --git a/src/me/ramswaroop/arrays/Segregate0sAnd1s.java b/src/me/ramswaroop/arrays/Segregate0sAnd1s.java new file mode 100644 index 00000000..2e0f4e06 --- /dev/null +++ b/src/me/ramswaroop/arrays/Segregate0sAnd1s.java @@ -0,0 +1,35 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/31/15 + * @time: 5:13 PM + */ +public class Segregate0sAnd1s { + + /** + * Segregate 0s and 1s by traversing the array only once. + * + * @param a + */ + public static void segregate0sAnd1s(int[] a) { + for (int i = 0, j = a.length - 1; i < j; i++, j--) { + if (a[i] > a[j]) { + // swap if a[i] > a[j] + a[i] = a[i] + a[j]; + a[j] = a[i] - a[j]; + a[i] = a[i] - a[j]; + } + } + } + + public static void main(String a[]) { + int[] ar = new int[]{0, 1, 1, 1, 0, 0, 1}; + segregate0sAnd1s(ar); + System.out.println(Arrays.toString(ar)); + } +} From 12be8d374906ca23f2987597334bea596c0c33a0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 1 Aug 2015 23:30:46 +0530 Subject: [PATCH 222/417] kth largest element : done (naive approach) --- .../ramswaroop/arrays/KthLargestElement.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/me/ramswaroop/arrays/KthLargestElement.java diff --git a/src/me/ramswaroop/arrays/KthLargestElement.java b/src/me/ramswaroop/arrays/KthLargestElement.java new file mode 100644 index 00000000..7280b37a --- /dev/null +++ b/src/me/ramswaroop/arrays/KthLargestElement.java @@ -0,0 +1,32 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/1/15 + * @time: 11:26 PM + */ +public class KthLargestElement { + + /** + * Naive approach. + *

+ * Time complexity: O(n log n) + * + * @param a + * @param k + * @return + */ + public static int getKthLargestElement(int[] a, int k) { + if (k >= a.length) return -1; + + a = MergeSort.mergeSort(a); + + return a[a.length - k]; + } + + public static void main(String a[]) { + System.out.println(getKthLargestElement(new int[]{2, 4, 5, 7, 1, 8, 9}, 3)); + } +} From 469064b02f13de2101d620f5e8b7d27dd7886cdc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 2 Aug 2015 13:48:06 +0530 Subject: [PATCH 223/417] heaps : initial commit --- src/me/ramswaroop/common/Heap.java | 76 ++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/me/ramswaroop/common/Heap.java diff --git a/src/me/ramswaroop/common/Heap.java b/src/me/ramswaroop/common/Heap.java new file mode 100644 index 00000000..443c8c17 --- /dev/null +++ b/src/me/ramswaroop/common/Heap.java @@ -0,0 +1,76 @@ +package me.ramswaroop.common; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/2/15 + * @time: 11:57 AM + */ +public class Heap { + + public static void minHeapify(int[] a, int index) { + int smallest = index; + int leftIndex = 2 * index + 1; + int rightIndex = 2 * index + 2; + + if (leftIndex < a.length && a[index] > a[leftIndex]) { + smallest = leftIndex; + } + if (rightIndex < a.length && a[smallest] > a[rightIndex]) { + smallest = rightIndex; + } + + if (smallest != index) { + swap(a, index, smallest); + minHeapify(a, smallest); + } + } + + public static void buildMinHeap(int[] a) { + for (int i = a.length / 2 - 1; i >= 0; i--) { + minHeapify(a, i); + } + } + + public static void maxHeapify(int[] a, int index) { + int largest = index; + int leftIndex = 2 * index + 1; + int rightIndex = 2 * index + 2; + + if (leftIndex < a.length && a[index] < a[leftIndex]) { + largest = leftIndex; + } + if (rightIndex < a.length && a[largest] < a[rightIndex]) { + largest = rightIndex; + } + + if (largest != index) { + swap(a, index, largest); + maxHeapify(a, largest); + } + } + + public static void buildMaxHeap(int[] a) { + for (int i = a.length / 2 - 1; i >= 0; i--) { + maxHeapify(a, i); + } + } + + public static void swap(int[] a, int firstIndex, int secondIndex) { + a[firstIndex] = a[firstIndex] + a[secondIndex]; + a[secondIndex] = a[firstIndex] - a[secondIndex]; + a[firstIndex] = a[firstIndex] - a[secondIndex]; + } + + public static void main(String[] args) { + int[] a = new int[]{2, 4, 5, 1, 6, 7, 8}; + System.out.println(Arrays.toString(a)); + buildMaxHeap(a); + System.out.println(Arrays.toString(a)); + buildMinHeap(a); + System.out.println(Arrays.toString(a)); + } +} From 3ede999e657f20f3ba3c6f9c09d0ae15d53087cf Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 2 Aug 2015 17:45:27 +0530 Subject: [PATCH 224/417] heaps : definition/comments added --- src/me/ramswaroop/common/Heap.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/me/ramswaroop/common/Heap.java b/src/me/ramswaroop/common/Heap.java index 443c8c17..aa2ebf2c 100644 --- a/src/me/ramswaroop/common/Heap.java +++ b/src/me/ramswaroop/common/Heap.java @@ -4,6 +4,19 @@ /** * Created by IntelliJ IDEA. + *

+ * A HEAP is a specialized tree-based ABSTRACT DATA TYPE that satisfies the heap property: + * min-heap: All non-leaf elements are either smaller than or equal to their left and right child. + * max-heap: All non-leaf elements are either greater than or equal to their left and right child. + *

+ * Often implemented as an array, where the children of the element at index i are at index + * 2i+1 (left child) and 2i+2 (right child). + *

+ * The first element (minimum or maximum, depending on chosen order) can be found in O(1). + * Each successor can be found in O(log n). The algorithm in maxHeapify() takes O(log n) time + * Therefore, buildMaxHeap() would take O(n log n) time BUT IF OBSERVED CAREFULLY IT TAKES 0(N) TIME. + *

+ * Used in the HeapSort algorithm. Also can be used to implement a PriorityQueue. * * @author: ramswaroop * @date: 8/2/15 @@ -29,6 +42,11 @@ public static void minHeapify(int[] a, int index) { } } + /** + * Converts array {@param a} in to a max heap. + * + * @param a + */ public static void buildMinHeap(int[] a) { for (int i = a.length / 2 - 1; i >= 0; i--) { minHeapify(a, i); @@ -53,6 +71,11 @@ public static void maxHeapify(int[] a, int index) { } } + /** + * Converts array {@param a} in to a max heap. + * + * @param a + */ public static void buildMaxHeap(int[] a) { for (int i = a.length / 2 - 1; i >= 0; i--) { maxHeapify(a, i); From 73c82e24851a1052c280b22ce9ddc3a0b7685a32 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 2 Aug 2015 22:49:12 +0530 Subject: [PATCH 225/417] kth largest element : done (heap method) --- .../ramswaroop/arrays/KthLargestElement.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/KthLargestElement.java b/src/me/ramswaroop/arrays/KthLargestElement.java index 7280b37a..115ed494 100644 --- a/src/me/ramswaroop/arrays/KthLargestElement.java +++ b/src/me/ramswaroop/arrays/KthLargestElement.java @@ -1,5 +1,9 @@ package me.ramswaroop.arrays; +import me.ramswaroop.common.Heap; + +import java.util.Arrays; + /** * Created by IntelliJ IDEA. * @@ -18,7 +22,7 @@ public class KthLargestElement { * @param k * @return */ - public static int getKthLargestElement(int[] a, int k) { + public static int getKthLargestElementNaive(int[] a, int k) { if (k >= a.length) return -1; a = MergeSort.mergeSort(a); @@ -26,7 +30,29 @@ public static int getKthLargestElement(int[] a, int k) { return a[a.length - k]; } + /** + * Determines the kth largest element by building a max heap + * k times removing the root each time. + * + * @param a + * @param k + * @return + */ + public static int getKthLargestElement(int[] a, int k) { + while (true) { + Heap.buildMaxHeap(a); + if (k == 1) break; + + Heap.swap(a, 0, a.length - 1); + a = Arrays.copyOfRange(a, 0, a.length - 1); + k--; + } + + return a[0]; + } + public static void main(String a[]) { + System.out.println(getKthLargestElementNaive(new int[]{2, 4, 5, 7, 1, 8, 9}, 3)); System.out.println(getKthLargestElement(new int[]{2, 4, 5, 7, 1, 8, 9}, 3)); } } From 388a108cf782ccf249577d7fede075337eb6f84f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 3 Aug 2015 15:13:02 +0530 Subject: [PATCH 226/417] min heap and max heap : done --- .../ramswaroop/arrays/KthLargestElement.java | 14 ++-- .../common/{Heap.java => MaxHeap.java} | 37 +++------ src/me/ramswaroop/common/MinHeap.java | 80 +++++++++++++++++++ 3 files changed, 98 insertions(+), 33 deletions(-) rename src/me/ramswaroop/common/{Heap.java => MaxHeap.java} (73%) create mode 100644 src/me/ramswaroop/common/MinHeap.java diff --git a/src/me/ramswaroop/arrays/KthLargestElement.java b/src/me/ramswaroop/arrays/KthLargestElement.java index 115ed494..07086965 100644 --- a/src/me/ramswaroop/arrays/KthLargestElement.java +++ b/src/me/ramswaroop/arrays/KthLargestElement.java @@ -1,6 +1,6 @@ package me.ramswaroop.arrays; -import me.ramswaroop.common.Heap; +import me.ramswaroop.common.MaxHeap; import java.util.Arrays; @@ -40,10 +40,10 @@ public static int getKthLargestElementNaive(int[] a, int k) { */ public static int getKthLargestElement(int[] a, int k) { while (true) { - Heap.buildMaxHeap(a); + MaxHeap.buildMaxHeap(a); if (k == 1) break; - Heap.swap(a, 0, a.length - 1); + MaxHeap.swap(a, 0, a.length - 1); a = Arrays.copyOfRange(a, 0, a.length - 1); k--; } @@ -52,7 +52,11 @@ public static int getKthLargestElement(int[] a, int k) { } public static void main(String a[]) { - System.out.println(getKthLargestElementNaive(new int[]{2, 4, 5, 7, 1, 8, 9}, 3)); - System.out.println(getKthLargestElement(new int[]{2, 4, 5, 7, 1, 8, 9}, 3)); + int[] ar = new int[]{2, 4, 5, 7, 1, 8, 9}; + System.out.println(Arrays.toString(ar)); + System.out.println(getKthLargestElementNaive(ar, 3)); + System.out.println(Arrays.toString(ar)); + System.out.println(getKthLargestElement(ar, 3)); + System.out.println(Arrays.toString(ar)); } } diff --git a/src/me/ramswaroop/common/Heap.java b/src/me/ramswaroop/common/MaxHeap.java similarity index 73% rename from src/me/ramswaroop/common/Heap.java rename to src/me/ramswaroop/common/MaxHeap.java index aa2ebf2c..19d45d63 100644 --- a/src/me/ramswaroop/common/Heap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -22,37 +22,17 @@ * @date: 8/2/15 * @time: 11:57 AM */ -public class Heap { - - public static void minHeapify(int[] a, int index) { - int smallest = index; - int leftIndex = 2 * index + 1; - int rightIndex = 2 * index + 2; - - if (leftIndex < a.length && a[index] > a[leftIndex]) { - smallest = leftIndex; - } - if (rightIndex < a.length && a[smallest] > a[rightIndex]) { - smallest = rightIndex; - } - - if (smallest != index) { - swap(a, index, smallest); - minHeapify(a, smallest); - } - } +public class MaxHeap { /** - * Converts array {@param a} in to a max heap. + * Makes the array {@param a} satisfy the max heap property starting from + * {@param index} till the end of array. + *

+ * Time complexity: O(log n). * * @param a + * @param index */ - public static void buildMinHeap(int[] a) { - for (int i = a.length / 2 - 1; i >= 0; i--) { - minHeapify(a, i); - } - } - public static void maxHeapify(int[] a, int index) { int largest = index; int leftIndex = 2 * index + 1; @@ -73,6 +53,8 @@ public static void maxHeapify(int[] a, int index) { /** * Converts array {@param a} in to a max heap. + *

+ * Time complexity: O(n) and is not O(n log n). * * @param a */ @@ -88,12 +70,11 @@ public static void swap(int[] a, int firstIndex, int secondIndex) { a[firstIndex] = a[firstIndex] - a[secondIndex]; } + // test cases public static void main(String[] args) { int[] a = new int[]{2, 4, 5, 1, 6, 7, 8}; System.out.println(Arrays.toString(a)); buildMaxHeap(a); System.out.println(Arrays.toString(a)); - buildMinHeap(a); - System.out.println(Arrays.toString(a)); } } diff --git a/src/me/ramswaroop/common/MinHeap.java b/src/me/ramswaroop/common/MinHeap.java new file mode 100644 index 00000000..19d51118 --- /dev/null +++ b/src/me/ramswaroop/common/MinHeap.java @@ -0,0 +1,80 @@ +package me.ramswaroop.common; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + *

+ * A HEAP is a specialized tree-based ABSTRACT DATA TYPE that satisfies the heap property: + * min-heap: All non-leaf elements are either smaller than or equal to their left and right child. + * max-heap: All non-leaf elements are either greater than or equal to their left and right child. + *

+ * Often implemented as an array, where the children of the element at index i are at index + * 2i+1 (left child) and 2i+2 (right child). + *

+ * The first element (minimum or maximum, depending on chosen order) can be found in O(1). + * Each successor can be found in O(log n). The algorithm in minHeapify() takes O(log n) time + * Therefore, buildMinHeap() would take O(n log n) time BUT IF OBSERVED CAREFULLY IT TAKES 0(N) TIME. + *

+ * Used in the HeapSort algorithm. Also can be used to implement a PriorityQueue. + * + * @author: ramswaroop + * @date: 8/2/15 + * @time: 11:57 AM + */ +public class MinHeap { + + /** + * Makes the array {@param a} satisfy the min heap property starting from + * {@param index} till the end of array. + *

+ * Time complexity: O(log n). + * + * @param a + * @param index + */ + public static void minHeapify(int[] a, int index) { + int smallest = index; + int leftIndex = 2 * index + 1; + int rightIndex = 2 * index + 2; + + if (leftIndex < a.length && a[index] > a[leftIndex]) { + smallest = leftIndex; + } + if (rightIndex < a.length && a[smallest] > a[rightIndex]) { + smallest = rightIndex; + } + + if (smallest != index) { + swap(a, index, smallest); + minHeapify(a, smallest); + } + } + + /** + * Converts array {@param a} in to a min heap. + *

+ * Time complexity: O(n) and is not O(n log n). + * + * @param a + */ + public static void buildMinHeap(int[] a) { + for (int i = a.length / 2 - 1; i >= 0; i--) { + minHeapify(a, i); + } + } + + public static void swap(int[] a, int firstIndex, int secondIndex) { + a[firstIndex] = a[firstIndex] + a[secondIndex]; + a[secondIndex] = a[firstIndex] - a[secondIndex]; + a[firstIndex] = a[firstIndex] - a[secondIndex]; + } + + // test cases + public static void main(String[] args) { + int[] a = new int[]{2, 4, 5, 1, 6, 7, 8}; + System.out.println(Arrays.toString(a)); + buildMinHeap(a); + System.out.println(Arrays.toString(a)); + } +} From d676d4a63896c26013b185d520b8820885128117 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 3 Aug 2015 18:03:17 +0530 Subject: [PATCH 227/417] k largest elements : done --- .../ramswaroop/arrays/KLargestElements.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/me/ramswaroop/arrays/KLargestElements.java diff --git a/src/me/ramswaroop/arrays/KLargestElements.java b/src/me/ramswaroop/arrays/KLargestElements.java new file mode 100644 index 00000000..eef26002 --- /dev/null +++ b/src/me/ramswaroop/arrays/KLargestElements.java @@ -0,0 +1,54 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.common.MinHeap; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/3/15 + * @time: 3:47 PM + */ +public class KLargestElements { + + /** + * Finds {@param k} largest elements in array {@param a}. + * + * Algorithm: + * 1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. This takes O(k) time. + * + * 2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH. + * ……a) If the element is greater than the root then make it root and call buildHeap for MH + * ……b) Else ignore it. + * This step takes (n-k) * O(k) time. + * + * 3) Finally, MH has k largest elements and root of the MH is the kth largest element. + * + * Therefore, the total time complexity of the above algorithm is: O(k) + (n-k) * O(k). + * + * @param a + * @param k + * @return + */ + public static int[] getKLargestElements(int[] a, int k) { + + int[] kElements = Arrays.copyOfRange(a, 0, k); + + MinHeap.buildMinHeap(kElements); + + for (int i = k; i < a.length; i++) { + if (a[i] > kElements[0]) { + kElements[0] = a[i]; + MinHeap.buildMinHeap(kElements); + } + } + + return kElements; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getKLargestElements(new int[]{2, 3, 4, 1, 5, 7, 9}, 3))); + } +} From 3eb0df778c648551c90f09f012bcef780316f517 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 3 Aug 2015 22:09:12 +0530 Subject: [PATCH 228/417] heapsort, max heap, min heap : done --- src/me/ramswaroop/arrays/HeapSort.java | 37 ++++++++++++++++++++++++++ src/me/ramswaroop/common/MaxHeap.java | 29 ++++++++++++++++++++ src/me/ramswaroop/common/MinHeap.java | 28 +++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 src/me/ramswaroop/arrays/HeapSort.java diff --git a/src/me/ramswaroop/arrays/HeapSort.java b/src/me/ramswaroop/arrays/HeapSort.java new file mode 100644 index 00000000..39f88650 --- /dev/null +++ b/src/me/ramswaroop/arrays/HeapSort.java @@ -0,0 +1,37 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.common.MaxHeap; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/3/15 + * @time: 3:13 PM + */ +public class HeapSort { + + /** + * Heapsort. + * + * Time complexity: O(n log n) + * @param a + */ + public static void heapSort(int[] a) { + MaxHeap.buildMaxHeap(a); + + for (int i = a.length - 1; i > 0; i--) { + MaxHeap.swap(a, 0, i); + MaxHeap.maxHeapify(a, 0, i); + } + } + + public static void main(String a[]) { + int[] ar = new int[]{2, 5, 1, 7, 9, 4}; + System.out.println(Arrays.toString(ar)); + heapSort(ar); + System.out.println(Arrays.toString(ar)); + } +} diff --git a/src/me/ramswaroop/common/MaxHeap.java b/src/me/ramswaroop/common/MaxHeap.java index 19d45d63..0bb517f5 100644 --- a/src/me/ramswaroop/common/MaxHeap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -21,6 +21,7 @@ * @author: ramswaroop * @date: 8/2/15 * @time: 11:57 AM + * @see: http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap07.htm */ public class MaxHeap { @@ -51,6 +52,34 @@ public static void maxHeapify(int[] a, int index) { } } + /** + * Makes the array {@param a} satisfy the max heap property starting from + * {@param index} till {@param l} position in array. + *

+ * Time complexity: O(log n). + * + * @param a + * @param index + * @param l + */ + public static void maxHeapify(int[] a, int index, int l) { + int largest = index; + int leftIndex = 2 * index + 1; + int rightIndex = 2 * index + 2; + + if (leftIndex < l && a[index] < a[leftIndex]) { + largest = leftIndex; + } + if (rightIndex < l && a[largest] < a[rightIndex]) { + largest = rightIndex; + } + + if (largest != index) { + swap(a, index, largest); + maxHeapify(a, largest, l); + } + } + /** * Converts array {@param a} in to a max heap. *

diff --git a/src/me/ramswaroop/common/MinHeap.java b/src/me/ramswaroop/common/MinHeap.java index 19d51118..031df266 100644 --- a/src/me/ramswaroop/common/MinHeap.java +++ b/src/me/ramswaroop/common/MinHeap.java @@ -21,6 +21,7 @@ * @author: ramswaroop * @date: 8/2/15 * @time: 11:57 AM + * @see: http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap07.htm */ public class MinHeap { @@ -51,6 +52,33 @@ public static void minHeapify(int[] a, int index) { } } + /** + * Makes the array {@param a} satisfy the min heap property starting from + * {@param index} till {@param l} position in array. + *

+ * Time complexity: O(log n). + * + * @param a + * @param index + */ + public static void minHeapify(int[] a, int index, int l) { + int smallest = index; + int leftIndex = 2 * index + 1; + int rightIndex = 2 * index + 2; + + if (leftIndex < a.length && a[index] > a[leftIndex]) { + smallest = leftIndex; + } + if (rightIndex < a.length && a[smallest] > a[rightIndex]) { + smallest = rightIndex; + } + + if (smallest != index) { + swap(a, index, smallest); + minHeapify(a, smallest, l); + } + } + /** * Converts array {@param a} in to a min heap. *

From 4b430b45be0dd310fa021bc05073f74129d074bb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 3 Aug 2015 22:12:21 +0530 Subject: [PATCH 229/417] minor fixes --- src/me/ramswaroop/arrays/HeapSort.java | 3 ++- src/me/ramswaroop/common/MaxHeap.java | 16 +--------------- src/me/ramswaroop/common/MinHeap.java | 20 +++----------------- 3 files changed, 6 insertions(+), 33 deletions(-) diff --git a/src/me/ramswaroop/arrays/HeapSort.java b/src/me/ramswaroop/arrays/HeapSort.java index 39f88650..d41b8e9d 100644 --- a/src/me/ramswaroop/arrays/HeapSort.java +++ b/src/me/ramswaroop/arrays/HeapSort.java @@ -15,8 +15,9 @@ public class HeapSort { /** * Heapsort. - * + *

* Time complexity: O(n log n) + * * @param a */ public static void heapSort(int[] a) { diff --git a/src/me/ramswaroop/common/MaxHeap.java b/src/me/ramswaroop/common/MaxHeap.java index 0bb517f5..0153c5fa 100644 --- a/src/me/ramswaroop/common/MaxHeap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -35,21 +35,7 @@ public class MaxHeap { * @param index */ public static void maxHeapify(int[] a, int index) { - int largest = index; - int leftIndex = 2 * index + 1; - int rightIndex = 2 * index + 2; - - if (leftIndex < a.length && a[index] < a[leftIndex]) { - largest = leftIndex; - } - if (rightIndex < a.length && a[largest] < a[rightIndex]) { - largest = rightIndex; - } - - if (largest != index) { - swap(a, index, largest); - maxHeapify(a, largest); - } + maxHeapify(a, index, a.length); } /** diff --git a/src/me/ramswaroop/common/MinHeap.java b/src/me/ramswaroop/common/MinHeap.java index 031df266..9ef4f8a1 100644 --- a/src/me/ramswaroop/common/MinHeap.java +++ b/src/me/ramswaroop/common/MinHeap.java @@ -35,21 +35,7 @@ public class MinHeap { * @param index */ public static void minHeapify(int[] a, int index) { - int smallest = index; - int leftIndex = 2 * index + 1; - int rightIndex = 2 * index + 2; - - if (leftIndex < a.length && a[index] > a[leftIndex]) { - smallest = leftIndex; - } - if (rightIndex < a.length && a[smallest] > a[rightIndex]) { - smallest = rightIndex; - } - - if (smallest != index) { - swap(a, index, smallest); - minHeapify(a, smallest); - } + minHeapify(a, index, a.length); } /** @@ -66,10 +52,10 @@ public static void minHeapify(int[] a, int index, int l) { int leftIndex = 2 * index + 1; int rightIndex = 2 * index + 2; - if (leftIndex < a.length && a[index] > a[leftIndex]) { + if (leftIndex < l && a[index] > a[leftIndex]) { smallest = leftIndex; } - if (rightIndex < a.length && a[smallest] > a[rightIndex]) { + if (rightIndex < l && a[smallest] > a[rightIndex]) { smallest = rightIndex; } From 4acda5b54a60f614cf1902fd71d994fbb1a082a1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 4 Aug 2015 23:59:50 +0530 Subject: [PATCH 230/417] maximum size square sub matrix : initial commit --- .../arrays/MaximumSizeSquareSubMatrix.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java diff --git a/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java b/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java new file mode 100644 index 00000000..d1a5c956 --- /dev/null +++ b/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java @@ -0,0 +1,29 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/4/15 + * @time: 11:48 PM + */ +public class MaximumSizeSquareSubMatrix { + + public static int[][] getMaximumSizeSquareSubMatrix(int[][] a) { + int size = a[0].length; // no. of rows/columns + int k; + int[][] subMatrix; + for (int i = 0; i < size - 1; i++) { + for (int j = 0; j < size - 1; j++) { + if (a[i][j] == a[j][i] && a[i][j] == 1) { + } + } + } + + return subMatrix; + } + + public static void main(String a[]) { + + } +} From 4d1c6d50de9b60cae4abbdd4604c3dfa7d62ab87 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 11 Aug 2015 23:33:33 +0530 Subject: [PATCH 231/417] max size sub matrix with all 1s : done --- .../arrays/MaximumSizeSquareSubMatrix.java | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java b/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java index d1a5c956..1d35ac81 100644 --- a/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java +++ b/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java @@ -9,21 +9,54 @@ */ public class MaximumSizeSquareSubMatrix { - public static int[][] getMaximumSizeSquareSubMatrix(int[][] a) { + public static void printMaximumSizeSquareSubMatrix(int[][] a) { int size = a[0].length; // no. of rows/columns - int k; - int[][] subMatrix; - for (int i = 0; i < size - 1; i++) { - for (int j = 0; j < size - 1; j++) { - if (a[i][j] == a[j][i] && a[i][j] == 1) { + int maxI = 0, maxJ = 0, maxSubMatrixSize = 0; + int[][] auxMatrix = new int[size][size]; + + for (int i = 0, j = 0; j < size; j++) { + auxMatrix[i][j] = a[i][j]; + } + + for (int i = 0, j = 0; i < size; i++) { + auxMatrix[i][j] = a[i][j]; + } + + for (int i = 1; i < size; i++) { + for (int j = 1; j < size; j++) { + if (a[i][j] == 1) { + auxMatrix[i][j] = Math.min(Math.min(auxMatrix[i - 1][j], auxMatrix[i][j - 1]), auxMatrix[i - 1][j - 1]) + 1; + } else { + auxMatrix[i][j] = 0; + } + + if (auxMatrix[i][j] > maxSubMatrixSize) { + maxSubMatrixSize = auxMatrix[i][j]; + maxI = i; + maxJ = j; } } } - return subMatrix; + for (int i = maxI; i > maxI - maxSubMatrixSize; i--) { + for (int j = maxJ; j > maxJ - maxSubMatrixSize; j--) { + System.out.print(a[i][j]); + } + System.out.println(); + } } public static void main(String a[]) { - + int[][] ar = new int[][]{{0, 1, 1, 1}, + {1, 1, 0, 1}, + {1, 0, 0, 1}, + {1, 0, 0, 1}}; + printMaximumSizeSquareSubMatrix(ar); + int[][] ar1 = new int[][]{{0, 1, 1, 1, 0}, + {1, 1, 0, 1, 1}, + {1, 1, 1, 0, 1}, + {1, 1, 1, 1, 1}, + {1, 1, 1, 0, 0}}; + printMaximumSizeSquareSubMatrix(ar1); } } From ed52e7dea10db38c10a15477abda653147214f28 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 12 Aug 2015 11:02:19 +0530 Subject: [PATCH 232/417] max size sub matrix with all 1s : comments added --- .../arrays/MaximumSizeSquareSubMatrix.java | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java b/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java index 1d35ac81..251a6fc9 100644 --- a/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java +++ b/src/me/ramswaroop/arrays/MaximumSizeSquareSubMatrix.java @@ -9,16 +9,33 @@ */ public class MaximumSizeSquareSubMatrix { + /** + * Prints the maximum size square sub-matrix in {@param a} with all 1s. + *

+ * Algorithm: + * 1) Construct a sum matrix/auxiliary matrix aux[R][C] for the given a[R][C]. + * ...a) Copy first row and first columns as it is from a[][] to aux[][] + * ...b) For other entries, use following expressions to construct aux[][] + * ........If a[i][j] is 1 then + * ........aux[i][j] = min(aux[i][j-1], aux[i-1][j], aux[i-1][j-1]) + 1 + * ........Else + * ........aux[i][j] = 0 + * 2) Find the maximum entry in aux[R][C] + * 3) Using the value and coordinates of maximum entry in aux[i], print sub-matrix of a[][] + * + * @param a + */ public static void printMaximumSizeSquareSubMatrix(int[][] a) { int size = a[0].length; // no. of rows/columns int maxI = 0, maxJ = 0, maxSubMatrixSize = 0; int[][] auxMatrix = new int[size][size]; - for (int i = 0, j = 0; j < size; j++) { + // construct auxiliary matrix + for (int i = 0, j = 0; j < size; j++) { // copy 1st row auxMatrix[i][j] = a[i][j]; } - for (int i = 0, j = 0; i < size; i++) { + for (int i = 0, j = 0; i < size; i++) { // copy 1st column auxMatrix[i][j] = a[i][j]; } @@ -38,6 +55,7 @@ public static void printMaximumSizeSquareSubMatrix(int[][] a) { } } + // print max size sub-matrix in array 'a' from the co-ordinates in auxiliary matrix for (int i = maxI; i > maxI - maxSubMatrixSize; i--) { for (int j = maxJ; j > maxJ - maxSubMatrixSize; j--) { System.out.print(a[i][j]); From 5e4fe361d85cd60f999236f4002ff36e8fa77b54 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 12 Aug 2015 11:02:48 +0530 Subject: [PATCH 233/417] abs without branching : comments added --- src/me/ramswaroop/bits/AbsWithoutBranching.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/bits/AbsWithoutBranching.java b/src/me/ramswaroop/bits/AbsWithoutBranching.java index ec55ab9b..cbe0c9b9 100644 --- a/src/me/ramswaroop/bits/AbsWithoutBranching.java +++ b/src/me/ramswaroop/bits/AbsWithoutBranching.java @@ -11,6 +11,14 @@ public class AbsWithoutBranching { /** * Returns the absolute value of any integer. + *

+ * EXPLANATION: + * For example, consider int takes 4 bits: + * So for input = -5, we have + * -5 = 1011 + * mask = 1111 + * mask + n = 1010 + * (mask + n)^mask = 0101 (which is 5) * * @param n * @return @@ -27,12 +35,3 @@ public static void main(String a[]) { System.out.println(abs(-0)); } } - -/** - * For example, consider int takes 4 bits: - * So for input = -5, we have - * -5 = 1011 - * mask = 1111 - * mask + n = 1010 - * (mask + n)^mask = 0101 (which is 5) - */ From e4669d477d4536b894899e0e90ae280f0d1e2445 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 13 Aug 2015 09:53:23 +0530 Subject: [PATCH 234/417] max diff with larger element after the smaller element : done --- ...fWithLargerElementAfterSmallerElement.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MaxDiffWithLargerElementAfterSmallerElement.java diff --git a/src/me/ramswaroop/arrays/MaxDiffWithLargerElementAfterSmallerElement.java b/src/me/ramswaroop/arrays/MaxDiffWithLargerElementAfterSmallerElement.java new file mode 100644 index 00000000..b5aa0d01 --- /dev/null +++ b/src/me/ramswaroop/arrays/MaxDiffWithLargerElementAfterSmallerElement.java @@ -0,0 +1,43 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/12/15 + * @time: 5:40 PM + */ +public class MaxDiffWithLargerElementAfterSmallerElement { + + /** + * Finds the difference between any two elements such that larger + * element appears after the smaller number in array {@param a}. + *

+ * Example: + * If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). + * If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9). + * + * @param a + * @return + */ + public static int getMaxDiffWithLargerElementAfterSmallerElement(int[] a) { + int minElement = a[0], maxDiff = a[1] - a[0]; + + for (int i = 1; i < a.length; i++) { + if (a[i] < minElement) { + minElement = a[i]; + } + if (a[i] - minElement > maxDiff) { + maxDiff = a[i] - minElement; + } + } + + return maxDiff; + } + + public static void main(String a[]) { + System.out.println(getMaxDiffWithLargerElementAfterSmallerElement(new int[]{2, 1, 4, 5, 10, 0})); + System.out.println(getMaxDiffWithLargerElementAfterSmallerElement(new int[]{2, -6, 4, 5, 10, 1})); + System.out.println(getMaxDiffWithLargerElementAfterSmallerElement(new int[]{-2, -6, -4, -5, -10, -1})); + } +} From 08b6fefaf1f4c0dbd63fea25bf976793c8eb21a2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 13 Aug 2015 15:37:10 +0530 Subject: [PATCH 235/417] random no generator from another random no generator : done --- .../EqualProbabilityRandomNoGenerator.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/me/ramswaroop/arrays/EqualProbabilityRandomNoGenerator.java diff --git a/src/me/ramswaroop/arrays/EqualProbabilityRandomNoGenerator.java b/src/me/ramswaroop/arrays/EqualProbabilityRandomNoGenerator.java new file mode 100644 index 00000000..d28d26b2 --- /dev/null +++ b/src/me/ramswaroop/arrays/EqualProbabilityRandomNoGenerator.java @@ -0,0 +1,53 @@ +package me.ramswaroop.arrays; + +import java.util.Random; +import java.util.Scanner; + +/** + * Given a random number generator f(n) which generates a random number + * from {@code 0} (inclusive) to {@code n} (exclusive), design a method + * which uses f(n) to generate non repeating random numbers from + * {@code 0} (inclusive) to {@code n} (exclusive)? + * + * @author: ramswaroop + * @date: 8/13/15 + * @time: 1:41 PM + */ +public class EqualProbabilityRandomNoGenerator { + + static int[] bucket; + static int size; + + /** + * The algorithm is to create a bucket of numbers and then to keep on + * removing the elements from the bucket which are returned. + * + * @return + */ + public static int getRandom() { + int random = f(size--); + int result = bucket[random]; + bucket[random] = bucket[size]; + return result; + } + + public static int f(int n) { + return new Random().nextInt(n); + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + System.out.println("How many random numbers you would like to generate?"); + size = in.nextInt(); + + bucket = new int[size]; + + for (int i = 0; i < bucket.length; i++) { + bucket[i] = i; + } + for (int i = 0; i < bucket.length; i++) { + System.out.println(getRandom()); + } + } +} From 500748289ce7ef5e7d13d15fe0bc8bf67e7baa01 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 13 Aug 2015 15:56:24 +0530 Subject: [PATCH 236/417] comments added --- .../ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java b/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java index c7ca3502..b5e10a84 100644 --- a/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java +++ b/src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java @@ -17,7 +17,8 @@ public class IntersectionAndUnionOf2Lists { * @param list1 * @param list2 * @param - * @return an array of list consisting of intersection and union of {@param list1} and {@param list2} respectively. + * @return an array of list consisting of intersection and union of two sorted + * list {@param list1} and {@param list2} respectively. */ public static > SingleLinkedList[] getIntersectionAndUnion(SingleLinkedList list1, SingleLinkedList list2) { From cf2ee73f8d46f317574ce80ebb84d18fc7199e72 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 14 Aug 2015 15:22:48 +0530 Subject: [PATCH 237/417] intersection and union of 2 sorted arrays : done --- .../IntersectionAndUnionOf2SortedArrays.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java diff --git a/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java b/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java new file mode 100644 index 00000000..40ead097 --- /dev/null +++ b/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java @@ -0,0 +1,62 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/13/15 + * @time: 3:56 PM + */ +public class IntersectionAndUnionOf2SortedArrays { + + /** + * Returns a 2-D array consisting of intersection and union of + * arrays {@param a} and {@param b} respectively. + * + * @param a + * @param b + * @return + */ + public static int[][] getIntersectionAndUnionOf2SortedArrays(int[] a, int[] b) { + int length = a.length + b.length, x = 0, y = 0; + int[] intersection = new int[length], union = new int[length]; + + for (int i = 0, j = 0; i < a.length || j < b.length; ) { + + // if either of the arrays runs out first + if (i == a.length) { + union[y++] = b[j++]; + continue; + } + if (j == b.length) { + union[y++] = a[i++]; + continue; + } + + if (a[i] < b[j]) { + union[y++] = a[i++]; + } else if (a[i] > b[j]) { + union[y++] = b[j++]; + } else { + intersection[x++] = a[i]; + union[y++] = a[i]; + i++; + j++; + } + } + + return new int[][]{intersection, union}; + } + + public static void main(String a[]) { + int[] a1 = new int[]{2, 3, 4, 5, 6, 7, 8}; + int[] a2 = new int[]{6, 7, 8, 10, 12, 14, 16}; + int[][] result = getIntersectionAndUnionOf2SortedArrays(a1, a2); + // intersection + System.out.println(Arrays.toString(result[0])); + // union + System.out.println(Arrays.toString(result[1])); + } +} From 2a02f7665c1e2b83a47c04d985d67f25d0a5bc30 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 14 Aug 2015 15:23:33 +0530 Subject: [PATCH 238/417] intersection and union of 2 sorted arrays : comments added --- .../ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java b/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java index 40ead097..7b6fae64 100644 --- a/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java +++ b/src/me/ramswaroop/arrays/IntersectionAndUnionOf2SortedArrays.java @@ -13,7 +13,7 @@ public class IntersectionAndUnionOf2SortedArrays { /** * Returns a 2-D array consisting of intersection and union of - * arrays {@param a} and {@param b} respectively. + * two sorted arrays {@param a} and {@param b} respectively. * * @param a * @param b From 0e76b0d97798bfb650c5c89ddac21c74211680cb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 15 Aug 2015 22:00:26 +0530 Subject: [PATCH 239/417] product array puzzle : done --- .../ramswaroop/arrays/ProductArrayPuzzle.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/me/ramswaroop/arrays/ProductArrayPuzzle.java diff --git a/src/me/ramswaroop/arrays/ProductArrayPuzzle.java b/src/me/ramswaroop/arrays/ProductArrayPuzzle.java new file mode 100644 index 00000000..6abe5a3e --- /dev/null +++ b/src/me/ramswaroop/arrays/ProductArrayPuzzle.java @@ -0,0 +1,71 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/15/15 + * @time: 9:17 PM + */ +public class ProductArrayPuzzle { + + /** + * Construct a Product Array prod[] (of same size) such that prod[i] is + * equal to the product of all the elements of arr[] except arr[i]. Solve + * it without division operator and in O(n). + *

+ * You can do this by taking two arrays one containing the products from + * left to right elements and other containing the products from right to + * left elements and then finally multiplying those two arrays gives you + * the answer. But the auxiliary space complexity of this method is O(n) + * as well as the space complexity is O(n). + *

+ * The below method is the optimized way to do this in O(1) auxiliary space + * but the space complexity is O(n). + *

+ * AUXILIARY SPACE is extra space or temporary space used by the algorithm, + * which is mostly used in algorithm where we use swapping or temporary variables. + *

+ * SPACE COMPLEXITY means total space taken by the algorithm with respect to + * input size.Space complexity calculated by both auxiliary space and space used + * by the input. + *

+ * For example - If we want to compare standard sorting algorithm on the basis of + * then auxiliary space would be better criteria than space complexity. Merge sort + * uses O(n) auxiliary space,where Insertion sort and Heap sort uses O(1) auxiliary + * space. Merge sort requires Ω(n) but Heap sort requires only a constant amount. + * Space complexity of all these sorting algorithm is O(n) though. + * + * @param a + * @return + */ + public static int[] getProductArray(int[] a) { + int[] prod = new int[a.length]; + + // prod array consists of products of the elements + prod[0] = 1; + + // fill prod with products of elements from left to right excluding current element + for (int i = 1; i < a.length; i++) { + prod[i] = a[i - 1] * prod[i - 1]; + } + + int temp = 1; + // fill prod with products of elements from right to left excluding current element + for (int i = a.length - 1; i >= 0; i--) { + prod[i] *= temp; + temp *= a[i]; + } + + // final prod array is the answer + return prod; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getProductArray(new int[]{10, 3, 5, 6, 2}))); + System.out.println(Arrays.toString(getProductArray(new int[]{0, 0}))); + System.out.println(Arrays.toString(getProductArray(new int[]{1}))); + } +} From f5d5800ab957f6597dd3d75153dfdfefa6407e89 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 16 Aug 2015 23:38:14 +0530 Subject: [PATCH 240/417] segregate even and odd nos : done --- .../arrays/SegregateEvenAndOddNos.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SegregateEvenAndOddNos.java diff --git a/src/me/ramswaroop/arrays/SegregateEvenAndOddNos.java b/src/me/ramswaroop/arrays/SegregateEvenAndOddNos.java new file mode 100644 index 00000000..aa79fd4a --- /dev/null +++ b/src/me/ramswaroop/arrays/SegregateEvenAndOddNos.java @@ -0,0 +1,50 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/31/15 + * @time: 5:13 PM + */ +public class SegregateEvenAndOddNos { + + /** + * Segregate even and odd numbers by traversing the + * array {@param a} only once. + *

+ * This is similar to {@link me.ramswaroop.arrays.Segregate0sAnd1s}. + * + * @param a + */ + public static void segregateEvenAndOddNos(int[] a) { + for (int i = 0, j = a.length - 1; i < j; ) { + if (a[i] % 2 != 0 && a[j] % 2 == 0) { + // swap + a[i] = a[i] + a[j]; + a[j] = a[i] - a[j]; + a[i] = a[i] - a[j]; + i++; + j--; + } else if (a[i] % 2 == 0 && a[j] % 2 == 0) { + i++; + } else if (a[i] % 2 != 0 && a[j] % 2 != 0) { + j--; + } else { + i++; + j--; + } + } + } + + public static void main(String a[]) { + int[] ar = new int[]{12, 34, 45, 9, 8, 90, 3}; + segregateEvenAndOddNos(ar); + System.out.println(Arrays.toString(ar)); + int[] ar1 = new int[]{34, 1, 45, 9, 8, 67, 3, 56, 78, 79, 101, 100}; + segregateEvenAndOddNos(ar1); + System.out.println(Arrays.toString(ar1)); + } +} From 235bb4aed7d13e444176dd412392f5d862c25296 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 17 Aug 2015 23:48:14 +0530 Subject: [PATCH 241/417] two repeating elements : initial commit --- .../arrays/TwoRepeatingElements.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/me/ramswaroop/arrays/TwoRepeatingElements.java diff --git a/src/me/ramswaroop/arrays/TwoRepeatingElements.java b/src/me/ramswaroop/arrays/TwoRepeatingElements.java new file mode 100644 index 00000000..5e7e1f62 --- /dev/null +++ b/src/me/ramswaroop/arrays/TwoRepeatingElements.java @@ -0,0 +1,19 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/17/15 + * @time: 7:23 PM + */ +public class TwoRepeatingElements { + + public static int[] getTwoRepeatingElements(int[] a) { + + } + + public static void main(String a[]) { + + } +} From 84cc7a430cc2bfcdffb284ee1600c7b0e1146d57 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 17 Aug 2015 23:57:07 +0530 Subject: [PATCH 242/417] two repeating elements : 90% done --- .../arrays/TwoRepeatingElements.java | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/TwoRepeatingElements.java b/src/me/ramswaroop/arrays/TwoRepeatingElements.java index 5e7e1f62..90ffb28d 100644 --- a/src/me/ramswaroop/arrays/TwoRepeatingElements.java +++ b/src/me/ramswaroop/arrays/TwoRepeatingElements.java @@ -1,5 +1,7 @@ package me.ramswaroop.arrays; +import java.util.Arrays; + /** * Created by IntelliJ IDEA. * @@ -10,10 +12,37 @@ public class TwoRepeatingElements { public static int[] getTwoRepeatingElements(int[] a) { - + int xor = a[0]; + int rightMostSetBit; + int x = 0, y = 0; + for (int i = 1; i < a.length; i++) { + xor ^= a[i]; + } + for (int i = 1; i <= a.length - 2; i++) { + xor ^= i; + } + rightMostSetBit = xor & ~(xor - 1); + + for (int i = 0; i < a.length; i++) { + if ((a[i] & rightMostSetBit) == 1) { + x ^= a[i]; + } else { + y ^= a[i]; + } + } + + for (int i = 1; i <= a.length - 2; i++) { + if ((i & rightMostSetBit) == 1) { + x ^= i; + } else { + y ^= i; + } + } + + return new int[]{x, y}; } public static void main(String a[]) { - + System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{4, 2, 4, 5, 2, 3, 1}))); } } From 02807a977806ca5d59f170a56f515a41d0b3762c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 18 Aug 2015 00:03:23 +0530 Subject: [PATCH 243/417] two repeating elements : done --- src/me/ramswaroop/arrays/TwoRepeatingElements.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/TwoRepeatingElements.java b/src/me/ramswaroop/arrays/TwoRepeatingElements.java index 90ffb28d..e3a60e75 100644 --- a/src/me/ramswaroop/arrays/TwoRepeatingElements.java +++ b/src/me/ramswaroop/arrays/TwoRepeatingElements.java @@ -15,6 +15,7 @@ public static int[] getTwoRepeatingElements(int[] a) { int xor = a[0]; int rightMostSetBit; int x = 0, y = 0; + for (int i = 1; i < a.length; i++) { xor ^= a[i]; } @@ -24,7 +25,7 @@ public static int[] getTwoRepeatingElements(int[] a) { rightMostSetBit = xor & ~(xor - 1); for (int i = 0; i < a.length; i++) { - if ((a[i] & rightMostSetBit) == 1) { + if ((a[i] & rightMostSetBit) == 0) { x ^= a[i]; } else { y ^= a[i]; @@ -32,7 +33,7 @@ public static int[] getTwoRepeatingElements(int[] a) { } for (int i = 1; i <= a.length - 2; i++) { - if ((i & rightMostSetBit) == 1) { + if ((i & rightMostSetBit) == 0) { x ^= i; } else { y ^= i; From bb3d1d3cce5b24a972fc1db77f509ba2c826148d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 18 Aug 2015 12:57:26 +0530 Subject: [PATCH 244/417] two repeating elements : comments added --- .../arrays/TwoRepeatingElements.java | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/TwoRepeatingElements.java b/src/me/ramswaroop/arrays/TwoRepeatingElements.java index e3a60e75..7cd16888 100644 --- a/src/me/ramswaroop/arrays/TwoRepeatingElements.java +++ b/src/me/ramswaroop/arrays/TwoRepeatingElements.java @@ -11,20 +11,38 @@ */ public class TwoRepeatingElements { + /** + * Finds the 2 repeating elements in an array {@param a} of 1 to n elements and n+2 length. This is + * similar to {@link me.ramswaroop.bits.TwoNonRepeatingElements}. + *

+ * EXPLANATION: + * Let the repeating numbers be X and Y, if we xor all the elements in the array and all integers from 1 to n, + * then the result is X xor Y. + * The 1’s in binary representation of X xor Y is corresponding to the different bits between X and Y. + * Suppose that the kth bit of X xor Y is 1, we can xor all the elements in the array and all integers + * from 1 to n, whose kth bits are 1. The result will be one of X and Y. + * + * @param a + * @return + */ public static int[] getTwoRepeatingElements(int[] a) { int xor = a[0]; int rightMostSetBit; int x = 0, y = 0; - + for (int i = 1; i < a.length; i++) { xor ^= a[i]; } + for (int i = 1; i <= a.length - 2; i++) { xor ^= i; } + + // now xor is X xor Y, therefore find any of its set bit rightMostSetBit = xor & ~(xor - 1); for (int i = 0; i < a.length; i++) { + // one number will have a set bit at that position and other wouldn't if ((a[i] & rightMostSetBit) == 0) { x ^= a[i]; } else { @@ -33,6 +51,7 @@ public static int[] getTwoRepeatingElements(int[] a) { } for (int i = 1; i <= a.length - 2; i++) { + // one number will have a set bit at that position and other wouldn't if ((i & rightMostSetBit) == 0) { x ^= i; } else { @@ -45,5 +64,7 @@ public static int[] getTwoRepeatingElements(int[] a) { public static void main(String a[]) { System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{4, 2, 4, 5, 2, 3, 1}))); + System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{2, 4, 5, 2, 3, 1, 6, 7, 7}))); + System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{1, 2, 1, 2}))); } } From 518e2af10f2f4dffeae7b89a8101e975c400d79b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 18 Aug 2015 21:06:24 +0530 Subject: [PATCH 245/417] segregate 0s 1 2s : done --- .../ramswaroop/arrays/Segregate0s1sAnd2s.java | 65 +++++++++++++++++++ src/me/ramswaroop/utils/Utils.java | 12 ---- 2 files changed, 65 insertions(+), 12 deletions(-) create mode 100644 src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java delete mode 100644 src/me/ramswaroop/utils/Utils.java diff --git a/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java b/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java new file mode 100644 index 00000000..266b6350 --- /dev/null +++ b/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java @@ -0,0 +1,65 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/18/15 + * @time: 8:38 PM + */ +public class Segregate0s1sAnd2s { + + /** + * Segregates an array {@param a} consisting of only 0s, 1s and 2s. Based on + * Dutch National Flag (DNF) problem {@see: http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/}. + * + * @param a + */ + public static void segregate0s1sAnd2s(int[] a) { + // assume low points to 0 and mid to 1 and high to 2 + int low = 0, mid = 0, high = a.length - 1; + + while (mid <= high) { + switch (a[mid]) { + case 0: // mid points to 0 but it should point to 1 so swap it with low + swap(a, low, mid); + low++; + mid++; + break; + case 1: // mid points to 1 which is correct acc. to our assumption so proceed + mid++; + break; + case 2: // mid points to 2 instead of 1 so swap it with high + swap(a, mid, high); + high--; + break; + } + } + } + + private static void swap(int[] a, int index1, int index2) { + int temp = a[index1]; + a[index1] = a[index2]; + a[index2] = temp; + } + + public static void main(String a[]) { + int[] ar = new int[]{0, 1, 2, 0, 1, 2}; + segregate0s1sAnd2s(ar); + System.out.println(Arrays.toString(ar)); + + int[] ar1 = new int[]{0, 2, 1, 1, 2, 0}; + segregate0s1sAnd2s(ar1); + System.out.println(Arrays.toString(ar1)); + + int[] ar2 = new int[]{0, 1, 2}; + segregate0s1sAnd2s(ar2); + System.out.println(Arrays.toString(ar2)); + + int[] ar3 = new int[]{2, 1, 0, 2, 1, 0}; + segregate0s1sAnd2s(ar3); + System.out.println(Arrays.toString(ar3)); + } +} diff --git a/src/me/ramswaroop/utils/Utils.java b/src/me/ramswaroop/utils/Utils.java deleted file mode 100644 index 448c4205..00000000 --- a/src/me/ramswaroop/utils/Utils.java +++ /dev/null @@ -1,12 +0,0 @@ -package me.ramswaroop.utils; - -/** - * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 4/19/15 - * Time: 11:57 AM - * To change this template go to Preferences | IDE Settings | File and Code Templates - */ -public class Utils { - -} From dc1afa51141ec23990fc4484ff5f6e39f2e29bc6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 18 Aug 2015 23:14:36 +0530 Subject: [PATCH 246/417] largest sum contiguous sub array : done --- .../arrays/LargestSumContiguousSubArray.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java index 770d61d6..290b6c64 100644 --- a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java +++ b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java @@ -9,11 +9,30 @@ */ public class LargestSumContiguousSubArray { - public void largestSumContiguousSubArray(int a[]) { + /** + * Based on Kadane's Algorithm. + * + * @param a + * @return + */ + public static int getLargestSumOfContiguousSubArray(int a[]) { + int maxSum = 0, maxSumTillIndex = 0; + for (int i = 0; i < a.length; i++) { + maxSumTillIndex += a[i]; + if (maxSumTillIndex < 0) { + maxSumTillIndex = 0; + } + if (maxSumTillIndex > maxSum) { + maxSum = maxSumTillIndex; + } + } + return maxSum; } public static void main(String a[]) { - + System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4})); + System.out.println(getLargestSumOfContiguousSubArray(new int[]{2, -1, -3, 4, -5, 1, 4})); + System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, -1, -3, -4, -5, -1, -4})); // doesn't work } } From 2b27f3a1ebe220b359a939ab2e2f927babd36b79 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 19 Aug 2015 23:44:53 +0530 Subject: [PATCH 247/417] largest sum contiguous sub array : comments added --- .../arrays/LargestSumContiguousSubArray.java | 37 ++++++++++++++++--- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java index 290b6c64..51eebdf5 100644 --- a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java +++ b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java @@ -10,29 +10,54 @@ public class LargestSumContiguousSubArray { /** - * Based on Kadane's Algorithm. - * + * Based on Kadane's Algorithm. Doesn't work when all + * elements in array {@param a} are negative. + * * @param a * @return */ - public static int getLargestSumOfContiguousSubArray(int a[]) { + public static int getLargestSumOfContiguousSubArray(int[] a) { int maxSum = 0, maxSumTillIndex = 0; for (int i = 0; i < a.length; i++) { maxSumTillIndex += a[i]; if (maxSumTillIndex < 0) { maxSumTillIndex = 0; - } - if (maxSumTillIndex > maxSum) { + } else if (maxSumTillIndex > maxSum) { maxSum = maxSumTillIndex; } } return maxSum; } + /** + * TODO + * @param a + * @return + */ + public static int getLargestSumOfContiguousSubArrayWhenAllNosNegative(int[] a) { + int maxSum = a[0], maxSumTillIndex = a[0]; + + for (int i = 1; i < a.length; i++) { + if (a[i] > maxSumTillIndex) { + maxSumTillIndex = a[i]; + } else if (maxSumTillIndex + a[i] < maxSumTillIndex) { + maxSumTillIndex = a[i]; + } + maxSum = Math.max(maxSum, maxSumTillIndex); + } + + return maxSum; + } + public static void main(String a[]) { System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4})); System.out.println(getLargestSumOfContiguousSubArray(new int[]{2, -1, -3, 4, -5, 1, 4})); - System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, -1, -3, -4, -5, -1, -4})); // doesn't work + // kadane's algorithm doesn't work if all no.s are -ve + System.out.println(getLargestSumOfContiguousSubArray(new int[]{-2, -1, -3, -4, -5, -1, -4})); + + System.out.println(getLargestSumOfContiguousSubArrayWhenAllNosNegative(new int[]{-2, 1, -3, 4, 5, -1, 4})); + System.out.println(getLargestSumOfContiguousSubArrayWhenAllNosNegative(new int[]{2, -1, -3, 4, -5, 1, 4})); + System.out.println(getLargestSumOfContiguousSubArrayWhenAllNosNegative(new int[]{-2, -1, -3, -4, -5, -1, -4})); } } From aa73f7929f74fce40c5ac72949c398a049b1b859 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 19 Aug 2015 23:47:58 +0530 Subject: [PATCH 248/417] largest sum contiguous sub array : comments added --- src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java index 51eebdf5..f1c03f0a 100644 --- a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java +++ b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java @@ -20,9 +20,9 @@ public static int getLargestSumOfContiguousSubArray(int[] a) { int maxSum = 0, maxSumTillIndex = 0; for (int i = 0; i < a.length; i++) { - maxSumTillIndex += a[i]; + maxSumTillIndex += a[i]; // keep on adding elements if (maxSumTillIndex < 0) { - maxSumTillIndex = 0; + maxSumTillIndex = 0; // once the sum is less than 0 restart adding elements from next index } else if (maxSumTillIndex > maxSum) { maxSum = maxSumTillIndex; } From 2a5c8292e4dcb2af57f26f37a863ff5bde342874 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 20 Aug 2015 00:17:03 +0530 Subject: [PATCH 249/417] largest sum contiguous sub array : added method for all -ve no.s --- .../arrays/LargestSumContiguousSubArray.java | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java index f1c03f0a..14266935 100644 --- a/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java +++ b/src/me/ramswaroop/arrays/LargestSumContiguousSubArray.java @@ -10,7 +10,7 @@ public class LargestSumContiguousSubArray { /** - * Based on Kadane's Algorithm. Doesn't work when all + * Based on Kadane's Algorithm. Doesn't work when all * elements in array {@param a} are negative. * * @param a @@ -31,7 +31,8 @@ public static int getLargestSumOfContiguousSubArray(int[] a) { } /** - * TODO + * Below algorithm works even when all elements in array {@param a} are negative. + * * @param a * @return */ @@ -39,11 +40,7 @@ public static int getLargestSumOfContiguousSubArrayWhenAllNosNegative(int[] a) { int maxSum = a[0], maxSumTillIndex = a[0]; for (int i = 1; i < a.length; i++) { - if (a[i] > maxSumTillIndex) { - maxSumTillIndex = a[i]; - } else if (maxSumTillIndex + a[i] < maxSumTillIndex) { - maxSumTillIndex = a[i]; - } + maxSumTillIndex = Math.max(a[i], maxSumTillIndex + a[i]); maxSum = Math.max(maxSum, maxSumTillIndex); } From 723beec589b136c1946c2144549842ece9deb1fa Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 20 Aug 2015 15:31:14 +0530 Subject: [PATCH 250/417] unsorted sub array : done --- .../ramswaroop/arrays/UnsortedSubArray.java | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/me/ramswaroop/arrays/UnsortedSubArray.java diff --git a/src/me/ramswaroop/arrays/UnsortedSubArray.java b/src/me/ramswaroop/arrays/UnsortedSubArray.java new file mode 100644 index 00000000..ab24d03d --- /dev/null +++ b/src/me/ramswaroop/arrays/UnsortedSubArray.java @@ -0,0 +1,97 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/20/15 + * @time: 10:31 AM + */ +public class UnsortedSubArray { + + /** + * Finds the unsorted sub array in array {@param a} such that + * sorting this sub array makes the entire array sorted. + *

+ * EXPLANATION: + * 1) Find the candidate unsorted subarray + * ...a) Scan from left to right and find the first element which is greater than the next element. Let s be the + * index of such an element. In the above example 1, s is 3 (index of 30). + * ...b) Scan from right to left and find the first element (first in right to left order) which is smaller than + * the next element (next in right to left order). Let e be the index of such an element. In the above example 1, + * e is 7 (index of 31). + * 2) Check whether sorting the candidate unsorted subarray makes the complete array sorted or not. If not, then + * include more elements in the subarray. + * ...a) Find the minimum and maximum values in arr[s..e]. Let minimum and maximum values be min and max. min and + * max for [30, 25, 40, 32, 31] are 25 and 40 respectively. + * ...b) Find the first element (if there is any) in arr[0..s-1] which is greater than min, change s to index of + * this element. There is no such element in above example 1. + * ...c) Find the last element (if there is any) in arr[e+1..n-1] which is smaller than max, change e to index of + * this element. In the above example 1, e is changed to 8 (index of 35) + * 3) Print s and e. + * + * @param a + * @return + */ + public static int[] getUnsortedSubArray(int[] a) { + int start = 0, end = a.length - 1, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; + int[] unsortedArray; + + // 1(a) + for (int i = 0; i < a.length-1; i++) { + if (a[i] > a[i + 1]) { + start = i; + break; + } + } + + // 1(b) + for (int i = a.length - 1; i > 0; i--) { + if (a[i] < a[i - 1]) { + end = i; + break; + } + } + + // 2(a) - find min and max + for (int i = start; i <= end; i++) { + if (a[i] < min) { + min = a[i]; + } + if (a[i] > max) { + max = a[i]; + } + } + + // 2(b) + for (int i = 0; i < start; i++) { + if (a[i] > min) { + start = i; + break; + } + } + + // 2(c) + for (int i = end + 1; i < a.length; i++) { + if (a[i] < max) { + end = i; + break; + } + } + + unsortedArray = new int[end - start + 1]; + for (int i = start, j = 0; i <= end; i++, j++) { + unsortedArray[j] = a[i]; + } + + return unsortedArray; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getUnsortedSubArray(new int[]{10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60}))); + System.out.println(Arrays.toString(getUnsortedSubArray(new int[]{0, 1, 15, 25, 6, 7, 30, 40, 50}))); + System.out.println(Arrays.toString(getUnsortedSubArray(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8}))); // fully sorted already + } +} From 2f0c6aaffe48bcfc0b76cff32812a8c3b5764ceb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 21 Aug 2015 09:59:19 +0530 Subject: [PATCH 251/417] duplicates in array : done --- .../ramswaroop/arrays/DuplicatesInArray.java | 44 +++++++++++++++++++ .../arrays/TwoRepeatingElements.java | 28 ++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 src/me/ramswaroop/arrays/DuplicatesInArray.java diff --git a/src/me/ramswaroop/arrays/DuplicatesInArray.java b/src/me/ramswaroop/arrays/DuplicatesInArray.java new file mode 100644 index 00000000..c77260a8 --- /dev/null +++ b/src/me/ramswaroop/arrays/DuplicatesInArray.java @@ -0,0 +1,44 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/21/15 + * @time: 9:41 AM + */ +public class DuplicatesInArray { + + /** + * The algorithm is simple. We use index of the array to track repeating elements. + * Once we encounter a element lets say 2 then we make the 2nd index -ve just to mark + * that we have encountered 2. When we encounter 2 again and see that 2nd index + * is already -ve we conclude that 2 is repeated. + * + * Similar to {@link me.ramswaroop.arrays.TwoRepeatingElements#findTwoRepeatingElements(int[])}. + * + * @param a + * @return + */ + public static int[] findDuplicatesInArray(int[] a) { + int[] duplicates = new int[a.length]; + + for (int i = 0, j = 0; i < a.length; i++) { + if (a[Math.abs(a[i])] >= 0) { + a[Math.abs(a[i])] = -a[Math.abs(a[i])]; + } else { + duplicates[j++] = Math.abs(a[i]); + } + } + return duplicates; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(findDuplicatesInArray(new int[]{1, 1, 2, 3, 1, 3, 6, 6}))); + // doesn't work if 0 is present in array (as -0 makes no sense but we can modify the algorithm to handle 0) + System.out.println(Arrays.toString(findDuplicatesInArray(new int[]{1, 0, 1, 2, 3, 1, 3, 6, 6}))); + System.out.println(Arrays.toString(findDuplicatesInArray(new int[]{0, 0, 1, 2, 3, 1, 3, 6, 6}))); + } +} diff --git a/src/me/ramswaroop/arrays/TwoRepeatingElements.java b/src/me/ramswaroop/arrays/TwoRepeatingElements.java index 7cd16888..4fe52e1c 100644 --- a/src/me/ramswaroop/arrays/TwoRepeatingElements.java +++ b/src/me/ramswaroop/arrays/TwoRepeatingElements.java @@ -62,9 +62,37 @@ public static int[] getTwoRepeatingElements(int[] a) { return new int[]{x, y}; } + /** + * The algorithm is simple. We use index of the array to track repeating elements. + * Once we encounter a element lets say 2 then we make the 2nd index -ve just to mark + * that we have encountered 2. When we encounter 2 again and see that 2nd index + * is already -ve we conclude that 2 is repeated. + * + * Similar to {@link me.ramswaroop.arrays.DuplicatesInArray#findDuplicatesInArray(int[])}. + * + * @param a + * @return + */ + public static int[] findTwoRepeatingElements(int[] a) { + int[] repeatingElements = new int[2]; + + for (int i = 0, j = 0; i < a.length; i++) { + if (a[Math.abs(a[i])] >= 0) { + a[Math.abs(a[i])] = -a[Math.abs(a[i])]; + } else { + repeatingElements[j++] = Math.abs(a[i]); + } + } + return repeatingElements; + } + public static void main(String a[]) { System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{4, 2, 4, 5, 2, 3, 1}))); System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{2, 4, 5, 2, 3, 1, 6, 7, 7}))); System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{1, 2, 1, 2}))); + System.out.println("========"); + System.out.println(Arrays.toString(findTwoRepeatingElements(new int[]{4, 2, 4, 5, 2, 3, 1}))); + System.out.println(Arrays.toString(findTwoRepeatingElements(new int[]{2, 4, 5, 2, 3, 1, 6, 7, 7}))); + System.out.println(Arrays.toString(findTwoRepeatingElements(new int[]{1, 2, 1, 2}))); } } From b04d9445821034f62d4077211666dc15a309cf64 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 21 Aug 2015 10:09:43 +0530 Subject: [PATCH 252/417] duplicates in array : comments added --- src/me/ramswaroop/arrays/DuplicatesInArray.java | 14 +++++++++++--- src/me/ramswaroop/arrays/TwoRepeatingElements.java | 4 ++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/me/ramswaroop/arrays/DuplicatesInArray.java b/src/me/ramswaroop/arrays/DuplicatesInArray.java index c77260a8..87402572 100644 --- a/src/me/ramswaroop/arrays/DuplicatesInArray.java +++ b/src/me/ramswaroop/arrays/DuplicatesInArray.java @@ -12,11 +12,19 @@ public class DuplicatesInArray { /** + * Given an array of n elements which contains elements from 0 to n-1, with any of + * these numbers appearing any number of times. Find these repeating numbers in O(n) + * and using only constant memory space. + *

+ * For example, let n be 7 and array be {1, 2, 3, 1, 3, 6, 6}, the answer should be + * 1, 3 and 6. + *

+ * EXPLANATION: * The algorithm is simple. We use index of the array to track repeating elements. - * Once we encounter a element lets say 2 then we make the 2nd index -ve just to mark - * that we have encountered 2. When we encounter 2 again and see that 2nd index + * Once we encounter a element lets say 2 then we make the element in 2nd index -ve just + * to mark that we have encountered 2. When we encounter 2 again and see that 2nd index * is already -ve we conclude that 2 is repeated. - * + *

* Similar to {@link me.ramswaroop.arrays.TwoRepeatingElements#findTwoRepeatingElements(int[])}. * * @param a diff --git a/src/me/ramswaroop/arrays/TwoRepeatingElements.java b/src/me/ramswaroop/arrays/TwoRepeatingElements.java index 4fe52e1c..c1c9a4ae 100644 --- a/src/me/ramswaroop/arrays/TwoRepeatingElements.java +++ b/src/me/ramswaroop/arrays/TwoRepeatingElements.java @@ -64,8 +64,8 @@ public static int[] getTwoRepeatingElements(int[] a) { /** * The algorithm is simple. We use index of the array to track repeating elements. - * Once we encounter a element lets say 2 then we make the 2nd index -ve just to mark - * that we have encountered 2. When we encounter 2 again and see that 2nd index + * Once we encounter a element lets say 2 then we make the element in 2nd index -ve just + * to mark that we have encountered 2. When we encounter 2 again and see that 2nd index * is already -ve we conclude that 2 is repeated. * * Similar to {@link me.ramswaroop.arrays.DuplicatesInArray#findDuplicatesInArray(int[])}. From 570f39e7f89ab2f6c26ddee47419bd7ddb60fa2b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 22 Aug 2015 12:22:19 +0530 Subject: [PATCH 253/417] equilibrium index : done --- .../ramswaroop/arrays/EquilibriumIndex.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/me/ramswaroop/arrays/EquilibriumIndex.java diff --git a/src/me/ramswaroop/arrays/EquilibriumIndex.java b/src/me/ramswaroop/arrays/EquilibriumIndex.java new file mode 100644 index 00000000..0fe83838 --- /dev/null +++ b/src/me/ramswaroop/arrays/EquilibriumIndex.java @@ -0,0 +1,56 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/22/15 + * @time: 11:56 AM + */ +public class EquilibriumIndex { + + /** + * EQUILIBRIUM INDEX of an array is an index such that the sum of elements at lower + * indexes is equal to the sum of elements at higher indexes. + *

+ * For example, in an array A = {-7, 1, 5, 2, -4, 3, 0} + *

+ * 3 is an equilibrium index, because + * A[0] + A[1] + A[2] = A[4] + A[5] + A[6] + *

+ * 6 is also an equilibrium index, because sum of zero elements is zero, + * i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5] = 0 + *

+ * 7 is not an equilibrium index, because it is not a valid index of array A. + * + * @param a + * @return equilibrium index of array {@param a}. + */ + public static int getEquilibriumIndex(int[] a) { + int totalSum = 0, leftSum = 0; + + for (int i = 0; i < a.length; i++) { + totalSum += a[i]; + } + + for (int i = 0; i < a.length; i++) { + totalSum -= a[i]; // totalSum now holds the right sum + if (leftSum == totalSum) { + return i; // left sum == right sum + } + leftSum += a[i]; // update left sum + } + + return -1; + } + + public static void main(String a[]) { + System.out.println(getEquilibriumIndex(new int[]{-7, 1, 5, 2, -4, 3, 0})); + System.out.println(getEquilibriumIndex(new int[]{-7, 1, 5, 0, 0, 0, 0, 1, 2, -4, 1, 3, 0})); + System.out.println(getEquilibriumIndex(new int[]{4, 5, 2, 1, 6, 7, 8, 0, 1})); + System.out.println(getEquilibriumIndex(new int[]{0})); + System.out.println(getEquilibriumIndex(new int[]{0, 0, 0})); + System.out.println(getEquilibriumIndex(new int[]{1, 1})); + System.out.println(getEquilibriumIndex(new int[]{1, 1, 1})); + } +} From c2ad1ea6d449f23455558a44fcbb5ff6a5442307 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 22 Aug 2015 13:14:08 +0530 Subject: [PATCH 254/417] selection sort : done --- src/me/ramswaroop/arrays/SelectionSort.java | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SelectionSort.java diff --git a/src/me/ramswaroop/arrays/SelectionSort.java b/src/me/ramswaroop/arrays/SelectionSort.java new file mode 100644 index 00000000..f17048bf --- /dev/null +++ b/src/me/ramswaroop/arrays/SelectionSort.java @@ -0,0 +1,59 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/22/15 + * @time: 12:28 PM + */ +public class SelectionSort { + + /** + * Selection Sort. + * + * Explanation: + * This is one of the simplest algorithm where each time the smallest/largest + * element is chosen and placed at the appropriate position and then again the + * logic is applied on rest of the elements till the entire array is sorted. + * + * Time complexity: O(n) for all cases. + * + * NOTE: Advantage of this sort is that it requires minimum number of memory writes + * like Cycle sort. + * + * + * @param a + */ + public static void selectionSort(int[] a) { + int minIndex; + + for (int i = 0; i < a.length - 1; i++) { + minIndex = i; + for (int j = i + 1; j < a.length; j++) { + if (a[j] < a[minIndex]) { + minIndex = j; + } + } + swap(a, i, minIndex); + } + } + + private static void swap(int[] a, int index1, int index2) { + int temp = a[index1]; + a[index1] = a[index2]; + a[index2] = temp; + } + + public static void main(String a[]) { + int[] ar = new int[]{3, 2, 1, 5, 6, 9, 7, 10}; + selectionSort(ar); + System.out.println(Arrays.toString(ar)); + + ar = new int[]{3, 2, 1, 5, 5, 6, 9, 7, 6, 10}; + selectionSort(ar); + System.out.println(Arrays.toString(ar)); + } +} From e4615a09cacb774b0fc0cbed9a438de7e68bc933 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 22 Aug 2015 16:41:40 +0530 Subject: [PATCH 255/417] matrix rotation : done --- .../arrays/RotateMatrixBy90Degrees.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java diff --git a/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java b/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java new file mode 100644 index 00000000..31b36232 --- /dev/null +++ b/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java @@ -0,0 +1,47 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/22/15 + * @time: 4:03 PM + */ +public class RotateMatrixBy90Degrees { + + public static int[][] rotateMatrixBy90DegreesRight(int[][] a) { + int rows = a.length, columns = a[0].length; + int[][] rotatedMatrix = new int[columns][rows]; + + for (int i = 0; --rows >= 0 && i < a.length; i++) { + for (int j = 0; j < a[0].length; j++) { + rotatedMatrix[j][rows] = a[i][j]; + } + } + + return rotatedMatrix; + } + + private static void print2DMatrix(int[][] a) { + for (int i = 0; i < a.length; i++) { + for (int j = 0; j < a[0].length; j++) { + System.out.print(a[i][j]); + } + System.out.println(); + } + } + + public static void main(String a[]) { + int[][] ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + print2DMatrix(ar); + System.out.println("--------"); + print2DMatrix(rotateMatrixBy90DegreesRight(ar)); + + System.out.println("========"); + + ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 5, 7}}; + print2DMatrix(ar); + System.out.println("--------"); + print2DMatrix(rotateMatrixBy90DegreesRight(ar)); + } +} From 6344e34109552f7f0b9ba6e31c5b4b874a26cd18 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 23 Aug 2015 22:54:44 +0530 Subject: [PATCH 256/417] search in sorted 2D array : initial commit --- .../arrays/SearchInSorted2DArray.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SearchInSorted2DArray.java diff --git a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java new file mode 100644 index 00000000..9bee7f01 --- /dev/null +++ b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java @@ -0,0 +1,51 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/23/15 + * @time: 10:31 PM + */ +public class SearchInSorted2DArray { + + public static int[] search(int[][] a, int i, int j, int value) { + + if (i == a.length && j == a[0].length && i == j && a[i][j] != value) { + return new int[]{-1, -1}; + } + + if (a[i][j] == value) { + return new int[]{i, j}; + } else if (a[i][j] < value && j < a[0].length - 1 && a[i][j + 1] <= value) { + return search(a, i, j + 1, value); + } else if (a[i][j] < value && i < a.length - 1 && a[i + 1][j] <= value) { + return search(a, i + 1, j, value); + } else if (a[i][j] > value && i > 0) { + return search(a, i - 1, j, value); + } else { + return new int[]{-1, -1}; + } + } + + private static void print2DMatrix(int[][] a) { + for (int i = 0; i < a.length; i++) { + for (int j = 0; j < a[0].length; j++) { + System.out.print(a[i][j]); + } + System.out.println(); + } + } + + public static void main(String a[]) { + int[][] ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + print2DMatrix(ar); + System.out.println(Arrays.toString(search(ar, 0, 0, 4))); + System.out.println(Arrays.toString(search(ar, 0, 0, 6))); + System.out.println(Arrays.toString(search(ar, 0, 0, 1))); + System.out.println(Arrays.toString(search(ar, 0, 0, 8))); + System.out.println(Arrays.toString(search(ar, 0, 0, 9))); + } +} From de151ed5c65f99dd3c24bd2de122b5058f054db4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 23 Aug 2015 22:58:13 +0530 Subject: [PATCH 257/417] matrix rotation : comments added --- .../arrays/RotateMatrixBy90Degrees.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java b/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java index 31b36232..9d81e9d8 100644 --- a/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java +++ b/src/me/ramswaroop/arrays/RotateMatrixBy90Degrees.java @@ -9,6 +9,17 @@ */ public class RotateMatrixBy90Degrees { + /** + * Rotates a 2-D array by 90 degrees clockwise. + *

+ * The algorithm is simple: + * 1st row = last column + * 2nd row = 2nd last column + * and so on... + * + * @param a + * @return + */ public static int[][] rotateMatrixBy90DegreesRight(int[][] a) { int rows = a.length, columns = a[0].length; int[][] rotatedMatrix = new int[columns][rows]; @@ -36,9 +47,9 @@ public static void main(String a[]) { print2DMatrix(ar); System.out.println("--------"); print2DMatrix(rotateMatrixBy90DegreesRight(ar)); - + System.out.println("========"); - + ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 5, 7}}; print2DMatrix(ar); System.out.println("--------"); From 3438b1297a3615d0c7e78e995bc81b4f41e81eff Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 24 Aug 2015 16:30:07 +0530 Subject: [PATCH 258/417] search in sorted 2D array : done --- .../arrays/SearchInSorted2DArray.java | 40 +++++++++++++------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java index 9bee7f01..fedd1997 100644 --- a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java +++ b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java @@ -11,20 +11,29 @@ */ public class SearchInSorted2DArray { + /** + * Searches {@param value} in a square sized 2-D array {@param a} which is sorted + * both row wise and column wise. + *

+ * Time complexity: O(n) where n is size of 2-D array. + * + * @param a + * @param i + * @param j + * @param value + * @return + */ public static int[] search(int[][] a, int i, int j, int value) { - - if (i == a.length && j == a[0].length && i == j && a[i][j] != value) { - return new int[]{-1, -1}; + for (int x = 0; x < a.length; x++) { + if (a[i][x] == value) { + return new int[]{i, x}; + } else if (a[x][j] == value) { + return new int[]{x, j}; + } } - if (a[i][j] == value) { - return new int[]{i, j}; - } else if (a[i][j] < value && j < a[0].length - 1 && a[i][j + 1] <= value) { - return search(a, i, j + 1, value); - } else if (a[i][j] < value && i < a.length - 1 && a[i + 1][j] <= value) { - return search(a, i + 1, j, value); - } else if (a[i][j] > value && i > 0) { - return search(a, i - 1, j, value); + if (i < a.length - 1) { + return search(a, i + 1, j + 1, value); } else { return new int[]{-1, -1}; } @@ -42,10 +51,17 @@ private static void print2DMatrix(int[][] a) { public static void main(String a[]) { int[][] ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print2DMatrix(ar); + System.out.println(Arrays.toString(search(ar, 0, 0, 1))); + System.out.println(Arrays.toString(search(ar, 0, 0, 2))); + System.out.println(Arrays.toString(search(ar, 0, 0, 3))); System.out.println(Arrays.toString(search(ar, 0, 0, 4))); + System.out.println(Arrays.toString(search(ar, 0, 0, 5))); System.out.println(Arrays.toString(search(ar, 0, 0, 6))); - System.out.println(Arrays.toString(search(ar, 0, 0, 1))); + System.out.println(Arrays.toString(search(ar, 0, 0, 7))); System.out.println(Arrays.toString(search(ar, 0, 0, 8))); System.out.println(Arrays.toString(search(ar, 0, 0, 9))); + System.out.println(Arrays.toString(search(ar, 0, 0, 10))); + System.out.println(Arrays.toString(search(ar, 0, 0, 11))); + System.out.println(Arrays.toString(search(ar, 0, 0, 12))); } } From 7abb6f72111897ffcfa8163966f345b5b312963a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 24 Aug 2015 16:46:01 +0530 Subject: [PATCH 259/417] search in sorted 2D array : optimized a little bit --- src/me/ramswaroop/arrays/SearchInSorted2DArray.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java index fedd1997..7713cab4 100644 --- a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java +++ b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java @@ -16,15 +16,20 @@ public class SearchInSorted2DArray { * both row wise and column wise. *

* Time complexity: O(n) where n is size of 2-D array. + *

+ * Explanation: + * Linearly searches across rows and columns until the element is found or till the last element. If + * the element is not found in the 1st row or 1st column then we search in 2nd row and 2nd column + * and so on. * * @param a * @param i * @param j * @param value - * @return + * @return an array consisting of co-ordinates if {@param value} is found otherwise {@code new int[]{-1, -1}}. */ public static int[] search(int[][] a, int i, int j, int value) { - for (int x = 0; x < a.length; x++) { + for (int x = 0; x < a.length && (a[i][x] <= value || a[x][j] <= value); x++) { if (a[i][x] == value) { return new int[]{i, x}; } else if (a[x][j] == value) { From cfb991f0d757245953b1659fe738992485871773 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 25 Aug 2015 15:19:43 +0530 Subject: [PATCH 260/417] search in sorted 2D array : more optimized version added --- .../arrays/SearchInSorted2DArray.java | 80 +++++++++++++++---- 1 file changed, 63 insertions(+), 17 deletions(-) diff --git a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java index 7713cab4..aa02619a 100644 --- a/src/me/ramswaroop/arrays/SearchInSorted2DArray.java +++ b/src/me/ramswaroop/arrays/SearchInSorted2DArray.java @@ -12,10 +12,13 @@ public class SearchInSorted2DArray { /** - * Searches {@param value} in a square sized 2-D array {@param a} which is sorted + * Searches {@param value} in a SQUARE sized 2-D array {@param a} which is sorted * both row wise and column wise. *

- * Time complexity: O(n) where n is size of 2-D array. + * Time complexity: + * T(n) = T(n) + T(n-1) + T(n-2) + .... + T(1) + * T(n) = n(n+1)/2 + * T(n) = O(n^2) where n is size of 2-D array. *

* Explanation: * Linearly searches across rows and columns until the element is found or till the last element. If @@ -28,8 +31,8 @@ public class SearchInSorted2DArray { * @param value * @return an array consisting of co-ordinates if {@param value} is found otherwise {@code new int[]{-1, -1}}. */ - public static int[] search(int[][] a, int i, int j, int value) { - for (int x = 0; x < a.length && (a[i][x] <= value || a[x][j] <= value); x++) { + public static int[] linearSearchNaive(int[][] a, int i, int j, int value) { + for (int x = i; x < a.length && (a[i][x] <= value || a[x][j] <= value); x++) { if (a[i][x] == value) { return new int[]{i, x}; } else if (a[x][j] == value) { @@ -38,12 +41,42 @@ public static int[] search(int[][] a, int i, int j, int value) { } if (i < a.length - 1) { - return search(a, i + 1, j + 1, value); + return linearSearchNaive(a, i + 1, j + 1, value); } else { return new int[]{-1, -1}; } } + /** + * More efficient way to search in a 2-D array sorted both row wise and column wise. + *

+ * Explanation: + * We start from top right corner (we can also start from bottom left corner) and move left if current + * element is greater than the value to be searched and bottom if current element is + * smaller than the value to be searched. + *

+ * Time complexity: O(m+n) where m = no. of rows, n = no. of columns + * + * @return + * @link http://articles.leetcode.com/2010/10/searching-2d-sorted-matrix-part-ii.html + */ + public static int[] linearSearch(int[][] a, int value) { + int i = 0, j = a[0].length - 1; // start from top right corner + + while (i < a.length && j >= 0) { + if (a[i][j] == value) { + return new int[]{i, j}; + } else if (a[i][j] > value) { + j--; // move left + } else { + i++; // move down + } + } + + return new int[]{-1, -1}; + + } + private static void print2DMatrix(int[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { @@ -56,17 +89,30 @@ private static void print2DMatrix(int[][] a) { public static void main(String a[]) { int[][] ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print2DMatrix(ar); - System.out.println(Arrays.toString(search(ar, 0, 0, 1))); - System.out.println(Arrays.toString(search(ar, 0, 0, 2))); - System.out.println(Arrays.toString(search(ar, 0, 0, 3))); - System.out.println(Arrays.toString(search(ar, 0, 0, 4))); - System.out.println(Arrays.toString(search(ar, 0, 0, 5))); - System.out.println(Arrays.toString(search(ar, 0, 0, 6))); - System.out.println(Arrays.toString(search(ar, 0, 0, 7))); - System.out.println(Arrays.toString(search(ar, 0, 0, 8))); - System.out.println(Arrays.toString(search(ar, 0, 0, 9))); - System.out.println(Arrays.toString(search(ar, 0, 0, 10))); - System.out.println(Arrays.toString(search(ar, 0, 0, 11))); - System.out.println(Arrays.toString(search(ar, 0, 0, 12))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 1))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 2))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 3))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 4))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 5))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 6))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 7))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 8))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 9))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 10))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 11))); + System.out.println(Arrays.toString(linearSearchNaive(ar, 0, 0, 12))); + System.out.println("============"); + System.out.println(Arrays.toString(linearSearch(ar, 1))); + System.out.println(Arrays.toString(linearSearch(ar, 2))); + System.out.println(Arrays.toString(linearSearch(ar, 3))); + System.out.println(Arrays.toString(linearSearch(ar, 4))); + System.out.println(Arrays.toString(linearSearch(ar, 5))); + System.out.println(Arrays.toString(linearSearch(ar, 6))); + System.out.println(Arrays.toString(linearSearch(ar, 7))); + System.out.println(Arrays.toString(linearSearch(ar, 8))); + System.out.println(Arrays.toString(linearSearch(ar, 9))); + System.out.println(Arrays.toString(linearSearch(ar, 10))); + System.out.println(Arrays.toString(linearSearch(ar, 11))); + System.out.println(Arrays.toString(linearSearch(ar, 12))); } } From c412b8ee0552d5a512756fcf86d1ac7a179fccd6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 26 Aug 2015 12:47:19 +0530 Subject: [PATCH 261/417] next greater element : done --- .../ramswaroop/arrays/NextGreaterElement.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/me/ramswaroop/arrays/NextGreaterElement.java diff --git a/src/me/ramswaroop/arrays/NextGreaterElement.java b/src/me/ramswaroop/arrays/NextGreaterElement.java new file mode 100644 index 00000000..68ff7f68 --- /dev/null +++ b/src/me/ramswaroop/arrays/NextGreaterElement.java @@ -0,0 +1,40 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/26/15 + * @time: 12:35 PM + */ +public class NextGreaterElement { + + /** + * Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element + * for an element x is the first greater element on the right side of x in array. Elements for which + * no greater element exist, consider next greater element as -1. + * + * @param a + * @return + */ + public static int[] nextGreaterElements(int[] a) { + int[] greaterElements = new int[a.length]; // stores the next greater element of each element in array a + greaterElements[a.length - 1] = -1; // no elements greater than the last element + + for (int i = a.length - 2; i >= 0; i--) { + if (a[i + 1] > a[i]) { // if next element is greater than the current element + greaterElements[i] = a[i + 1]; + } else { // if next element is smaller then find the greater element of the next element + greaterElements[i] = greaterElements[i + 1]; + } + } + return greaterElements; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(nextGreaterElements(new int[]{4, 5, 2, 25}))); + System.out.println(Arrays.toString(nextGreaterElements(new int[]{11, 13, 21, 3}))); + } +} From 75d59413ca41fd2050a3d0f48353a7e4966d8207 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 26 Aug 2015 12:50:26 +0530 Subject: [PATCH 262/417] divide by zero : added comments --- src/me/ramswaroop/practice/DivideByZero.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/practice/DivideByZero.java b/src/me/ramswaroop/practice/DivideByZero.java index 5169ba39..20f05c02 100644 --- a/src/me/ramswaroop/practice/DivideByZero.java +++ b/src/me/ramswaroop/practice/DivideByZero.java @@ -9,6 +9,7 @@ */ public class DivideByZero { public static void main(String[] a) { - System.out.print(5.0/0); + System.out.println(5.0/0); // doesn't throw any exception + System.out.println(5/0); // throws runtime exception (arithmetic exception) } } From 1ef3296f99580d8286c299e028ef89c51a1e67bf Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 27 Aug 2015 18:49:05 +0530 Subject: [PATCH 263/417] next greater element : error fixed --- .../ramswaroop/arrays/NextGreaterElement.java | 44 ++++++++++++++----- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/src/me/ramswaroop/arrays/NextGreaterElement.java b/src/me/ramswaroop/arrays/NextGreaterElement.java index 68ff7f68..0c468c4d 100644 --- a/src/me/ramswaroop/arrays/NextGreaterElement.java +++ b/src/me/ramswaroop/arrays/NextGreaterElement.java @@ -1,6 +1,7 @@ package me.ramswaroop.arrays; -import java.util.Arrays; +import me.ramswaroop.common.LinkedStack; +import me.ramswaroop.common.Stack; /** * Created by IntelliJ IDEA. @@ -19,22 +20,41 @@ public class NextGreaterElement { * @param a * @return */ - public static int[] nextGreaterElements(int[] a) { - int[] greaterElements = new int[a.length]; // stores the next greater element of each element in array a - greaterElements[a.length - 1] = -1; // no elements greater than the last element + public static void nextGreaterElements(int[] a) { + int i = 0; + Stack stack = new LinkedStack<>(); // used to store elements whose NGE is yet to be determined - for (int i = a.length - 2; i >= 0; i--) { - if (a[i + 1] > a[i]) { // if next element is greater than the current element - greaterElements[i] = a[i + 1]; - } else { // if next element is smaller then find the greater element of the next element - greaterElements[i] = greaterElements[i + 1]; + for (; i < a.length - 1; i++) { + stack.push(a[i]); + + while (!stack.isEmpty()) { + Integer pop = stack.pop(); + if (pop < a[i + 1]) { // NGE found for popped element + System.out.println(pop + "->" + a[i + 1]); + } else { + stack.push(pop); // NGE still not found for popped element, so push it again + break; + } } } - return greaterElements; + + // no NGE for elements left in stack + while (!stack.isEmpty()) { + System.out.println(stack.pop() + "->" + -1); + } + + // no NGE for last element + System.out.println(a[i] + "->" + -1); } public static void main(String a[]) { - System.out.println(Arrays.toString(nextGreaterElements(new int[]{4, 5, 2, 25}))); - System.out.println(Arrays.toString(nextGreaterElements(new int[]{11, 13, 21, 3}))); + int[] ar = new int[]{4, 5, 2, 25}; + nextGreaterElements(ar); + System.out.println("========="); + ar = new int[]{11, 13, 21, 3}; + nextGreaterElements(ar); + System.out.println("========="); + ar = new int[]{1, 5, 3, 4, 2, 0, 11}; + nextGreaterElements(ar); } } From 6046746b4018eea6a49d049eeeb6648229eeae85 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 28 Aug 2015 11:49:20 +0530 Subject: [PATCH 264/417] consecutive elements : initial commit --- .../arrays/ConsecutiveElements.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/me/ramswaroop/arrays/ConsecutiveElements.java diff --git a/src/me/ramswaroop/arrays/ConsecutiveElements.java b/src/me/ramswaroop/arrays/ConsecutiveElements.java new file mode 100644 index 00000000..f09e6ba7 --- /dev/null +++ b/src/me/ramswaroop/arrays/ConsecutiveElements.java @@ -0,0 +1,51 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/28/15 + * @time: 10:32 AM + */ +public class ConsecutiveElements { + + /** + * + * @param a + * @return + */ + public static boolean areConsecutiveElements(int[] a) { + int min = a[0], max = a[0]; + int[] visitedArray = new int[a.length]; + + for (int i = 1; i < a.length; i++) { + if (a[i] < min) { + min = a[i]; + } + if (a[i] > max) { + max = a[i]; + } + } + + if (a.length != max - min + 1) { + return false; + } + + for (int i = 0; i < a.length; i++) { + if (visitedArray[a[i] - min] == 0) { + visitedArray[a[i] - min] = a[i]; + } else { + return false; + } + } + + return true; + } + + public static void main(String a[]) { + System.out.println(areConsecutiveElements(new int[]{5, 4, 3, 2, 1})); + System.out.println(areConsecutiveElements(new int[]{67, 68, 69, 72, 70, 71})); + System.out.println(areConsecutiveElements(new int[]{67, 68, 69, 72, 70, 71, 70})); + System.out.println(areConsecutiveElements(new int[]{8, 5, 2, 4, 3, 1})); + } +} From fbcdf23e52e0e93a2f7c37614236c8f53c5acefc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 28 Aug 2015 14:32:19 +0530 Subject: [PATCH 265/417] consecutive elements : comments added --- .../arrays/ConsecutiveElements.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/ConsecutiveElements.java b/src/me/ramswaroop/arrays/ConsecutiveElements.java index f09e6ba7..12cb87fe 100644 --- a/src/me/ramswaroop/arrays/ConsecutiveElements.java +++ b/src/me/ramswaroop/arrays/ConsecutiveElements.java @@ -10,7 +10,23 @@ public class ConsecutiveElements { /** - * + * Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers. + *

+ * Examples: + * a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers + * from 1 to 5. + * b) If array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive. + * c) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive. + *

+ * ALGORITHM: + * The idea is to check for following two conditions. If following two conditions are true, then return true. + * 1) max – min + 1 = n where max is the maximum element in array, min is minimum element in array and n is the number + * of elements in array. + * 2) All elements are distinct. + *

+ * To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input + * array arr[] to visited array by using arr[i] – min as index in visited[]. + * * @param a * @return */ @@ -18,6 +34,7 @@ public static boolean areConsecutiveElements(int[] a) { int min = a[0], max = a[0]; int[] visitedArray = new int[a.length]; + // find min and max element for (int i = 1; i < a.length; i++) { if (a[i] < min) { min = a[i]; @@ -27,10 +44,12 @@ public static boolean areConsecutiveElements(int[] a) { } } + // diff of max and min should be equal to length of array if (a.length != max - min + 1) { return false; } + // check for distinct elements for (int i = 0; i < a.length; i++) { if (visitedArray[a[i] - min] == 0) { visitedArray[a[i] - min] = a[i]; From 0379082ee99e60bc3cf8a827a9445219c2e16fa6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 29 Aug 2015 13:04:44 +0530 Subject: [PATCH 266/417] consecutive elements : added another method which uses O(1) auxiliary space --- .../arrays/ConsecutiveElements.java | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/ConsecutiveElements.java b/src/me/ramswaroop/arrays/ConsecutiveElements.java index 12cb87fe..4cd92231 100644 --- a/src/me/ramswaroop/arrays/ConsecutiveElements.java +++ b/src/me/ramswaroop/arrays/ConsecutiveElements.java @@ -25,7 +25,7 @@ public class ConsecutiveElements { * 2) All elements are distinct. *

* To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input - * array arr[] to visited array by using arr[i] – min as index in visited[]. + * array arr[] to visited array by using arr[i] – min as index in visited[]. So we need O(n) auxiliary space. * * @param a * @return @@ -61,10 +61,53 @@ public static boolean areConsecutiveElements(int[] a) { return true; } + /** + * This approach is similar to {@link me.ramswaroop.arrays.ConsecutiveElements#areConsecutiveElements(int[])} but + * requires O(1) auxiliary space instead of O(n). But the only con of this method is that it modifies the original + * input array {@param a}. + * + * @param a + * @return + */ + public static boolean areConsecutiveElementsInO1Space(int[] a) { + int min = a[0], max = a[0]; + + // find min and max element + for (int i = 1; i < a.length; i++) { + if (a[i] < min) { + min = a[i]; + } + if (a[i] > max) { + max = a[i]; + } + } + + // diff of max and min should be equal to length of array + if (a.length != max - min + 1) { + return false; + } + + // check for distinct elements + for (int i = 0; i < a.length; i++) { + if (a[Math.abs(a[i]) - min] >= 0) { + a[Math.abs(a[i]) - min] = -(a[Math.abs(a[i]) - min]); + } else { + return false; + } + } + + return true; + } + public static void main(String a[]) { System.out.println(areConsecutiveElements(new int[]{5, 4, 3, 2, 1})); System.out.println(areConsecutiveElements(new int[]{67, 68, 69, 72, 70, 71})); System.out.println(areConsecutiveElements(new int[]{67, 68, 69, 72, 70, 71, 70})); System.out.println(areConsecutiveElements(new int[]{8, 5, 2, 4, 3, 1})); + System.out.println("=============="); + System.out.println(areConsecutiveElementsInO1Space(new int[]{5, 4, 3, 2, 1})); + System.out.println(areConsecutiveElementsInO1Space(new int[]{67, 68, 69, 72, 70, 71})); + System.out.println(areConsecutiveElementsInO1Space(new int[]{67, 68, 69, 72, 70, 71, 70})); + System.out.println(areConsecutiveElementsInO1Space(new int[]{8, 5, 2, 4, 3, 1})); } } From 59b713155ea73554ee1b8abdf626a70420459a54 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 30 Aug 2015 18:25:23 +0530 Subject: [PATCH 267/417] smallest missing number : initial commit --- .../arrays/SmallestMissingNumber.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SmallestMissingNumber.java diff --git a/src/me/ramswaroop/arrays/SmallestMissingNumber.java b/src/me/ramswaroop/arrays/SmallestMissingNumber.java new file mode 100644 index 00000000..14887f87 --- /dev/null +++ b/src/me/ramswaroop/arrays/SmallestMissingNumber.java @@ -0,0 +1,19 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/29/15 + * @time: 12:51 PM + */ +public class SmallestMissingNumber { + + public void smallestMissingNumber(int[] a) { + + } + + public static void main(String a[]) { + + } +} From cbb4734193be51e08b9507f353120466457d06fc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 30 Aug 2015 18:30:49 +0530 Subject: [PATCH 268/417] selection sort : refactoring --- src/me/ramswaroop/arrays/SelectionSort.java | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/arrays/SelectionSort.java b/src/me/ramswaroop/arrays/SelectionSort.java index f17048bf..b2084fc7 100644 --- a/src/me/ramswaroop/arrays/SelectionSort.java +++ b/src/me/ramswaroop/arrays/SelectionSort.java @@ -13,18 +13,17 @@ public class SelectionSort { /** * Selection Sort. - * - * Explanation: + *

+ * Explanation: * This is one of the simplest algorithm where each time the smallest/largest * element is chosen and placed at the appropriate position and then again the * logic is applied on rest of the elements till the entire array is sorted. - * + *

* Time complexity: O(n) for all cases. - * + *

* NOTE: Advantage of this sort is that it requires minimum number of memory writes - * like Cycle sort. - * - * + * like Cycle sort. + * * @param a */ public static void selectionSort(int[] a) { @@ -41,6 +40,13 @@ public static void selectionSort(int[] a) { } } + /** + * Swaps variables in {@param a} at {@param index1} with {@param index2}. + * + * @param a + * @param index1 + * @param index2 + */ private static void swap(int[] a, int index1, int index2) { int temp = a[index1]; a[index1] = a[index2]; From 5b80a89c4140775f715769bcb3dba243bad7bc69 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 31 Aug 2015 13:28:15 +0530 Subject: [PATCH 269/417] smallest missing number : done --- .../arrays/SmallestMissingNumber.java | 37 +++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/arrays/SmallestMissingNumber.java b/src/me/ramswaroop/arrays/SmallestMissingNumber.java index 14887f87..e2e8fcfd 100644 --- a/src/me/ramswaroop/arrays/SmallestMissingNumber.java +++ b/src/me/ramswaroop/arrays/SmallestMissingNumber.java @@ -9,11 +9,42 @@ */ public class SmallestMissingNumber { - public void smallestMissingNumber(int[] a) { - + /** + * Modified Binary Search to find the smallest missing number in an array + * {@param a} consisting of numbers between 0 to m - 1 and m > n where n is + * length of array. + *

+ * EXPLANATION: + * In standard Binary Search, the element to be searched is compared with + * the middle element and on the basis of comparison result, we decide whether + * to search is over or to go to left half or right half. + * In this method, we modify the standard Binary Search algorithm to compare the + * middle element with its index and make decision on the basis of this comparison. + * + * @param a + * @param low + * @param high + * @return + */ + public static int smallestMissingNumber(int[] a, int low, int high) { + if (low < high) { + int mid = (low + high) / 2; + + if (a[mid] == mid) { + return smallestMissingNumber(a, mid + 1, high); + } else if (a[mid] > mid) { + return smallestMissingNumber(a, low, mid - 1); + } else { + return smallestMissingNumber(a, mid + 1, high); + } + } else { + return low; + } } public static void main(String a[]) { - + System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 6, 9}, 0, 4)); + System.out.println(smallestMissingNumber(new int[]{4, 5, 10, 11}, 0, 3)); + System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 10}, 0, 8)); } } From a5afb1daf2f2baa545f72d28bd30581b7fe6ce6b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 31 Aug 2015 13:33:45 +0530 Subject: [PATCH 270/417] smallest missing number : added test cases --- src/me/ramswaroop/arrays/SmallestMissingNumber.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/SmallestMissingNumber.java b/src/me/ramswaroop/arrays/SmallestMissingNumber.java index e2e8fcfd..71e6a629 100644 --- a/src/me/ramswaroop/arrays/SmallestMissingNumber.java +++ b/src/me/ramswaroop/arrays/SmallestMissingNumber.java @@ -14,11 +14,14 @@ public class SmallestMissingNumber { * {@param a} consisting of numbers between 0 to m - 1 and m > n where n is * length of array. *

+ * Time complexity: O(log n) + * Con: Doesn't work if there are repetitive elements. + *

* EXPLANATION: * In standard Binary Search, the element to be searched is compared with * the middle element and on the basis of comparison result, we decide whether * to search is over or to go to left half or right half. - * In this method, we modify the standard Binary Search algorithm to compare the + * In this method, we modify the standard Binary Search algorithm to compare the * middle element with its index and make decision on the basis of this comparison. * * @param a @@ -46,5 +49,6 @@ public static void main(String a[]) { System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 6, 9}, 0, 4)); System.out.println(smallestMissingNumber(new int[]{4, 5, 10, 11}, 0, 3)); System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 10}, 0, 8)); + System.out.println(smallestMissingNumber(new int[]{0, 1, 3, 3, 11}, 0, 4)); // doesn't work } } From f62e213d783c38adcf938379a2ac6d37ff2024b9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 31 Aug 2015 15:16:16 +0530 Subject: [PATCH 271/417] smallest missing number : minor fix --- src/me/ramswaroop/arrays/SmallestMissingNumber.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/SmallestMissingNumber.java b/src/me/ramswaroop/arrays/SmallestMissingNumber.java index 71e6a629..5a8cd2a6 100644 --- a/src/me/ramswaroop/arrays/SmallestMissingNumber.java +++ b/src/me/ramswaroop/arrays/SmallestMissingNumber.java @@ -30,7 +30,7 @@ public class SmallestMissingNumber { * @return */ public static int smallestMissingNumber(int[] a, int low, int high) { - if (low < high) { + if (low <= high) { int mid = (low + high) / 2; if (a[mid] == mid) { @@ -46,9 +46,11 @@ public static int smallestMissingNumber(int[] a, int low, int high) { } public static void main(String a[]) { + System.out.println(smallestMissingNumber(new int[]{0, 1}, 0, 1)); System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 6, 9}, 0, 4)); System.out.println(smallestMissingNumber(new int[]{4, 5, 10, 11}, 0, 3)); + System.out.println(smallestMissingNumber(new int[]{0, 4, 5, 10, 56}, 0, 4)); System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 10}, 0, 8)); - System.out.println(smallestMissingNumber(new int[]{0, 1, 3, 3, 11}, 0, 4)); // doesn't work + System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 3, 3}, 0, 4)); // doesn't work } } From b8af09cb90f2fcec048a1982536a9fd2f2229779 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 31 Aug 2015 15:24:30 +0530 Subject: [PATCH 272/417] binary search : modified --- src/me/ramswaroop/common/Search.java | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/common/Search.java b/src/me/ramswaroop/common/Search.java index a2e08def..69d296f0 100644 --- a/src/me/ramswaroop/common/Search.java +++ b/src/me/ramswaroop/common/Search.java @@ -10,7 +10,9 @@ public class Search { /** - * Searches an item in a sorted array in O(log n) time. + * Searches an element {@param n} in a sorted array {@param a} + * and returns its index in O(log n) time. The Index may not + * correspond to the first occurrence of the element. * * @param a * @param n @@ -21,16 +23,19 @@ public static int binarySearch(int a[], int n) { } public static int binarySearch(int a[], int n, int low, int high) { - int mid = (low + high) / 2; - if (high < low) { - return -1; - } else if (n == a[mid]) { - return mid; - } else if (n < a[mid]) { - return binarySearch(a, n, 0, mid - 1); + if (low <= high) { + int mid = (low + high) / 2; + + if (n == a[mid]) { + return mid; + } else if (n < a[mid]) { + return binarySearch(a, n, 0, mid - 1); + } else { + return binarySearch(a, n, mid + 1, high); + } } else { - return binarySearch(a, n, mid + 1, high); + return -1; } } @@ -41,5 +46,9 @@ public static int binarySearch(int a[], int n, int low, int high) { */ public static void main(String a[]) { System.out.println(binarySearch(new int[]{0, 2}, 2)); + System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 2)); + System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 3)); + System.out.println(binarySearch(new int[]{0, 2}, 0)); + System.out.println(binarySearch(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); // doesn't return index of first occurrence } } From 8b7305a1d69d7a4995f00fc6dd4cc128ab1b4365 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 31 Aug 2015 17:01:20 +0530 Subject: [PATCH 273/417] majority element in sorted array : refactoring --- .../arrays/MajorityElementInSortedArray.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java b/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java index 9588a658..f75289fe 100644 --- a/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java +++ b/src/me/ramswaroop/arrays/MajorityElementInSortedArray.java @@ -21,7 +21,7 @@ public class MajorityElementInSortedArray { */ public static boolean isMajorityElement(int[] a, int n) { int l = a.length; - int startIndex = getIndexOf(a, 0, l - 1, n); + int startIndex = getFirstIndexOf(a, n, 0, l - 1); // element not found if (startIndex == -1) return false; @@ -43,7 +43,7 @@ public static boolean isMajorityElement(int[] a, int n) { * @param n * @return */ - public static int getIndexOf(int[] a, int low, int high, int n) { + public static int getFirstIndexOf(int[] a, int n, int low, int high) { if (low <= high) { int mid = (low + high) / 2; /** @@ -53,12 +53,12 @@ public static int getIndexOf(int[] a, int low, int high, int n) { * (i) mid == 0 and a[mid] == n * (ii) n > a[mid-1] and a[mid] == n */ - if ((mid == 0 || n > a[mid - 1]) && (a[mid] == n)) { + if (a[mid] == n && (mid == 0 || n > a[mid - 1])) { return mid; } else if (n <= a[mid]) { - return getIndexOf(a, low, mid - 1, n); + return getFirstIndexOf(a, n, low, mid - 1); } else { - return getIndexOf(a, mid + 1, high, n); + return getFirstIndexOf(a, n, mid + 1, high); } } return -1; From bd0ff7b4c4d13ef98ce41897ba9ba0cfe8758ab3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 31 Aug 2015 17:23:37 +0530 Subject: [PATCH 274/417] occurrences in sorted array : done --- .../arrays/OccurrencesInSortedArray.java | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/me/ramswaroop/arrays/OccurrencesInSortedArray.java diff --git a/src/me/ramswaroop/arrays/OccurrencesInSortedArray.java b/src/me/ramswaroop/arrays/OccurrencesInSortedArray.java new file mode 100644 index 00000000..d4af1859 --- /dev/null +++ b/src/me/ramswaroop/arrays/OccurrencesInSortedArray.java @@ -0,0 +1,85 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 8/31/15 + * @time: 2:52 PM + */ +public class OccurrencesInSortedArray { + + /** + * Finds the occurrences of {@param k} in sorted array {@param a} in + * O(log n) time. + * + * @param a + * @param k + * @return + */ + public static int getOccurrencesInSortedArray(int[] a, int k) { + int firstIndex = getFirstIndexOf(a, k, 0, a.length - 1); + // element not found + if (firstIndex == -1) { + return 0; + } + return getLastIndexOf(a, k, firstIndex, a.length - 1) - firstIndex + 1; + } + + /** + * Returns the index of first occurrence of {@param n} in array {@param a}. + * + * @param a + * @param low + * @param high + * @param n + * @return + */ + public static int getFirstIndexOf(int[] a, int n, int low, int high) { + if (low <= high) { + int mid = (low + high) / 2; + if (a[mid] == n && (mid == 0 || a[mid - 1] < n)) { + return mid; + } else if (a[mid] < n) { + return getFirstIndexOf(a, n, mid + 1, high); + } else { + return getFirstIndexOf(a, n, low, mid - 1); + } + } else { + return -1; + } + } + + /** + * Returns the index of last occurrence of {@param n} in array {@param a}. + * + * @param a + * @param low + * @param high + * @param n + * @return + */ + public static int getLastIndexOf(int[] a, int n, int low, int high) { + if (low <= high) { + int mid = (low + high) / 2; + if (a[mid] == n && (mid == a.length - 1 || a[mid + 1] > n)) { + return mid; + } else if (a[mid] <= n) { + return getLastIndexOf(a, n, mid + 1, high); + } else { + return getLastIndexOf(a, n, low, mid - 1); + } + } else { + return -1; + } + } + + public static void main(String a[]) { + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 1)); + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 1, 2, 2, 2, 2, 3}, 1)); + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 2)); + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 3)); + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 0)); + System.out.println(getOccurrencesInSortedArray(new int[]{1, 1, 2, 2, 2, 2, 3}, 4)); + } +} From be74c1e376c4c22920ceea5e69684b213b3bb11b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 1 Sep 2015 17:30:22 +0530 Subject: [PATCH 275/417] interpolation search : done + code refactoring --- .../ramswaroop/arrays/KthLargestElement.java | 1 + .../arrays/PivotedBinarySearch.java | 6 +-- .../arrays/TwoElementsSumClosestToZero.java | 2 + .../searching/BinarySearch.java} | 8 ++-- .../arrays/searching/InterpolationSearch.java | 47 +++++++++++++++++++ .../arrays/{ => sorting}/HeapSort.java | 2 +- .../arrays/{ => sorting}/MergeSort.java | 2 +- .../arrays/{ => sorting}/QuickSort.java | 2 +- .../arrays/{ => sorting}/SelectionSort.java | 2 +- 9 files changed, 61 insertions(+), 11 deletions(-) rename src/me/ramswaroop/{common/Search.java => arrays/searching/BinarySearch.java} (93%) create mode 100644 src/me/ramswaroop/arrays/searching/InterpolationSearch.java rename src/me/ramswaroop/arrays/{ => sorting}/HeapSort.java (95%) rename src/me/ramswaroop/arrays/{ => sorting}/MergeSort.java (97%) rename src/me/ramswaroop/arrays/{ => sorting}/QuickSort.java (98%) rename src/me/ramswaroop/arrays/{ => sorting}/SelectionSort.java (97%) diff --git a/src/me/ramswaroop/arrays/KthLargestElement.java b/src/me/ramswaroop/arrays/KthLargestElement.java index 07086965..d15a89fa 100644 --- a/src/me/ramswaroop/arrays/KthLargestElement.java +++ b/src/me/ramswaroop/arrays/KthLargestElement.java @@ -1,5 +1,6 @@ package me.ramswaroop.arrays; +import me.ramswaroop.arrays.sorting.MergeSort; import me.ramswaroop.common.MaxHeap; import java.util.Arrays; diff --git a/src/me/ramswaroop/arrays/PivotedBinarySearch.java b/src/me/ramswaroop/arrays/PivotedBinarySearch.java index aa5b5a98..d1b2ea7f 100644 --- a/src/me/ramswaroop/arrays/PivotedBinarySearch.java +++ b/src/me/ramswaroop/arrays/PivotedBinarySearch.java @@ -1,6 +1,6 @@ package me.ramswaroop.arrays; -import me.ramswaroop.common.Search; +import me.ramswaroop.arrays.searching.BinarySearch; /** * Created by IntelliJ IDEA. @@ -28,9 +28,9 @@ public static int pivotedBinarySearch(int a[], int n) { if (pivot == -1 || a[pivot] == n) { return pivot; } else if (n <= a[0]) { - return Search.binarySearch(a, n, pivot + 1, a.length - 1); + return BinarySearch.binarySearch(a, n, pivot + 1, a.length - 1); } else { - return Search.binarySearch(a, n, 0, pivot - 1); + return BinarySearch.binarySearch(a, n, 0, pivot - 1); } } diff --git a/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java b/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java index 8e3cf0ad..db1eb771 100644 --- a/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java +++ b/src/me/ramswaroop/arrays/TwoElementsSumClosestToZero.java @@ -1,5 +1,7 @@ package me.ramswaroop.arrays; +import me.ramswaroop.arrays.sorting.QuickSort; + import java.util.Arrays; /** diff --git a/src/me/ramswaroop/common/Search.java b/src/me/ramswaroop/arrays/searching/BinarySearch.java similarity index 93% rename from src/me/ramswaroop/common/Search.java rename to src/me/ramswaroop/arrays/searching/BinarySearch.java index 69d296f0..9f330bf6 100644 --- a/src/me/ramswaroop/common/Search.java +++ b/src/me/ramswaroop/arrays/searching/BinarySearch.java @@ -1,13 +1,13 @@ -package me.ramswaroop.common; +package me.ramswaroop.arrays.searching; /** * Created by IntelliJ IDEA. * * @author: ramswaroop - * @date: 5/31/15 - * @time: 10:45 PM + * @date: 9/1/15 + * @time: 4:56 PM */ -public class Search { +public class BinarySearch { /** * Searches an element {@param n} in a sorted array {@param a} diff --git a/src/me/ramswaroop/arrays/searching/InterpolationSearch.java b/src/me/ramswaroop/arrays/searching/InterpolationSearch.java new file mode 100644 index 00000000..81169cfa --- /dev/null +++ b/src/me/ramswaroop/arrays/searching/InterpolationSearch.java @@ -0,0 +1,47 @@ +package me.ramswaroop.arrays.searching; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/1/15 + * @time: 4:57 PM + */ +public class InterpolationSearch { + + /** + * @param a + * @param k + * @return + */ + public static int search(int[] a, int k) { + int low = 0, high = a.length - 1, mid; + + while (a[low] != a[high] && k >= a[low] && k <= a[high]) { + mid = low + (k - a[low]) * (high - low) / a[high] - a[low]; + + if (k < a[mid]) { + high = mid - 1; + } else if (k > a[mid]) { + low = mid + 1; + } else { + return mid; + } + } + + if (k == a[low]) { + return low; + } else { + return -1; + } + } + + public static void main(String a[]) { + System.out.println(search(new int[]{0, 2}, 2)); + System.out.println(search(new int[]{0, 1}, 2)); + System.out.println(search(new int[]{0, 1, 2, 3}, 2)); + System.out.println(search(new int[]{0, 1, 2, 3}, 3)); + System.out.println(search(new int[]{0, 2}, 0)); + System.out.println(search(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); + } +} diff --git a/src/me/ramswaroop/arrays/HeapSort.java b/src/me/ramswaroop/arrays/sorting/HeapSort.java similarity index 95% rename from src/me/ramswaroop/arrays/HeapSort.java rename to src/me/ramswaroop/arrays/sorting/HeapSort.java index d41b8e9d..5ada67b2 100644 --- a/src/me/ramswaroop/arrays/HeapSort.java +++ b/src/me/ramswaroop/arrays/sorting/HeapSort.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.arrays.sorting; import me.ramswaroop.common.MaxHeap; diff --git a/src/me/ramswaroop/arrays/MergeSort.java b/src/me/ramswaroop/arrays/sorting/MergeSort.java similarity index 97% rename from src/me/ramswaroop/arrays/MergeSort.java rename to src/me/ramswaroop/arrays/sorting/MergeSort.java index 4195cd6a..d5d8f024 100644 --- a/src/me/ramswaroop/arrays/MergeSort.java +++ b/src/me/ramswaroop/arrays/sorting/MergeSort.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.arrays.sorting; import java.util.Arrays; diff --git a/src/me/ramswaroop/arrays/QuickSort.java b/src/me/ramswaroop/arrays/sorting/QuickSort.java similarity index 98% rename from src/me/ramswaroop/arrays/QuickSort.java rename to src/me/ramswaroop/arrays/sorting/QuickSort.java index f0df4f35..83cdcd09 100644 --- a/src/me/ramswaroop/arrays/QuickSort.java +++ b/src/me/ramswaroop/arrays/sorting/QuickSort.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.arrays.sorting; import java.util.Arrays; diff --git a/src/me/ramswaroop/arrays/SelectionSort.java b/src/me/ramswaroop/arrays/sorting/SelectionSort.java similarity index 97% rename from src/me/ramswaroop/arrays/SelectionSort.java rename to src/me/ramswaroop/arrays/sorting/SelectionSort.java index b2084fc7..3944d945 100644 --- a/src/me/ramswaroop/arrays/SelectionSort.java +++ b/src/me/ramswaroop/arrays/sorting/SelectionSort.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.arrays.sorting; import java.util.Arrays; From 9f67953155e4284ca2db0ac2d951889e026b3b1c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 2 Sep 2015 23:54:06 +0530 Subject: [PATCH 276/417] solution done --- src/me/ramswaroop/arrays/MaxIndexDiff.java | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MaxIndexDiff.java diff --git a/src/me/ramswaroop/arrays/MaxIndexDiff.java b/src/me/ramswaroop/arrays/MaxIndexDiff.java new file mode 100644 index 00000000..9c2a476f --- /dev/null +++ b/src/me/ramswaroop/arrays/MaxIndexDiff.java @@ -0,0 +1,48 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/1/15 + * @time: 10:21 PM + */ +public class MaxIndexDiff { + + /** + * @param a + * @return + */ + public static int maxDiff(int[] a) { + int maxDiff = -1; + int[] leftMin = new int[a.length], rightMax = new int[a.length]; + + leftMin[0] = a[0]; + for (int i = 1; i < a.length; i++) { + leftMin[i] = Math.min(a[i], leftMin[i - 1]); + } + + rightMax[a.length - 1] = a[a.length - 1]; + for (int i = a.length - 2; i >= 0; i--) { + rightMax[i] = Math.max(a[i], rightMax[i + 1]); + } + + for (int i = 0, j = 0; i < a.length && j < a.length; ) { + if (rightMax[j] > leftMin[i]) { + maxDiff = Math.max(maxDiff, j - i); + j++; + } else { + i++; + } + } + return maxDiff; + } + + public static void main(String a[]) { + System.out.println(maxDiff(new int[]{34, 8, 10, 3, 2, 80, 30, 33, 1})); + System.out.println(maxDiff(new int[]{9, 2, 3, 4, 5, 6, 7, 8, 18, 0})); + System.out.println(maxDiff(new int[]{1, 2, 3, 4, 5, 6})); + System.out.println(maxDiff(new int[]{6, 5, 4, 3, 2, 1})); + System.out.println(maxDiff(new int[]{10, 11, 12, 13, 14, 6, 9, 7, 5, 3})); + } +} From 919b8cf615d06e9880d9c1df01c52794c8e0004a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 3 Sep 2015 10:58:53 +0530 Subject: [PATCH 277/417] comments added --- src/me/ramswaroop/arrays/MaxIndexDiff.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/me/ramswaroop/arrays/MaxIndexDiff.java b/src/me/ramswaroop/arrays/MaxIndexDiff.java index 9c2a476f..03c7ea5d 100644 --- a/src/me/ramswaroop/arrays/MaxIndexDiff.java +++ b/src/me/ramswaroop/arrays/MaxIndexDiff.java @@ -10,6 +10,8 @@ public class MaxIndexDiff { /** + * Given an array arr[], find the maximum j – i such that arr[j] > arr[i]. + * * @param a * @return */ @@ -17,16 +19,25 @@ public static int maxDiff(int[] a) { int maxDiff = -1; int[] leftMin = new int[a.length], rightMax = new int[a.length]; + /** + * leftMin[i] holds the smallest element on left side of arr[i] including arr[i]. + * In other words, leftMin[i] stores the minimum value from (arr[0], arr[1], ... arr[i]). + */ leftMin[0] = a[0]; for (int i = 1; i < a.length; i++) { leftMin[i] = Math.min(a[i], leftMin[i - 1]); } + /** + * rightMax[i] holds the greatest element on right side of arr[i] including arr[i]. + * In other words, rightMax[i] stores the maximum value from (arr[i], arr[i+1], ..arr[n-1]) + */ rightMax[a.length - 1] = a[a.length - 1]; for (int i = a.length - 2; i >= 0; i--) { rightMax[i] = Math.max(a[i], rightMax[i + 1]); } + // traverse both arrays from left to right to find maximum j - i for (int i = 0, j = 0; i < a.length && j < a.length; ) { if (rightMax[j] > leftMin[i]) { maxDiff = Math.max(maxDiff, j - i); From 93c459f866fbe7f4474f86585233b7a14f0e1d29 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 3 Sep 2015 21:15:24 +0530 Subject: [PATCH 278/417] code refactoring --- .../ramswaroop/arrays/KthLargestElement.java | 8 +++- .../ramswaroop/arrays/sorting/HeapSort.java | 40 ++++++++++++++++++- src/me/ramswaroop/common/MaxHeap.java | 25 ++++-------- src/me/ramswaroop/common/MinHeap.java | 19 ++------- 4 files changed, 55 insertions(+), 37 deletions(-) diff --git a/src/me/ramswaroop/arrays/KthLargestElement.java b/src/me/ramswaroop/arrays/KthLargestElement.java index d15a89fa..fd1d5d4a 100644 --- a/src/me/ramswaroop/arrays/KthLargestElement.java +++ b/src/me/ramswaroop/arrays/KthLargestElement.java @@ -44,7 +44,7 @@ public static int getKthLargestElement(int[] a, int k) { MaxHeap.buildMaxHeap(a); if (k == 1) break; - MaxHeap.swap(a, 0, a.length - 1); + swap(a, 0, a.length - 1); a = Arrays.copyOfRange(a, 0, a.length - 1); k--; } @@ -52,6 +52,12 @@ public static int getKthLargestElement(int[] a, int k) { return a[0]; } + private static void swap(int[] a, int firstIndex, int secondIndex) { + a[firstIndex] = a[firstIndex] + a[secondIndex]; + a[secondIndex] = a[firstIndex] - a[secondIndex]; + a[firstIndex] = a[firstIndex] - a[secondIndex]; + } + public static void main(String a[]) { int[] ar = new int[]{2, 4, 5, 7, 1, 8, 9}; System.out.println(Arrays.toString(ar)); diff --git a/src/me/ramswaroop/arrays/sorting/HeapSort.java b/src/me/ramswaroop/arrays/sorting/HeapSort.java index 5ada67b2..d560ff0e 100644 --- a/src/me/ramswaroop/arrays/sorting/HeapSort.java +++ b/src/me/ramswaroop/arrays/sorting/HeapSort.java @@ -24,11 +24,47 @@ public static void heapSort(int[] a) { MaxHeap.buildMaxHeap(a); for (int i = a.length - 1; i > 0; i--) { - MaxHeap.swap(a, 0, i); - MaxHeap.maxHeapify(a, 0, i); + swap(a, 0, i); + maxHeapify(a, 0, i); } } + /** + * Makes the array {@param a} satisfy the max heap property starting from + * {@param index} till {@param end} position in array. + *

+ * See this {@link MaxHeap#maxHeapify} for a basic version of maxHeapify. + *

+ * Time complexity: O(log n). + * + * @param a + * @param index + * @param end + */ + private static void maxHeapify(int[] a, int index, int end) { + int largest = index; + int leftIndex = 2 * index + 1; + int rightIndex = 2 * index + 2; + + if (leftIndex < end && a[index] < a[leftIndex]) { + largest = leftIndex; + } + if (rightIndex < end && a[largest] < a[rightIndex]) { + largest = rightIndex; + } + + if (largest != index) { + swap(a, index, largest); + maxHeapify(a, largest, end); + } + } + + private static void swap(int[] a, int firstIndex, int secondIndex) { + a[firstIndex] = a[firstIndex] + a[secondIndex]; + a[secondIndex] = a[firstIndex] - a[secondIndex]; + a[firstIndex] = a[firstIndex] - a[secondIndex]; + } + public static void main(String a[]) { int[] ar = new int[]{2, 5, 1, 7, 9, 4}; System.out.println(Arrays.toString(ar)); diff --git a/src/me/ramswaroop/common/MaxHeap.java b/src/me/ramswaroop/common/MaxHeap.java index 0153c5fa..fb7a03c3 100644 --- a/src/me/ramswaroop/common/MaxHeap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -29,40 +29,29 @@ public class MaxHeap { * Makes the array {@param a} satisfy the max heap property starting from * {@param index} till the end of array. *

- * Time complexity: O(log n). - * - * @param a - * @param index - */ - public static void maxHeapify(int[] a, int index) { - maxHeapify(a, index, a.length); - } - - /** - * Makes the array {@param a} satisfy the max heap property starting from - * {@param index} till {@param l} position in array. + * See {@link me.ramswaroop.arrays.sorting.HeapSort#maxHeapify} for a modified + * version of maxHeapify. *

* Time complexity: O(log n). * * @param a * @param index - * @param l */ - public static void maxHeapify(int[] a, int index, int l) { + public static void maxHeapify(int[] a, int index) { int largest = index; int leftIndex = 2 * index + 1; int rightIndex = 2 * index + 2; - if (leftIndex < l && a[index] < a[leftIndex]) { + if (leftIndex < a.length && a[index] < a[leftIndex]) { largest = leftIndex; } - if (rightIndex < l && a[largest] < a[rightIndex]) { + if (rightIndex < a.length && a[largest] < a[rightIndex]) { largest = rightIndex; } if (largest != index) { swap(a, index, largest); - maxHeapify(a, largest, l); + maxHeapify(a, largest); } } @@ -79,7 +68,7 @@ public static void buildMaxHeap(int[] a) { } } - public static void swap(int[] a, int firstIndex, int secondIndex) { + private static void swap(int[] a, int firstIndex, int secondIndex) { a[firstIndex] = a[firstIndex] + a[secondIndex]; a[secondIndex] = a[firstIndex] - a[secondIndex]; a[firstIndex] = a[firstIndex] - a[secondIndex]; diff --git a/src/me/ramswaroop/common/MinHeap.java b/src/me/ramswaroop/common/MinHeap.java index 9ef4f8a1..f4aebba1 100644 --- a/src/me/ramswaroop/common/MinHeap.java +++ b/src/me/ramswaroop/common/MinHeap.java @@ -35,33 +35,20 @@ public class MinHeap { * @param index */ public static void minHeapify(int[] a, int index) { - minHeapify(a, index, a.length); - } - - /** - * Makes the array {@param a} satisfy the min heap property starting from - * {@param index} till {@param l} position in array. - *

- * Time complexity: O(log n). - * - * @param a - * @param index - */ - public static void minHeapify(int[] a, int index, int l) { int smallest = index; int leftIndex = 2 * index + 1; int rightIndex = 2 * index + 2; - if (leftIndex < l && a[index] > a[leftIndex]) { + if (leftIndex < a.length && a[index] > a[leftIndex]) { smallest = leftIndex; } - if (rightIndex < l && a[smallest] > a[rightIndex]) { + if (rightIndex < a.length && a[smallest] > a[rightIndex]) { smallest = rightIndex; } if (smallest != index) { swap(a, index, smallest); - minHeapify(a, smallest, l); + minHeapify(a, smallest); } } From 10a082ee1bd98c4d03f42307a0ef18193d1e08c5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 3 Sep 2015 23:30:03 +0530 Subject: [PATCH 279/417] done (naive approach) --- .../ramswaroop/arrays/MaxInAllSubArrays.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MaxInAllSubArrays.java diff --git a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java new file mode 100644 index 00000000..4e89f394 --- /dev/null +++ b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java @@ -0,0 +1,46 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.common.MaxHeap; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/3/15 + * @time: 9:21 PM + */ +public class MaxInAllSubArrays { + + /** + * Finds the maximum element in each and every sub-array + * in {@param a} of size {@param k}. + *

+ * Time complexity: O(n^2) + * + * @param a + * @param k + */ + public static int[] maxInAllSubArraysOfSizeKNaive(int[] a, int k) { + int[] maxElements = new int[a.length - k + 1]; + int[] kElements; + + for (int i = 0; i <= a.length - k; i++) { + kElements = Arrays.copyOfRange(a, i, i + k); + /** + * maxHeapify() can't be used because to call maxHeapify() on i, left(i) and right (i) should + * already satisfy the max heap property which isn't true in this case. + */ + MaxHeap.buildMaxHeap(kElements); + maxElements[i] = kElements[0]; + } + + return maxElements; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(maxInAllSubArraysOfSizeKNaive(new int[]{1, 2, 3, 1, 4, 5, 2, 3, 6}, 3))); + System.out.println(Arrays.toString(maxInAllSubArraysOfSizeKNaive(new int[]{8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, 4))); + } +} From 79d27aa384f83b08de14fb4cd1c486a35a04c363 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 4 Sep 2015 23:11:45 +0530 Subject: [PATCH 280/417] minor fix --- src/me/ramswaroop/arrays/MaxInAllSubArrays.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java index 4e89f394..333296bd 100644 --- a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java +++ b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java @@ -17,7 +17,7 @@ public class MaxInAllSubArrays { * Finds the maximum element in each and every sub-array * in {@param a} of size {@param k}. *

- * Time complexity: O(n^2) + * Time complexity: O(n*k), or more precisely O((n-k) * k) * * @param a * @param k From 66e5dc15016e010adf2677cde900077cae76ef91 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 4 Sep 2015 23:43:47 +0530 Subject: [PATCH 281/417] done --- src/me/ramswaroop/arrays/SubsetOfArray.java | 44 +++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SubsetOfArray.java diff --git a/src/me/ramswaroop/arrays/SubsetOfArray.java b/src/me/ramswaroop/arrays/SubsetOfArray.java new file mode 100644 index 00000000..4374eb88 --- /dev/null +++ b/src/me/ramswaroop/arrays/SubsetOfArray.java @@ -0,0 +1,44 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.arrays.sorting.QuickSort; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/4/15 + * @time: 11:28 PM + */ +public class SubsetOfArray { + + public static boolean isSubsetOfArray(int[] a, int[] b) { + + QuickSort.quickSort(a); + QuickSort.quickSort(b); + + int i, j; + for (i = 0, j = 0; i < a.length && j < b.length; ) { + if (a[i] > b[j]) { + return false; + } else if (a[i] == b[j]) { + i++; + j++; + } else { + i++; + } + } + + if (i < b.length) { + return false; + } else { + return true; + } + } + + public static void main(String a[]) { + System.out.println(isSubsetOfArray(new int[]{11, 1, 13, 21, 3, 7}, new int[]{11, 3, 7, 1})); + System.out.println(isSubsetOfArray(new int[]{1, 2, 2, 3, 4, 5, 6}, new int[]{1, 2, 4})); + System.out.println(isSubsetOfArray(new int[]{1, 2, 2, 3, 4, 5, 6}, new int[]{1, 2, 2, 4})); + System.out.println(isSubsetOfArray(new int[]{1, 4, 2}, new int[]{1, 4, 4, 2})); + } +} From 1b4bf8eb324ac2314caa5d9922b95ddacb4d21fe Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 5 Sep 2015 13:47:45 +0530 Subject: [PATCH 282/417] comments added --- src/me/ramswaroop/arrays/SubsetOfArray.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/me/ramswaroop/arrays/SubsetOfArray.java b/src/me/ramswaroop/arrays/SubsetOfArray.java index 4374eb88..7f19f84b 100644 --- a/src/me/ramswaroop/arrays/SubsetOfArray.java +++ b/src/me/ramswaroop/arrays/SubsetOfArray.java @@ -11,6 +11,19 @@ */ public class SubsetOfArray { + /** + * Determines if array {@param b} is a subset of array {@param a}. + *

+ * Explanation: The below method uses sorting + merge method of merge sort. Time + * complexity is O(mlogm + nlogn) where m and n are lengths of array a and b resp. + * You could also have used sorting + binary search but this fails when superset + * array has repeating elements for example, a={1,4,4,2} and b={1,4,2}. Time + * complexity would be O(mlogm + nlogm). + * + * @param a + * @param b + * @return + */ public static boolean isSubsetOfArray(int[] a, int[] b) { QuickSort.quickSort(a); From 8c69ee7d3143fbc69fb69a0a1c3da8516e70d16b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 5 Sep 2015 17:38:59 +0530 Subject: [PATCH 283/417] deque approach added --- .../ramswaroop/arrays/MaxInAllSubArrays.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java index 333296bd..c3ca1dd7 100644 --- a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java +++ b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java @@ -2,6 +2,7 @@ import me.ramswaroop.common.MaxHeap; +import java.util.ArrayDeque; import java.util.Arrays; /** @@ -14,6 +15,8 @@ public class MaxInAllSubArrays { /** + * Naive approach. + *

* Finds the maximum element in each and every sub-array * in {@param a} of size {@param k}. *

@@ -39,8 +42,60 @@ public static int[] maxInAllSubArraysOfSizeKNaive(int[] a, int k) { return maxElements; } + /** + * Finds the maximum element in each and every sub-array + * in {@param a} of size {@param k}. + * + * Time complexity: O(n) + * Auxiliary Space: O(k) + * + * @param a + * @param k + * @return + */ + public static int[] maxInAllSubArraysOfSizeK(int[] a, int k) { + int i, j = 0; + int[] result = new int[a.length - k + 1]; + /** + * Create a Double Ended Queue, Qi that will store indexes of array elements + * The queue will store indexes of useful elements in every window and it will + * maintain decreasing order of values from front to rear in Qi, i.e, + * arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order. + */ + ArrayDeque deque = new ArrayDeque<>(); + + for (i = 0; i < k; i++) { + // remove smaller elements on left side of current element + while (!deque.isEmpty() && a[i] > a[deque.peekLast()]) { + deque.removeLast(); + } + deque.addLast(i); + } + + for (; i < a.length; i++) { + result[j++] = a[deque.peekFirst()]; + + // remove elements that are outside window k + while (!deque.isEmpty() && deque.peekFirst() <= i - k) { + deque.removeFirst(); + } + // remove smaller elements on left side of current element + while (!deque.isEmpty() && a[i] > a[deque.peekLast()]) { + deque.removeLast(); + } + deque.addLast(i); + } + + // for max in last k elements + result[j] = a[deque.peekFirst()]; + + return result; + } + public static void main(String a[]) { System.out.println(Arrays.toString(maxInAllSubArraysOfSizeKNaive(new int[]{1, 2, 3, 1, 4, 5, 2, 3, 6}, 3))); System.out.println(Arrays.toString(maxInAllSubArraysOfSizeKNaive(new int[]{8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, 4))); + System.out.println(Arrays.toString(maxInAllSubArraysOfSizeK(new int[]{1, 2, 3, 1, 4, 5, 2, 3, 6}, 3))); + System.out.println(Arrays.toString(maxInAllSubArraysOfSizeK(new int[]{8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, 4))); } } From 2a88e18d0a6ffbd80882da4e1411c0c628e239d3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 6 Sep 2015 23:20:18 +0530 Subject: [PATCH 284/417] code done + unit tested --- .../arrays/MinimumDistanceBetweenTwoNos.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java diff --git a/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java b/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java new file mode 100644 index 00000000..034ccfcc --- /dev/null +++ b/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java @@ -0,0 +1,55 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/6/15 + * @time: 10:53 PM + */ +public class MinimumDistanceBetweenTwoNos { + + /** + * Finds the minimum distance between two no.s {@param x} + * and {@param y} in an unsorted array {@param a} which + * may contain duplicates. + *

+ * Note: Either of the no.s may occur first in the array. + * + * @param a + * @param x + * @param y + * @return + */ + public static int getMinimumDistanceBetweenTwoNos(int[] a, int x, int y) { + int startIndex = -1, endIndex = a.length, minDiff = a.length; + + for (int i = 0; i < a.length; i++) { + // find the 1st occurrence of either of the numbers + if (startIndex == -1 && (a[i] == x || a[i] == y)) { + startIndex = i; // holds the index of the number that occurred first in array + } else if (a[i] == x || a[i] == y) { + // see if it is same as the number that occurred first + if (a[startIndex] == a[i]) { + startIndex = i; + } else { + endIndex = i; + } + } + // if distance is less then update + if (Math.abs(endIndex - startIndex) < minDiff) { + minDiff = Math.abs(endIndex - startIndex); + } + } + + return minDiff; + } + + public static void main(String a[]) { + System.out.println(getMinimumDistanceBetweenTwoNos(new int[]{1, 2}, 1, 2)); + System.out.println(getMinimumDistanceBetweenTwoNos(new int[]{3, 4, 5}, 3, 5)); + System.out.println(getMinimumDistanceBetweenTwoNos(new int[]{3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}, 3, 6)); + System.out.println(getMinimumDistanceBetweenTwoNos(new int[]{3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 1, 2, 4, 3}, 3, 6)); + System.out.println(getMinimumDistanceBetweenTwoNos(new int[]{2, 5, 3, 5, 4, 4, 2, 3}, 3, 2)); + } +} From ba1747a8d521f1f1183d9213407f08dc06980054 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 7 Sep 2015 13:16:23 +0530 Subject: [PATCH 285/417] code done + unit tested --- .../arrays/MissingAndRepeatingElements.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MissingAndRepeatingElements.java diff --git a/src/me/ramswaroop/arrays/MissingAndRepeatingElements.java b/src/me/ramswaroop/arrays/MissingAndRepeatingElements.java new file mode 100644 index 00000000..a5b8a32f --- /dev/null +++ b/src/me/ramswaroop/arrays/MissingAndRepeatingElements.java @@ -0,0 +1,46 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/7/15 + * @time: 10:54 AM + */ +public class MissingAndRepeatingElements { + + /** + * Finds two numbers in an unsorted array of size n with elements in range from + * 1 to n where one number from set {1, 2, …n} is missing and one number occurs + * twice in array. + * + * @param a + * @return an array where 1st element is the repeating element and 2nd is the missing one + */ + public static int[] findMissingAndRepeatingElements(int[] a) { + int[] result = new int[2]; + for (int i = 0; i < a.length; i++) { + // we use indices to mark already encountered numbers + if (a[Math.abs(a[i]) - 1] < 0) { + result[0] = Math.abs(a[i]); // repeating element + } else { + a[Math.abs(a[i]) - 1] = -a[Math.abs(a[i]) - 1]; + } + } + // no. is +ve means its index wasn't encountered + for (int i = 0; i < a.length; i++) { + if (a[i] > 0) { + result[1] = i + 1; // missing element + } + } + return result; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{3, 1, 3}))); + System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 3, 6, 2, 1, 1}))); + System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 4, 6, 2, 5, 1}))); + } +} From f8a35a26c381aa36a0afb3cc6eee7ba72ba8810d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 8 Sep 2015 23:44:10 +0530 Subject: [PATCH 286/417] code done + unit tested --- src/me/ramswaroop/arrays/FixedPoint.java | 41 ++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/me/ramswaroop/arrays/FixedPoint.java diff --git a/src/me/ramswaroop/arrays/FixedPoint.java b/src/me/ramswaroop/arrays/FixedPoint.java new file mode 100644 index 00000000..d893ba92 --- /dev/null +++ b/src/me/ramswaroop/arrays/FixedPoint.java @@ -0,0 +1,41 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/8/15 + * @time: 11:34 PM + */ +public class FixedPoint { + + /** + * Finds the FIXED POINT in an array {@param a} of n distinct integers sorted + * in ascending order. If there is no fixed point it returns -1. + * FIXED POINT in an array is an index i such that arr[i] is equal to i. Note that + * integers in array can be negative. + * + * @param a + * @return + */ + public static int findFixedPoint(int[] a) { + int low = 0, high = a.length - 1, mid; + while (low <= high) { + mid = (low + high) / 2; + if (a[mid] == mid) { + return mid; + } else if (a[mid] > mid) { + high = mid - 1; + } else { + low = mid + 1; + } + } + return -1; + } + + public static void main(String a[]) { + System.out.println(findFixedPoint(new int[]{-10, -5, 0, 3, 7})); + System.out.println(findFixedPoint(new int[]{0, 2, 5, 8, 17})); + System.out.println(findFixedPoint(new int[]{-10, -5, 3, 4, 7, 9})); + } +} From 22274ed5f61e3d8dfaa1f77b088aa0037aadcf37 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 9 Sep 2015 15:13:34 +0530 Subject: [PATCH 287/417] print perimeter done --- src/me/ramswaroop/arrays/MatrixInSpiral.java | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MatrixInSpiral.java diff --git a/src/me/ramswaroop/arrays/MatrixInSpiral.java b/src/me/ramswaroop/arrays/MatrixInSpiral.java new file mode 100644 index 00000000..42c0d7ce --- /dev/null +++ b/src/me/ramswaroop/arrays/MatrixInSpiral.java @@ -0,0 +1,38 @@ +package me.ramswaroop.arrays; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/9/15 + * @time: 2:55 PM + */ +public class MatrixInSpiral { + + public static void printMatrixInSpiral(int[][] a) { + int row = a.length, col = a[0].length; + + //for (int r = 0, c = col - 1; r < row && c >= 0; r++, c--) { + for (int i = 0, j = 0; j < col; j++) { + out.print(a[i][j]); + } + for (int i = 1, j = col - 1; i < row; i++) { + out.print(a[i][j]); + } + for (int i = row - 1, j = col - 2; j >= 0; j--) { + out.print(a[i][j]); + } + for (int i = row - 2, j = 0; i > 0; i--) { + out.print(a[i][j]); + } + //} + } + + public static void main(String a[]) { + printMatrixInSpiral(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}); + out.println(); + printMatrixInSpiral(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}); + } +} From 88d25bbf5e83c0c7cb287c2b29ea0073e87e407f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 9 Sep 2015 15:50:55 +0530 Subject: [PATCH 288/417] print spiral matrix almost done --- src/me/ramswaroop/arrays/MatrixInSpiral.java | 24 +++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/arrays/MatrixInSpiral.java b/src/me/ramswaroop/arrays/MatrixInSpiral.java index 42c0d7ce..41a64171 100644 --- a/src/me/ramswaroop/arrays/MatrixInSpiral.java +++ b/src/me/ramswaroop/arrays/MatrixInSpiral.java @@ -11,23 +11,35 @@ */ public class MatrixInSpiral { + /** + * + * @param a + */ public static void printMatrixInSpiral(int[][] a) { int row = a.length, col = a[0].length; - //for (int r = 0, c = col - 1; r < row && c >= 0; r++, c--) { - for (int i = 0, j = 0; j < col; j++) { + // this loop iterates for the entire matrix + for (int r = row, c = col, x = 0; r >= 0 && c >= 0; r--, c--, x++) { + /** + * Below 4 {@code for} loops print the perimeter of a matrix + */ + // prints the top row + for (int i = x, j = x; i < r && j < c; j++) { out.print(a[i][j]); } - for (int i = 1, j = col - 1; i < row; i++) { + // prints the right most column + for (int i = x + 1, j = c - 1; i < r; i++) { out.print(a[i][j]); } - for (int i = row - 1, j = col - 2; j >= 0; j--) { + // prints the bottom row + for (int i = r - 1, j = c - 2; j >= x; j--) { out.print(a[i][j]); } - for (int i = row - 2, j = 0; i > 0; i--) { + // prints the left most column + for (int i = r - 2, j = x; i > x; i--) { out.print(a[i][j]); } - //} + } } public static void main(String a[]) { From 104fe7c04af44f3f6c9442c316cced356855603b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 9 Sep 2015 16:24:19 +0530 Subject: [PATCH 289/417] code done + unit tested --- src/me/ramswaroop/arrays/MatrixInSpiral.java | 21 ++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/arrays/MatrixInSpiral.java b/src/me/ramswaroop/arrays/MatrixInSpiral.java index 41a64171..69e05cf2 100644 --- a/src/me/ramswaroop/arrays/MatrixInSpiral.java +++ b/src/me/ramswaroop/arrays/MatrixInSpiral.java @@ -12,7 +12,8 @@ public class MatrixInSpiral { /** - * + * Prints a 2D array {@param a} in spiral form (clockwise). + * * @param a */ public static void printMatrixInSpiral(int[][] a) { @@ -25,26 +26,34 @@ public static void printMatrixInSpiral(int[][] a) { */ // prints the top row for (int i = x, j = x; i < r && j < c; j++) { - out.print(a[i][j]); + out.print(a[i][j] + " "); } // prints the right most column for (int i = x + 1, j = c - 1; i < r; i++) { - out.print(a[i][j]); + out.print(a[i][j] + " "); } // prints the bottom row - for (int i = r - 1, j = c - 2; j >= x; j--) { - out.print(a[i][j]); + for (int i = r - 1, j = c - 2; i > x && j >= x; j--) { + out.print(a[i][j] + " "); } // prints the left most column for (int i = r - 2, j = x; i > x; i--) { - out.print(a[i][j]); + out.print(a[i][j] + " "); } } } public static void main(String a[]) { + printMatrixInSpiral(new int[][]{{1}, {2}}); + out.println(); + printMatrixInSpiral(new int[][]{{1, 2}, {3, 4}}); + out.println(); + printMatrixInSpiral(new int[][]{{1, 2, 3}, {4, 5, 6}}); + out.println(); printMatrixInSpiral(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}); out.println(); printMatrixInSpiral(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}); + out.println(); + printMatrixInSpiral(new int[][]{{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}); } } From 6203d59b42d8dab5dde9054fbf0ae356fdb53b42 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 10 Sep 2015 17:11:10 +0530 Subject: [PATCH 290/417] code done + unit tested --- .../dynamicprogramming/FibonacciNumbers.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java diff --git a/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java b/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java new file mode 100644 index 00000000..dac48fb4 --- /dev/null +++ b/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java @@ -0,0 +1,42 @@ +package me.ramswaroop.dynamicprogramming; + +import java.util.Arrays; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/10/15 + * @time: 3:57 PM + */ +public class FibonacciNumbers { + + /** + * Computes first {@param k} fibonacci numbers using + * bottom-up DP approach. + *

+ * Time complexity: O(k) + * + * @param k + */ + public static int[] getFirstKFibonacciNumbers(int k) { + int[] fib = new int[k + 1]; + int i = 1; + while (i <= k) { + if (i == 1 || i == 2) { + fib[i] = 1; + } else { + fib[i] = fib[i - 1] + fib[i - 2]; + } + i++; + } + return fib; + } + + public static void main(String a[]) { + out.println(Arrays.toString(getFirstKFibonacciNumbers(10))); + out.println(Arrays.toString(getFirstKFibonacciNumbers(46))); + } +} From dc488d0e46a06084f7b429a37d4b8dd675d9e64b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 11 Sep 2015 16:44:42 +0530 Subject: [PATCH 291/417] code done + unit tested --- src/me/ramswaroop/arrays/BooleanMatrix.java | 81 +++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/me/ramswaroop/arrays/BooleanMatrix.java diff --git a/src/me/ramswaroop/arrays/BooleanMatrix.java b/src/me/ramswaroop/arrays/BooleanMatrix.java new file mode 100644 index 00000000..7e47012c --- /dev/null +++ b/src/me/ramswaroop/arrays/BooleanMatrix.java @@ -0,0 +1,81 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/11/15 + * @time: 3:28 PM + * @see: http://www.geeksforgeeks.org/a-boolean-matrix-question/ + */ +public class BooleanMatrix { + + /** + * Given a boolean matrix mat[M][N] of size M X N, modify it such that + * if a matrix cell mat[i][j] is 1 (or true) then make all the cells of + * ith row and jth column as 1. + * + * @param a + */ + public static void modifyBooleanMatrix(int[][] a) { + int rowFlag = 0, colFlag = 0; + + // if a[i][j] is 1 then we make a[0][j] 1 and a[i][0] 1 + for (int i = 0; i < a.length; i++) { + for (int j = 0; j < a[0].length; j++) { + if (i == 0 || j == 0) { + if (a[i][0] == 1) { + rowFlag = 1; + } + if (a[0][j] == 1) { + colFlag = 1; + } + } else if (a[i][j] == 1) { + a[0][j] = 1; + a[i][0] = 1; + } + } + } + + // if a[0][j] is 1 or a[i][0] is 1 then a[i][j] is 1 + for (int i = 1; i < a.length; i++) { + for (int j = 1; j < a[0].length; j++) { + if (a[0][j] == 1 || a[i][0] == 1) { + a[i][j] = 1; + } + } + } + + if (rowFlag == 1) { + for (int j = 0; j < a[0].length; j++) { + a[0][j] = 1; + } + } + if (colFlag == 1) { + for (int i = 0; i < a.length; i++) { + a[i][0] = 1; + } + } + } + + private static void print2DMatrix(int[][] a) { + for (int i = 0; i < a.length; i++) { + for (int j = 0; j < a[0].length; j++) { + System.out.print(a[i][j]); + } + System.out.println(); + } + } + + public static void main(String a[]) { + int[][] ar = new int[][]{{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; + print2DMatrix(ar); + modifyBooleanMatrix(ar); + print2DMatrix(ar); + System.out.println("-------"); + ar = new int[][]{{1, 0}, {0, 0}}; + print2DMatrix(ar); + modifyBooleanMatrix(ar); + print2DMatrix(ar); + } +} From 73a1be643d3a9765692ee4b733e55419761d6f35 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 12 Sep 2015 23:04:12 +0530 Subject: [PATCH 292/417] code refactoring --- src/me/ramswaroop/arrays/MatrixInSpiral.java | 2 + .../{practice => misc}/BotTesting.java | 2 +- .../{practice => misc}/DivideByZero.java | 2 +- .../ramswaroop/{practice => misc}/Equals.java | 2 +- .../GenericNonGenericMix.java | 2 +- .../MethodLocalVSInner.java | 2 +- .../{practice => misc}/MethodOverloading.java | 2 +- src/me/ramswaroop/misc/Regex.java | 46 +++++++++++++++++++ .../RightShiftOperator.java | 2 +- .../{practice => misc}/Threads.java | 2 +- .../{practice => misc}/TreeList.java | 2 +- 11 files changed, 57 insertions(+), 9 deletions(-) rename src/me/ramswaroop/{practice => misc}/BotTesting.java (98%) rename src/me/ramswaroop/{practice => misc}/DivideByZero.java (92%) rename src/me/ramswaroop/{practice => misc}/Equals.java (94%) rename src/me/ramswaroop/{practice => misc}/GenericNonGenericMix.java (95%) rename src/me/ramswaroop/{practice => misc}/MethodLocalVSInner.java (95%) rename src/me/ramswaroop/{practice => misc}/MethodOverloading.java (97%) create mode 100644 src/me/ramswaroop/misc/Regex.java rename src/me/ramswaroop/{practice => misc}/RightShiftOperator.java (98%) rename src/me/ramswaroop/{practice => misc}/Threads.java (96%) rename src/me/ramswaroop/{practice => misc}/TreeList.java (99%) diff --git a/src/me/ramswaroop/arrays/MatrixInSpiral.java b/src/me/ramswaroop/arrays/MatrixInSpiral.java index 69e05cf2..da4ce95e 100644 --- a/src/me/ramswaroop/arrays/MatrixInSpiral.java +++ b/src/me/ramswaroop/arrays/MatrixInSpiral.java @@ -55,5 +55,7 @@ public static void main(String a[]) { printMatrixInSpiral(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}); out.println(); printMatrixInSpiral(new int[][]{{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}); + out.println(); + printMatrixInSpiral(new int[][]{{1, 2, 3, 4, 5, 6, 7, 8}, {9, 10, 11, 12, 13, 14, 15, 16}}); } } diff --git a/src/me/ramswaroop/practice/BotTesting.java b/src/me/ramswaroop/misc/BotTesting.java similarity index 98% rename from src/me/ramswaroop/practice/BotTesting.java rename to src/me/ramswaroop/misc/BotTesting.java index 887ce7dc..7fa425c4 100644 --- a/src/me/ramswaroop/practice/BotTesting.java +++ b/src/me/ramswaroop/misc/BotTesting.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/practice/DivideByZero.java b/src/me/ramswaroop/misc/DivideByZero.java similarity index 92% rename from src/me/ramswaroop/practice/DivideByZero.java rename to src/me/ramswaroop/misc/DivideByZero.java index 20f05c02..64778ae5 100644 --- a/src/me/ramswaroop/practice/DivideByZero.java +++ b/src/me/ramswaroop/misc/DivideByZero.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/practice/Equals.java b/src/me/ramswaroop/misc/Equals.java similarity index 94% rename from src/me/ramswaroop/practice/Equals.java rename to src/me/ramswaroop/misc/Equals.java index 82817e03..1f032256 100644 --- a/src/me/ramswaroop/practice/Equals.java +++ b/src/me/ramswaroop/misc/Equals.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/practice/GenericNonGenericMix.java b/src/me/ramswaroop/misc/GenericNonGenericMix.java similarity index 95% rename from src/me/ramswaroop/practice/GenericNonGenericMix.java rename to src/me/ramswaroop/misc/GenericNonGenericMix.java index 406487e6..826cffd7 100644 --- a/src/me/ramswaroop/practice/GenericNonGenericMix.java +++ b/src/me/ramswaroop/misc/GenericNonGenericMix.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; import java.util.ArrayList; import java.util.List; diff --git a/src/me/ramswaroop/practice/MethodLocalVSInner.java b/src/me/ramswaroop/misc/MethodLocalVSInner.java similarity index 95% rename from src/me/ramswaroop/practice/MethodLocalVSInner.java rename to src/me/ramswaroop/misc/MethodLocalVSInner.java index 72617088..7c4a5954 100644 --- a/src/me/ramswaroop/practice/MethodLocalVSInner.java +++ b/src/me/ramswaroop/misc/MethodLocalVSInner.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/practice/MethodOverloading.java b/src/me/ramswaroop/misc/MethodOverloading.java similarity index 97% rename from src/me/ramswaroop/practice/MethodOverloading.java rename to src/me/ramswaroop/misc/MethodOverloading.java index 1ae5d961..83e9c465 100644 --- a/src/me/ramswaroop/practice/MethodOverloading.java +++ b/src/me/ramswaroop/misc/MethodOverloading.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/misc/Regex.java b/src/me/ramswaroop/misc/Regex.java new file mode 100644 index 00000000..285f257a --- /dev/null +++ b/src/me/ramswaroop/misc/Regex.java @@ -0,0 +1,46 @@ +package me.ramswaroop.misc; + +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/12/15 + * @time: 1:49 PM + */ +public class Regex { + + /** + * Validates latitude/longitude in the form (+75, 180) etc. + * + * @param s + * @return + */ + public static String validateLatLong(String s) { + String regex_coords = "^(\\(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?\\))$"; + Pattern compiledPattern2 = Pattern.compile(regex_coords, Pattern.CASE_INSENSITIVE); + Matcher matcher2 = compiledPattern2.matcher(s); + while (matcher2.find()) { + return "Valid"; + } + return "Invalid"; + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + int t = Integer.parseInt(in.nextLine()); + String[] in_ar = new String[t]; + + for (int i = 0; i < t; i++) { + in_ar[i] = in.nextLine(); + } + + for (String i : in_ar) { + System.out.println(validateLatLong(i)); + } + } +} diff --git a/src/me/ramswaroop/practice/RightShiftOperator.java b/src/me/ramswaroop/misc/RightShiftOperator.java similarity index 98% rename from src/me/ramswaroop/practice/RightShiftOperator.java rename to src/me/ramswaroop/misc/RightShiftOperator.java index 08d72ab3..c5c52b9e 100644 --- a/src/me/ramswaroop/practice/RightShiftOperator.java +++ b/src/me/ramswaroop/misc/RightShiftOperator.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/practice/Threads.java b/src/me/ramswaroop/misc/Threads.java similarity index 96% rename from src/me/ramswaroop/practice/Threads.java rename to src/me/ramswaroop/misc/Threads.java index ec54b347..bc10a8b6 100644 --- a/src/me/ramswaroop/practice/Threads.java +++ b/src/me/ramswaroop/misc/Threads.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/practice/TreeList.java b/src/me/ramswaroop/misc/TreeList.java similarity index 99% rename from src/me/ramswaroop/practice/TreeList.java rename to src/me/ramswaroop/misc/TreeList.java index eb093d53..978bc2a2 100644 --- a/src/me/ramswaroop/practice/TreeList.java +++ b/src/me/ramswaroop/misc/TreeList.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; /** * Created by IntelliJ IDEA. From 4de1b53c3a2b4e0ed1a6ff1bfdc951064eeb22d1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 12 Sep 2015 23:50:05 +0530 Subject: [PATCH 293/417] code but not tested --- src/me/ramswaroop/arrays/MedianOfStream.java | 316 +++++++++++++++++++ 1 file changed, 316 insertions(+) create mode 100644 src/me/ramswaroop/arrays/MedianOfStream.java diff --git a/src/me/ramswaroop/arrays/MedianOfStream.java b/src/me/ramswaroop/arrays/MedianOfStream.java new file mode 100644 index 00000000..d1fe8b2c --- /dev/null +++ b/src/me/ramswaroop/arrays/MedianOfStream.java @@ -0,0 +1,316 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; +import java.util.NoSuchElementException; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/12/15 + * @time: 11:19 PM + */ +public class MedianOfStream { + + public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap minHeap) { + switch (compare(maxHeap.getSize(), minHeap.getSize())) { + case 0: + if (elem < med) { + maxHeap.insert(elem); + med = maxHeap.findMax(); + } else { + minHeap.insert(elem); + med = minHeap.findMin(); + } + break; + case 1: + if (elem < med) { + minHeap.insert(maxHeap.deleteMax()); + maxHeap.insert(elem); + } else { + minHeap.insert(elem); + } + med = (maxHeap.findMax() + minHeap.findMin())/2; + break; + case -1: + if (elem < med) { + maxHeap.insert(elem); + } else { + maxHeap.insert(minHeap.deleteMin()); + minHeap.insert(elem); + } + med = (maxHeap.findMax() + minHeap.findMin())/2; + break; + } + return med; + } + + static void printMedianOfStream(int[] a) { + int m = 0; + MaxHeap maxHeap = new MaxHeap(128); + MinHeap minHeap = new MinHeap(128); + for (int i = 0; i < a.length; i++) { + m = getMedianOfStream(m, a[i], maxHeap, minHeap); + } + System.out.println(m); + } + + static int compare(int a, int b) { + if (a == b) { + return 0; + } else { + return a < b ? -1 : 1; + } + } + + public static void main(String a[]) { + printMedianOfStream(new int[]{5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4}); + } +} + +class MinHeap { + /** + * The number of children each node has * + */ + private static final int d = 2; + private int size; + private int[] heap; + + /** + * Constructor * + */ + public MinHeap(int capacity) { + size = 0; + heap = new int[capacity + 1]; + Arrays.fill(heap, -1); + } + + /** + * Function to check if heap is empty * + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Check if heap is full * + */ + public boolean isFull() { + return size == heap.length; + } + + /** + * Clear heap + */ + public void makeEmpty() { + size = 0; + } + + /** + * Function to get index parent of i * + */ + private int parent(int i) { + return (i - 1) / d; + } + + /** + * Function to get index of k th child of i * + */ + private int kthChild(int i, int k) { + return d * i + k; + } + + /** + * Function to insert element + */ + public void insert(int x) { + if (isFull()) + throw new NoSuchElementException("Overflow Exception"); + /** Percolate up **/ + heap[size++] = x; + heapifyUp(size - 1); + } + + /** + * Function to find least element * + */ + public int findMin() { + if (isEmpty()) + throw new NoSuchElementException("Underflow Exception"); + return heap[0]; + } + + /** + * Function to delete min element * + */ + public int deleteMin() { + int keyItem = heap[0]; + delete(0); + return keyItem; + } + + /** + * Function to delete element at an index * + */ + public int delete(int ind) { + if (isEmpty()) + throw new NoSuchElementException("Underflow Exception"); + int keyItem = heap[ind]; + heap[ind] = heap[size - 1]; + size--; + heapifyDown(ind); + return keyItem; + } + + /** + * Function heapifyUp * + */ + private void heapifyUp(int childInd) { + int tmp = heap[childInd]; + while (childInd > 0 && tmp < heap[parent(childInd)]) { + heap[childInd] = heap[parent(childInd)]; + childInd = parent(childInd); + } + heap[childInd] = tmp; + } + + /** + * Function heapifyDown * + */ + private void heapifyDown(int ind) { + int child; + int tmp = heap[ind]; + while (kthChild(ind, 1) < size) { + child = minChild(ind); + if (heap[child] < tmp) + heap[ind] = heap[child]; + else + break; + ind = child; + } + heap[ind] = tmp; + } + + /** + * Function to get smallest child * + */ + private int minChild(int ind) { + int bestChild = kthChild(ind, 1); + int k = 2; + int pos = kthChild(ind, k); + while ((k <= d) && (pos < size)) { + if (heap[pos] < heap[bestChild]) + bestChild = pos; + pos = kthChild(ind, k++); + } + return bestChild; + } + + public int getSize() { + return size; + } + + /** + * Function to print heap * + */ + public void printHeap() { + System.out.print("\nHeap = "); + for (int i = 0; i < size; i++) + System.out.print(heap[i] + " "); + System.out.println(); + } +} + +class MaxHeap { + private int[] heap; + private int size; + private int maxsize; + + private static final int FRONT = 1; + + public MaxHeap(int maxsize) { + this.maxsize = maxsize; + this.size = 0; + heap = new int[this.maxsize + 1]; + heap[0] = Integer.MAX_VALUE; + } + + public int findMax() { + return heap[0]; + } + + public int parent(int pos) { + return pos / 2; + } + + private int leftChild(int pos) { + return (2 * pos); + } + + private int rightChild(int pos) { + return (2 * pos) + 1; + } + + private boolean isLeaf(int pos) { + if (pos >= (size / 2) && pos <= size) { + return true; + } + return false; + } + + private void swap(int fpos, int spos) { + int tmp; + tmp = heap[fpos]; + heap[fpos] = heap[spos]; + heap[spos] = tmp; + } + + private void maxHeapify(int pos) { + if (!isLeaf(pos)) { + if (heap[pos] < heap[leftChild(pos)] || heap[pos] < heap[rightChild(pos)]) { + if (heap[leftChild(pos)] > heap[rightChild(pos)]) { + swap(pos, leftChild(pos)); + maxHeapify(leftChild(pos)); + } else { + swap(pos, rightChild(pos)); + maxHeapify(rightChild(pos)); + } + } + } + } + + public void insert(int element) { + heap[++size] = element; + int current = size; + + while (heap[current] > heap[parent(current)]) { + swap(current, parent(current)); + current = parent(current); + } + } + + public int getSize() { + return size; + } + + public void print() { + for (int i = 1; i <= size / 2; i++) { + System.out.print(" PARENT : " + heap[i] + " LEFT CHILD : " + heap[2 * i] + + " RIGHT CHILD :" + heap[2 * i + 1]); + System.out.println(); + } + } + + public void maxHeap() { + for (int pos = (size / 2); pos >= 1; pos--) { + maxHeapify(pos); + } + } + + public int deleteMax() { + int popped = heap[FRONT]; + heap[FRONT] = heap[size--]; + maxHeapify(FRONT); + return popped; + } +} From 91c92ac3bccbd6705e64f742da0ff2b5a50c5d86 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 13 Sep 2015 00:00:05 +0530 Subject: [PATCH 294/417] coded + tested --- src/me/ramswaroop/arrays/MedianOfStream.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/arrays/MedianOfStream.java b/src/me/ramswaroop/arrays/MedianOfStream.java index d1fe8b2c..2f0367dd 100644 --- a/src/me/ramswaroop/arrays/MedianOfStream.java +++ b/src/me/ramswaroop/arrays/MedianOfStream.java @@ -13,6 +13,7 @@ public class MedianOfStream { public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap minHeap) { + switch (compare(maxHeap.getSize(), minHeap.getSize())) { case 0: if (elem < med) { @@ -30,7 +31,7 @@ public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap } else { minHeap.insert(elem); } - med = (maxHeap.findMax() + minHeap.findMin())/2; + med = (maxHeap.findMax() + minHeap.findMin()) / 2; break; case -1: if (elem < med) { @@ -39,7 +40,7 @@ public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap maxHeap.insert(minHeap.deleteMin()); minHeap.insert(elem); } - med = (maxHeap.findMax() + minHeap.findMin())/2; + med = (maxHeap.findMax() + minHeap.findMin()) / 2; break; } return med; @@ -47,8 +48,8 @@ public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap static void printMedianOfStream(int[] a) { int m = 0; - MaxHeap maxHeap = new MaxHeap(128); - MinHeap minHeap = new MinHeap(128); + MaxHeap maxHeap = new MaxHeap(12); + MinHeap minHeap = new MinHeap(12); for (int i = 0; i < a.length; i++) { m = getMedianOfStream(m, a[i], maxHeap, minHeap); } @@ -135,8 +136,7 @@ public void insert(int x) { * Function to find least element * */ public int findMin() { - if (isEmpty()) - throw new NoSuchElementException("Underflow Exception"); + if (size == 0) return -1; return heap[0]; } @@ -236,7 +236,8 @@ public MaxHeap(int maxsize) { } public int findMax() { - return heap[0]; + if (size == 0) return -1; + return heap[FRONT]; } public int parent(int pos) { From 348ccec2a85f08f0b2f417f95cec312afb2b3654 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 13 Sep 2015 16:59:47 +0530 Subject: [PATCH 295/417] MaxHeap and MinHeap code changes + added new methods --- .../ramswaroop/arrays/KLargestElements.java | 11 +- .../ramswaroop/arrays/KthLargestElement.java | 10 +- .../ramswaroop/arrays/MaxInAllSubArrays.java | 7 +- src/me/ramswaroop/arrays/MedianOfStream.java | 274 ++---------------- .../ramswaroop/arrays/sorting/HeapSort.java | 13 +- src/me/ramswaroop/common/MaxHeap.java | 101 +++++-- src/me/ramswaroop/common/MinHeap.java | 101 +++++-- 7 files changed, 211 insertions(+), 306 deletions(-) diff --git a/src/me/ramswaroop/arrays/KLargestElements.java b/src/me/ramswaroop/arrays/KLargestElements.java index eef26002..aa173187 100644 --- a/src/me/ramswaroop/arrays/KLargestElements.java +++ b/src/me/ramswaroop/arrays/KLargestElements.java @@ -36,16 +36,17 @@ public static int[] getKLargestElements(int[] a, int k) { int[] kElements = Arrays.copyOfRange(a, 0, k); - MinHeap.buildMinHeap(kElements); + MinHeap minHeap = new MinHeap(kElements); + minHeap.buildMinHeap(); for (int i = k; i < a.length; i++) { - if (a[i] > kElements[0]) { - kElements[0] = a[i]; - MinHeap.buildMinHeap(kElements); + if (a[i] > minHeap.findMin()) { + minHeap.extractMin(); + minHeap.insert(a[i]); } } - return kElements; + return minHeap.getHeap(); } public static void main(String a[]) { diff --git a/src/me/ramswaroop/arrays/KthLargestElement.java b/src/me/ramswaroop/arrays/KthLargestElement.java index fd1d5d4a..62c771b2 100644 --- a/src/me/ramswaroop/arrays/KthLargestElement.java +++ b/src/me/ramswaroop/arrays/KthLargestElement.java @@ -40,16 +40,16 @@ public static int getKthLargestElementNaive(int[] a, int k) { * @return */ public static int getKthLargestElement(int[] a, int k) { + MaxHeap maxHeap = new MaxHeap(a); + maxHeap.buildMaxHeap(); while (true) { - MaxHeap.buildMaxHeap(a); if (k == 1) break; - - swap(a, 0, a.length - 1); - a = Arrays.copyOfRange(a, 0, a.length - 1); + + maxHeap.extractMax(); k--; } - return a[0]; + return maxHeap.findMax(); } private static void swap(int[] a, int firstIndex, int secondIndex) { diff --git a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java index c3ca1dd7..6bfb01da 100644 --- a/src/me/ramswaroop/arrays/MaxInAllSubArrays.java +++ b/src/me/ramswaroop/arrays/MaxInAllSubArrays.java @@ -32,11 +32,12 @@ public static int[] maxInAllSubArraysOfSizeKNaive(int[] a, int k) { for (int i = 0; i <= a.length - k; i++) { kElements = Arrays.copyOfRange(a, i, i + k); /** - * maxHeapify() can't be used because to call maxHeapify() on i, left(i) and right (i) should + * maxHeapify() can't be used because to call maxHeapify() on i because left(i) and right (i) should * already satisfy the max heap property which isn't true in this case. */ - MaxHeap.buildMaxHeap(kElements); - maxElements[i] = kElements[0]; + MaxHeap maxHeap = new MaxHeap(kElements); + maxHeap.buildMaxHeap(); + maxElements[i] = maxHeap.findMax(); } return maxElements; diff --git a/src/me/ramswaroop/arrays/MedianOfStream.java b/src/me/ramswaroop/arrays/MedianOfStream.java index 2f0367dd..f019f36c 100644 --- a/src/me/ramswaroop/arrays/MedianOfStream.java +++ b/src/me/ramswaroop/arrays/MedianOfStream.java @@ -1,7 +1,7 @@ package me.ramswaroop.arrays; -import java.util.Arrays; -import java.util.NoSuchElementException; +import me.ramswaroop.common.MaxHeap; +import me.ramswaroop.common.MinHeap; /** * Created by IntelliJ IDEA. @@ -12,10 +12,17 @@ */ public class MedianOfStream { + /** + * @param med + * @param elem + * @param maxHeap + * @param minHeap + * @return + */ public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap minHeap) { switch (compare(maxHeap.getSize(), minHeap.getSize())) { - case 0: + case 0: // sizes of maxHeap and minHeap are same if (elem < med) { maxHeap.insert(elem); med = maxHeap.findMax(); @@ -24,20 +31,20 @@ public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap med = minHeap.findMin(); } break; - case 1: + case 1: // size of maxHeap greater than minHeap if (elem < med) { - minHeap.insert(maxHeap.deleteMax()); + minHeap.insert(maxHeap.extractMax()); maxHeap.insert(elem); } else { minHeap.insert(elem); } med = (maxHeap.findMax() + minHeap.findMin()) / 2; break; - case -1: + case -1: // size of maxHeap smaller than minHeap if (elem < med) { maxHeap.insert(elem); } else { - maxHeap.insert(minHeap.deleteMin()); + maxHeap.insert(minHeap.extractMin()); minHeap.insert(elem); } med = (maxHeap.findMax() + minHeap.findMin()) / 2; @@ -48,8 +55,10 @@ public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap static void printMedianOfStream(int[] a) { int m = 0; - MaxHeap maxHeap = new MaxHeap(12); - MinHeap minHeap = new MinHeap(12); + MaxHeap maxHeap = new MaxHeap(a); + MinHeap minHeap = new MinHeap(a); + + // calling in a loop so at to resemble a stream for (int i = 0; i < a.length; i++) { m = getMedianOfStream(m, a[i], maxHeap, minHeap); } @@ -68,250 +77,3 @@ public static void main(String a[]) { printMedianOfStream(new int[]{5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4}); } } - -class MinHeap { - /** - * The number of children each node has * - */ - private static final int d = 2; - private int size; - private int[] heap; - - /** - * Constructor * - */ - public MinHeap(int capacity) { - size = 0; - heap = new int[capacity + 1]; - Arrays.fill(heap, -1); - } - - /** - * Function to check if heap is empty * - */ - public boolean isEmpty() { - return size == 0; - } - - /** - * Check if heap is full * - */ - public boolean isFull() { - return size == heap.length; - } - - /** - * Clear heap - */ - public void makeEmpty() { - size = 0; - } - - /** - * Function to get index parent of i * - */ - private int parent(int i) { - return (i - 1) / d; - } - - /** - * Function to get index of k th child of i * - */ - private int kthChild(int i, int k) { - return d * i + k; - } - - /** - * Function to insert element - */ - public void insert(int x) { - if (isFull()) - throw new NoSuchElementException("Overflow Exception"); - /** Percolate up **/ - heap[size++] = x; - heapifyUp(size - 1); - } - - /** - * Function to find least element * - */ - public int findMin() { - if (size == 0) return -1; - return heap[0]; - } - - /** - * Function to delete min element * - */ - public int deleteMin() { - int keyItem = heap[0]; - delete(0); - return keyItem; - } - - /** - * Function to delete element at an index * - */ - public int delete(int ind) { - if (isEmpty()) - throw new NoSuchElementException("Underflow Exception"); - int keyItem = heap[ind]; - heap[ind] = heap[size - 1]; - size--; - heapifyDown(ind); - return keyItem; - } - - /** - * Function heapifyUp * - */ - private void heapifyUp(int childInd) { - int tmp = heap[childInd]; - while (childInd > 0 && tmp < heap[parent(childInd)]) { - heap[childInd] = heap[parent(childInd)]; - childInd = parent(childInd); - } - heap[childInd] = tmp; - } - - /** - * Function heapifyDown * - */ - private void heapifyDown(int ind) { - int child; - int tmp = heap[ind]; - while (kthChild(ind, 1) < size) { - child = minChild(ind); - if (heap[child] < tmp) - heap[ind] = heap[child]; - else - break; - ind = child; - } - heap[ind] = tmp; - } - - /** - * Function to get smallest child * - */ - private int minChild(int ind) { - int bestChild = kthChild(ind, 1); - int k = 2; - int pos = kthChild(ind, k); - while ((k <= d) && (pos < size)) { - if (heap[pos] < heap[bestChild]) - bestChild = pos; - pos = kthChild(ind, k++); - } - return bestChild; - } - - public int getSize() { - return size; - } - - /** - * Function to print heap * - */ - public void printHeap() { - System.out.print("\nHeap = "); - for (int i = 0; i < size; i++) - System.out.print(heap[i] + " "); - System.out.println(); - } -} - -class MaxHeap { - private int[] heap; - private int size; - private int maxsize; - - private static final int FRONT = 1; - - public MaxHeap(int maxsize) { - this.maxsize = maxsize; - this.size = 0; - heap = new int[this.maxsize + 1]; - heap[0] = Integer.MAX_VALUE; - } - - public int findMax() { - if (size == 0) return -1; - return heap[FRONT]; - } - - public int parent(int pos) { - return pos / 2; - } - - private int leftChild(int pos) { - return (2 * pos); - } - - private int rightChild(int pos) { - return (2 * pos) + 1; - } - - private boolean isLeaf(int pos) { - if (pos >= (size / 2) && pos <= size) { - return true; - } - return false; - } - - private void swap(int fpos, int spos) { - int tmp; - tmp = heap[fpos]; - heap[fpos] = heap[spos]; - heap[spos] = tmp; - } - - private void maxHeapify(int pos) { - if (!isLeaf(pos)) { - if (heap[pos] < heap[leftChild(pos)] || heap[pos] < heap[rightChild(pos)]) { - if (heap[leftChild(pos)] > heap[rightChild(pos)]) { - swap(pos, leftChild(pos)); - maxHeapify(leftChild(pos)); - } else { - swap(pos, rightChild(pos)); - maxHeapify(rightChild(pos)); - } - } - } - } - - public void insert(int element) { - heap[++size] = element; - int current = size; - - while (heap[current] > heap[parent(current)]) { - swap(current, parent(current)); - current = parent(current); - } - } - - public int getSize() { - return size; - } - - public void print() { - for (int i = 1; i <= size / 2; i++) { - System.out.print(" PARENT : " + heap[i] + " LEFT CHILD : " + heap[2 * i] - + " RIGHT CHILD :" + heap[2 * i + 1]); - System.out.println(); - } - } - - public void maxHeap() { - for (int pos = (size / 2); pos >= 1; pos--) { - maxHeapify(pos); - } - } - - public int deleteMax() { - int popped = heap[FRONT]; - heap[FRONT] = heap[size--]; - maxHeapify(FRONT); - return popped; - } -} diff --git a/src/me/ramswaroop/arrays/sorting/HeapSort.java b/src/me/ramswaroop/arrays/sorting/HeapSort.java index d560ff0e..b16f5b45 100644 --- a/src/me/ramswaroop/arrays/sorting/HeapSort.java +++ b/src/me/ramswaroop/arrays/sorting/HeapSort.java @@ -21,7 +21,7 @@ public class HeapSort { * @param a */ public static void heapSort(int[] a) { - MaxHeap.buildMaxHeap(a); + buildMaxHeap(a); for (int i = a.length - 1; i > 0; i--) { swap(a, 0, i); @@ -59,6 +59,17 @@ private static void maxHeapify(int[] a, int index, int end) { } } + /** + * Converts array {@param a} in to a max heap. + *

+ * Time complexity: O(n) and is not O(n log n). + */ + private static void buildMaxHeap(int[] a) { + for (int i = a.length / 2 - 1; i >= 0; i--) { + maxHeapify(a, i, a.length); + } + } + private static void swap(int[] a, int firstIndex, int secondIndex) { a[firstIndex] = a[firstIndex] + a[secondIndex]; a[secondIndex] = a[firstIndex] - a[secondIndex]; diff --git a/src/me/ramswaroop/common/MaxHeap.java b/src/me/ramswaroop/common/MaxHeap.java index fb7a03c3..ae05be47 100644 --- a/src/me/ramswaroop/common/MaxHeap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -25,6 +25,14 @@ */ public class MaxHeap { + int[] heap; + int size; + + public MaxHeap(int[] heap) { + this.size = heap.length; + this.heap = Arrays.copyOf(heap, size); + } + /** * Makes the array {@param a} satisfy the max heap property starting from * {@param index} till the end of array. @@ -34,24 +42,23 @@ public class MaxHeap { *

* Time complexity: O(log n). * - * @param a * @param index */ - public static void maxHeapify(int[] a, int index) { + public void maxHeapify(int index) { int largest = index; int leftIndex = 2 * index + 1; int rightIndex = 2 * index + 2; - if (leftIndex < a.length && a[index] < a[leftIndex]) { + if (leftIndex < size && heap[index] < heap[leftIndex]) { largest = leftIndex; } - if (rightIndex < a.length && a[largest] < a[rightIndex]) { + if (rightIndex < size && heap[largest] < heap[rightIndex]) { largest = rightIndex; } if (largest != index) { - swap(a, index, largest); - maxHeapify(a, largest); + swap(index, largest); + maxHeapify(largest); } } @@ -59,26 +66,84 @@ public static void maxHeapify(int[] a, int index) { * Converts array {@param a} in to a max heap. *

* Time complexity: O(n) and is not O(n log n). - * - * @param a */ - public static void buildMaxHeap(int[] a) { - for (int i = a.length / 2 - 1; i >= 0; i--) { - maxHeapify(a, i); + public void buildMaxHeap() { + for (int i = size / 2 - 1; i >= 0; i--) { + maxHeapify(i); + } + } + + public void insert(int elem) { + heap = Arrays.copyOf(heap, size + 1); + int i = size; + int parentIndex = (int) Math.ceil((i / 2) - 1); + while (i > 0 && elem > heap[parentIndex]) { + heap[i] = heap[parentIndex]; + i = parentIndex; + parentIndex = (int) Math.ceil((parentIndex / 2) - 1); + } + heap[i] = elem; + size++; + } + + public int findMax() { + if (size == 0) { + return -1; + } else { + return heap[0]; + } + } + + public int extractMax() { + if (size == 0) return -1; + + int min = heap[0]; + heap[0] = heap[size - 1]; + size--; + maxHeapify(0); + return min; + } + + public int getSize() { + return size; + } + + public int[] getHeap() { + return heap; + } + + public void printHeap() { + if (heap == null) + System.out.print("null"); + int iMax = size - 1, i; + if (iMax == -1) + System.out.print("[]"); + + StringBuilder b = new StringBuilder(); + b.append('['); + for (i = 0; i < iMax; i++) { + b.append(heap[i]); + b.append(", "); } + System.out.println(b.append(heap[i]).append(']').toString()); } - private static void swap(int[] a, int firstIndex, int secondIndex) { - a[firstIndex] = a[firstIndex] + a[secondIndex]; - a[secondIndex] = a[firstIndex] - a[secondIndex]; - a[firstIndex] = a[firstIndex] - a[secondIndex]; + private void swap(int firstIndex, int secondIndex) { + int temp = heap[firstIndex]; + heap[firstIndex] = heap[secondIndex]; + heap[secondIndex] = temp; } // test cases public static void main(String[] args) { int[] a = new int[]{2, 4, 5, 1, 6, 7, 8}; - System.out.println(Arrays.toString(a)); - buildMaxHeap(a); - System.out.println(Arrays.toString(a)); + MaxHeap maxHeap = new MaxHeap(a); + maxHeap.printHeap(); + maxHeap.buildMaxHeap(); + maxHeap.printHeap(); + maxHeap.extractMax(); + maxHeap.printHeap(); + maxHeap.insert(12); + maxHeap.printHeap(); } } diff --git a/src/me/ramswaroop/common/MinHeap.java b/src/me/ramswaroop/common/MinHeap.java index f4aebba1..80bd51df 100644 --- a/src/me/ramswaroop/common/MinHeap.java +++ b/src/me/ramswaroop/common/MinHeap.java @@ -25,30 +25,37 @@ */ public class MinHeap { + int[] heap; + int size; + + public MinHeap(int[] heap) { + this.size = heap.length; + this.heap = Arrays.copyOf(heap, size); + } + /** * Makes the array {@param a} satisfy the min heap property starting from * {@param index} till the end of array. *

* Time complexity: O(log n). * - * @param a * @param index */ - public static void minHeapify(int[] a, int index) { + public void minHeapify(int index) { int smallest = index; int leftIndex = 2 * index + 1; int rightIndex = 2 * index + 2; - if (leftIndex < a.length && a[index] > a[leftIndex]) { + if (leftIndex < size && heap[index] > heap[leftIndex]) { smallest = leftIndex; } - if (rightIndex < a.length && a[smallest] > a[rightIndex]) { + if (rightIndex < size && heap[smallest] > heap[rightIndex]) { smallest = rightIndex; } if (smallest != index) { - swap(a, index, smallest); - minHeapify(a, smallest); + swap(index, smallest); + minHeapify(smallest); } } @@ -56,26 +63,84 @@ public static void minHeapify(int[] a, int index) { * Converts array {@param a} in to a min heap. *

* Time complexity: O(n) and is not O(n log n). - * - * @param a */ - public static void buildMinHeap(int[] a) { - for (int i = a.length / 2 - 1; i >= 0; i--) { - minHeapify(a, i); + public void buildMinHeap() { + for (int i = size / 2 - 1; i >= 0; i--) { + minHeapify(i); + } + } + + public void insert(int elem) { + heap = Arrays.copyOf(heap, size + 1); + int i = size; + int parentIndex = (int) Math.ceil((i / 2) - 1); + while (i > 0 && elem < heap[parentIndex]) { + heap[i] = heap[parentIndex]; + i = parentIndex; + parentIndex = (int) Math.ceil((parentIndex / 2) - 1); + } + heap[i] = elem; + size++; + } + + public int findMin() { + if (size == 0) { + return -1; + } else { + return heap[0]; + } + } + + public int extractMin() { + if (size == 0) return -1; + + int min = heap[0]; + heap[0] = heap[size - 1]; + size--; + minHeapify(0); + return min; + } + + public int getSize() { + return size; + } + + public int[] getHeap() { + return heap; + } + + public void printHeap() { + if (heap == null) + System.out.print("null"); + int iMax = size - 1, i; + if (iMax == -1) + System.out.print("[]"); + + StringBuilder b = new StringBuilder(); + b.append('['); + for (i = 0; i < iMax; i++) { + b.append(heap[i]); + b.append(", "); } + System.out.println(b.append(heap[i]).append(']').toString()); } - public static void swap(int[] a, int firstIndex, int secondIndex) { - a[firstIndex] = a[firstIndex] + a[secondIndex]; - a[secondIndex] = a[firstIndex] - a[secondIndex]; - a[firstIndex] = a[firstIndex] - a[secondIndex]; + private void swap(int firstIndex, int secondIndex) { + int temp = heap[firstIndex]; + heap[firstIndex] = heap[secondIndex]; + heap[secondIndex] = temp; } // test cases public static void main(String[] args) { int[] a = new int[]{2, 4, 5, 1, 6, 7, 8}; - System.out.println(Arrays.toString(a)); - buildMinHeap(a); - System.out.println(Arrays.toString(a)); + MinHeap minHeap = new MinHeap(a); + minHeap.printHeap(); + minHeap.buildMinHeap(); + minHeap.printHeap(); + minHeap.extractMin(); + minHeap.printHeap(); + minHeap.insert(0); + minHeap.printHeap(); } } From 34bfb560e52d446d9b03910c5610d744e9e85fdc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 13 Sep 2015 17:17:39 +0530 Subject: [PATCH 296/417] minor fixes --- src/me/ramswaroop/arrays/MedianOfStream.java | 2 ++ src/me/ramswaroop/common/MaxHeap.java | 4 ++-- src/me/ramswaroop/common/MinHeap.java | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/arrays/MedianOfStream.java b/src/me/ramswaroop/arrays/MedianOfStream.java index f019f36c..d92a002c 100644 --- a/src/me/ramswaroop/arrays/MedianOfStream.java +++ b/src/me/ramswaroop/arrays/MedianOfStream.java @@ -75,5 +75,7 @@ static int compare(int a, int b) { public static void main(String a[]) { printMedianOfStream(new int[]{5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4}); + printMedianOfStream(new int[]{5, 15, 1}); + printMedianOfStream(new int[]{5, 15, 10, 20}); } } diff --git a/src/me/ramswaroop/common/MaxHeap.java b/src/me/ramswaroop/common/MaxHeap.java index ae05be47..4eb7c87c 100644 --- a/src/me/ramswaroop/common/MaxHeap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -76,11 +76,11 @@ public void buildMaxHeap() { public void insert(int elem) { heap = Arrays.copyOf(heap, size + 1); int i = size; - int parentIndex = (int) Math.ceil((i / 2) - 1); + int parentIndex = (int) Math.floor((i - 1) / 2); while (i > 0 && elem > heap[parentIndex]) { heap[i] = heap[parentIndex]; i = parentIndex; - parentIndex = (int) Math.ceil((parentIndex / 2) - 1); + parentIndex = (int) Math.floor((i - 1) / 2); } heap[i] = elem; size++; diff --git a/src/me/ramswaroop/common/MinHeap.java b/src/me/ramswaroop/common/MinHeap.java index 80bd51df..be1f3312 100644 --- a/src/me/ramswaroop/common/MinHeap.java +++ b/src/me/ramswaroop/common/MinHeap.java @@ -73,11 +73,11 @@ public void buildMinHeap() { public void insert(int elem) { heap = Arrays.copyOf(heap, size + 1); int i = size; - int parentIndex = (int) Math.ceil((i / 2) - 1); + int parentIndex = (int) Math.floor((i - 1) / 2); while (i > 0 && elem < heap[parentIndex]) { heap[i] = heap[parentIndex]; i = parentIndex; - parentIndex = (int) Math.ceil((parentIndex / 2) - 1); + parentIndex = (int) Math.floor((i - 1) / 2); } heap[i] = elem; size++; From c015e16e4d6c9cafe93e529f2b115867d72b3ed5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 14 Sep 2015 12:11:58 +0530 Subject: [PATCH 297/417] added one more example --- src/me/ramswaroop/arrays/NextGreaterElement.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/me/ramswaroop/arrays/NextGreaterElement.java b/src/me/ramswaroop/arrays/NextGreaterElement.java index 0c468c4d..dd9d721c 100644 --- a/src/me/ramswaroop/arrays/NextGreaterElement.java +++ b/src/me/ramswaroop/arrays/NextGreaterElement.java @@ -56,5 +56,8 @@ public static void main(String a[]) { System.out.println("========="); ar = new int[]{1, 5, 3, 4, 2, 0, 11}; nextGreaterElements(ar); + System.out.println("========="); + ar = new int[]{3, 6, 8, 2 , 1, 5, 12, 4, 9}; + nextGreaterElements(ar); } } From 168f7a815d97ae12997d2a701514631a887056ed Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 14 Sep 2015 12:12:50 +0530 Subject: [PATCH 298/417] alignment --- src/me/ramswaroop/arrays/NextGreaterElement.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/arrays/NextGreaterElement.java b/src/me/ramswaroop/arrays/NextGreaterElement.java index dd9d721c..3039fb0a 100644 --- a/src/me/ramswaroop/arrays/NextGreaterElement.java +++ b/src/me/ramswaroop/arrays/NextGreaterElement.java @@ -42,7 +42,7 @@ public static void nextGreaterElements(int[] a) { while (!stack.isEmpty()) { System.out.println(stack.pop() + "->" + -1); } - + // no NGE for last element System.out.println(a[i] + "->" + -1); } @@ -57,7 +57,7 @@ public static void main(String a[]) { ar = new int[]{1, 5, 3, 4, 2, 0, 11}; nextGreaterElements(ar); System.out.println("========="); - ar = new int[]{3, 6, 8, 2 , 1, 5, 12, 4, 9}; - nextGreaterElements(ar); + ar = new int[]{3, 6, 8, 2, 1, 5, 12, 4, 9}; + nextGreaterElements(ar); } } From af590580f864933293000dff8fe6b2af1dba3d37 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 15 Sep 2015 23:34:45 +0530 Subject: [PATCH 299/417] initial commit --- src/me/ramswaroop/misc/Parenthesis.java | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/me/ramswaroop/misc/Parenthesis.java diff --git a/src/me/ramswaroop/misc/Parenthesis.java b/src/me/ramswaroop/misc/Parenthesis.java new file mode 100644 index 00000000..7deb21e1 --- /dev/null +++ b/src/me/ramswaroop/misc/Parenthesis.java @@ -0,0 +1,64 @@ +package me.ramswaroop.misc; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/15/15 + * @time: 11:15 PM + */ +public class Parenthesis { + + public static String isWellFormed(String input) { + int len = input.length() - 1; + for (int i = 0; i < len / 2; i++) { + if (input.charAt(0) != input.charAt(len - i - 1)) { + return "False"; + } + } + return "True"; + } + + public static void areParenthesisWellFormed(String filename) { + List input = readFile(filename); + for (int i = 0; i < input.size(); i++) { + isWellFormed(input.get(i)); + } + } + + public static List readFile(String filename) { + List input = new ArrayList<>(); + BufferedReader br = null; + + try { + + String sCurrentLine; + + br = new BufferedReader(new FileReader(filename)); + + while ((sCurrentLine = br.readLine()) != null) { + input.add(sCurrentLine); + } + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) br.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return input; + } + + public static void main(String a[]) { + areParenthesisWellFormed(a[0]); + } +} From 75019cbe8194b1265563b45c88626de0bc548dc6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 15 Sep 2015 23:58:45 +0530 Subject: [PATCH 300/417] minor fixes --- src/me/ramswaroop/misc/Parenthesis.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/misc/Parenthesis.java b/src/me/ramswaroop/misc/Parenthesis.java index 7deb21e1..36c2dc8b 100644 --- a/src/me/ramswaroop/misc/Parenthesis.java +++ b/src/me/ramswaroop/misc/Parenthesis.java @@ -16,9 +16,9 @@ public class Parenthesis { public static String isWellFormed(String input) { - int len = input.length() - 1; + int len = input.length(); for (int i = 0; i < len / 2; i++) { - if (input.charAt(0) != input.charAt(len - i - 1)) { + if (input.charAt(i) != input.charAt(len - i - 1)) { return "False"; } } @@ -28,24 +28,22 @@ public static String isWellFormed(String input) { public static void areParenthesisWellFormed(String filename) { List input = readFile(filename); for (int i = 0; i < input.size(); i++) { - isWellFormed(input.get(i)); + System.out.println(isWellFormed(input.get(i))); } } public static List readFile(String filename) { + List input = new ArrayList<>(); BufferedReader br = null; try { - String sCurrentLine; - br = new BufferedReader(new FileReader(filename)); while ((sCurrentLine = br.readLine()) != null) { input.add(sCurrentLine); } - } catch (IOException e) { e.printStackTrace(); } finally { @@ -60,5 +58,6 @@ public static List readFile(String filename) { public static void main(String a[]) { areParenthesisWellFormed(a[0]); + System.exit(0); } } From 9adb89955f9385e70610c852adb8a76d8f04a9f4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 16 Sep 2015 10:48:04 +0530 Subject: [PATCH 301/417] coded + unit tested --- src/me/ramswaroop/common/LinkedStack.java | 4 +- src/me/ramswaroop/misc/Parenthesis.java | 124 ++++++++++++++++++---- 2 files changed, 105 insertions(+), 23 deletions(-) diff --git a/src/me/ramswaroop/common/LinkedStack.java b/src/me/ramswaroop/common/LinkedStack.java index 113d470f..55b78fe6 100644 --- a/src/me/ramswaroop/common/LinkedStack.java +++ b/src/me/ramswaroop/common/LinkedStack.java @@ -13,7 +13,7 @@ /** * Stack implementation using - * a singly linked list + * a singly linked list. * * @param */ @@ -107,7 +107,7 @@ private class Node { E item; Node next; - Node(E item, Node next) { + Node(E item, Node next) { this.item = item; this.next = next; } diff --git a/src/me/ramswaroop/misc/Parenthesis.java b/src/me/ramswaroop/misc/Parenthesis.java index 36c2dc8b..acd183c3 100644 --- a/src/me/ramswaroop/misc/Parenthesis.java +++ b/src/me/ramswaroop/misc/Parenthesis.java @@ -4,6 +4,7 @@ import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; +import java.util.EmptyStackException; import java.util.List; /** @@ -15,43 +16,56 @@ */ public class Parenthesis { - public static String isWellFormed(String input) { + private static final char L_PAREN = '('; + private static final char R_PAREN = ')'; + private static final char L_BRACE = '{'; + private static final char R_BRACE = '}'; + private static final char L_BRACKET = '['; + private static final char R_BRACKET = ']'; + + public static boolean isWellFormed(String input) { int len = input.length(); - for (int i = 0; i < len / 2; i++) { - if (input.charAt(i) != input.charAt(len - i - 1)) { - return "False"; + Stack stack = new Stack<>(); + + // base case + if (len % 2 != 0) return false; + + for (int i = 0; i < len; i++) { + char charAtI = input.charAt(i); + if (charAtI == L_PAREN || charAtI == L_BRACE || charAtI == L_BRACKET) { + stack.push(charAtI); + } else if (charAtI == R_PAREN) { + if (stack.isEmpty() || stack.pop() != L_PAREN) return false; + } else if (charAtI == R_BRACE) { + if (stack.isEmpty() || stack.pop() != L_BRACE) return false; + } else if (charAtI == R_BRACKET) { + if (stack.isEmpty() || stack.pop() != L_BRACKET) return false; } } - return "True"; + + return stack.isEmpty(); } - public static void areParenthesisWellFormed(String filename) { - List input = readFile(filename); + public static void areParenthesisWellFormed(String filePath) { + List input = readFile(filePath); for (int i = 0; i < input.size(); i++) { - System.out.println(isWellFormed(input.get(i))); + System.out.println(isWellFormed(input.get(i)) ? "True" : "False"); } } - public static List readFile(String filename) { + public static List readFile(String filePath) { List input = new ArrayList<>(); - BufferedReader br = null; + try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { - try { - String sCurrentLine; - br = new BufferedReader(new FileReader(filename)); + String line; - while ((sCurrentLine = br.readLine()) != null) { - input.add(sCurrentLine); + while ((line = br.readLine()) != null) { + input.add(line); } + } catch (IOException e) { e.printStackTrace(); - } finally { - try { - if (br != null) br.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } } return input; } @@ -61,3 +75,71 @@ public static void main(String a[]) { System.exit(0); } } + +/** + * Stack implementation using + * a singly linked list. + * + * @param + */ +class Stack { + + private Node top; + + public Stack() { + top = null; + } + + /** + * Pushes an item onto the top of this stack. + * + * @param item + */ + public E push(E item) { + top = new Node<>(item, top); + return item; + } + + /** + * Removes the object at the top of this stack and + * returns it. + * + * @return + */ + public E pop() { + E item = peek(); + top = top.next; + return item; + } + + /** + * Looks at the object at the top of this stack without removing it from the stack. + * + * @return + */ + public E peek() { + if (top == null) { + throw new EmptyStackException(); + } + return top.item; + } + + /** + * Tests if this stack is empty. + * + * @return + */ + public boolean isEmpty() { + return top == null; + } + + private class Node { + E item; + Node next; + + Node(E item, Node next) { + this.item = item; + this.next = next; + } + } +} From 73620cffd3696e17c21c3b178ceefcbe4c704b05 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 16 Sep 2015 10:55:08 +0530 Subject: [PATCH 302/417] added comments --- src/me/ramswaroop/misc/Parenthesis.java | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/me/ramswaroop/misc/Parenthesis.java b/src/me/ramswaroop/misc/Parenthesis.java index acd183c3..5b455f14 100644 --- a/src/me/ramswaroop/misc/Parenthesis.java +++ b/src/me/ramswaroop/misc/Parenthesis.java @@ -23,6 +23,18 @@ public class Parenthesis { private static final char L_BRACKET = '['; private static final char R_BRACKET = ']'; + /** + * Checks if the parenthesis are well-formed in string {@param input}. + *

+ * For example, + * {[()]} : true + * {[]()[]} : true + * {[)} : false + * {(} : false + * + * @param input + * @return {@code true} if parenthesis are well-formed, {@code false} otherwise. + */ public static boolean isWellFormed(String input) { int len = input.length(); Stack stack = new Stack<>(); @@ -46,6 +58,11 @@ public static boolean isWellFormed(String input) { return stack.isEmpty(); } + /** + * Checks if the parenthesis are well-formed for the entire input. + * + * @param filePath + */ public static void areParenthesisWellFormed(String filePath) { List input = readFile(filePath); for (int i = 0; i < input.size(); i++) { @@ -53,6 +70,12 @@ public static void areParenthesisWellFormed(String filePath) { } } + /** + * Reads the file specified in {@param filePath}. + * + * @param filePath + * @return list of strings in each line of the file + */ public static List readFile(String filePath) { List input = new ArrayList<>(); @@ -70,6 +93,11 @@ public static List readFile(String filePath) { return input; } + /** + * Starting point of the program. + * + * @param a + */ public static void main(String a[]) { areParenthesisWellFormed(a[0]); System.exit(0); @@ -133,6 +161,11 @@ public boolean isEmpty() { return top == null; } + /** + * Generic node for holding values of any object type. + * + * @param + */ private class Node { E item; Node next; From 67bed69ec41990a50a241afce295432c1c49d692 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 16 Sep 2015 16:46:51 +0530 Subject: [PATCH 303/417] minor optimizations --- src/me/ramswaroop/misc/Parenthesis.java | 28 ++++++------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/src/me/ramswaroop/misc/Parenthesis.java b/src/me/ramswaroop/misc/Parenthesis.java index 5b455f14..6945d347 100644 --- a/src/me/ramswaroop/misc/Parenthesis.java +++ b/src/me/ramswaroop/misc/Parenthesis.java @@ -3,9 +3,7 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; -import java.util.ArrayList; import java.util.EmptyStackException; -import java.util.List; /** * Created by IntelliJ IDEA. @@ -57,40 +55,26 @@ public static boolean isWellFormed(String input) { return stack.isEmpty(); } - - /** - * Checks if the parenthesis are well-formed for the entire input. - * - * @param filePath - */ - public static void areParenthesisWellFormed(String filePath) { - List input = readFile(filePath); - for (int i = 0; i < input.size(); i++) { - System.out.println(isWellFormed(input.get(i)) ? "True" : "False"); - } - } - + /** - * Reads the file specified in {@param filePath}. + * Reads the file specified in {@param filePath} line by line + * and checks if parenthesis are well-formed or not. * * @param filePath - * @return list of strings in each line of the file */ - public static List readFile(String filePath) { + public static void readFile(String filePath) { - List input = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { - input.add(line); + System.out.println(isWellFormed(line) ? "True" : "False"); } } catch (IOException e) { e.printStackTrace(); } - return input; } /** @@ -99,7 +83,7 @@ public static List readFile(String filePath) { * @param a */ public static void main(String a[]) { - areParenthesisWellFormed(a[0]); + readFile(a[0]); System.exit(0); } } From 92423e66225267901a299d2245d374bf03839d59 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 17 Sep 2015 10:00:32 +0530 Subject: [PATCH 304/417] initial commit --- src/me/ramswaroop/misc/ReverseAndAdd.java | 68 ++++++++++++++ src/me/ramswaroop/misc/reverseandadd.txt | 106 ++++++++++++++++++++++ 2 files changed, 174 insertions(+) create mode 100644 src/me/ramswaroop/misc/ReverseAndAdd.java create mode 100644 src/me/ramswaroop/misc/reverseandadd.txt diff --git a/src/me/ramswaroop/misc/ReverseAndAdd.java b/src/me/ramswaroop/misc/ReverseAndAdd.java new file mode 100644 index 00000000..5e2d8445 --- /dev/null +++ b/src/me/ramswaroop/misc/ReverseAndAdd.java @@ -0,0 +1,68 @@ +package me.ramswaroop.misc; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/16/15 + * @time: 10:53 PM + */ +public class ReverseAndAdd { + + public static long getReverse(long n) { + return Long.valueOf(new StringBuilder().append(n).reverse().toString()); + } + + public static boolean isPalindrome(long n) { + return n == getReverse(n); + } + + public static boolean isNegative(long n) { + return n < 0; + } + + public static long[] reverseAddAndCheck(String n) { + long additions = 0; + long original = Long.valueOf(n); + + boolean isNegative = isNegative(original); + if (isNegative) original = -original; + + long reverse; + + while (!isPalindrome(original + (reverse = getReverse(original)))) { + original += reverse; + additions++; + } + + original += reverse; + if (isNegative) original = -original; + + return new long[]{additions, original}; + } + + public static void readFile(String filePath) { + + try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { + + String line; + + while ((line = br.readLine()) != null) { + long[] result = reverseAddAndCheck(line); + System.out.println(result[0] + " " + result[1]); + } + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void main(String a[]) { + readFile(a[0]); + System.exit(0); + } +} diff --git a/src/me/ramswaroop/misc/reverseandadd.txt b/src/me/ramswaroop/misc/reverseandadd.txt new file mode 100644 index 00000000..2265b806 --- /dev/null +++ b/src/me/ramswaroop/misc/reverseandadd.txt @@ -0,0 +1,106 @@ +1 +5 +59 +69 +79 +89 +166 +188 +193 +829 +167 +849 +177 +999 +739 +989 +869 +187 +1397 +2069 +1797 +1798 +6999 +1297 +10797 +10853 +10921 +10971 +13297 +10548 +13293 +17793 +20889 +80359 +13697 +10794 +15891 +70759 +70269 +10677 +10833 +10911 +700269 +106977 +108933 +600259 +131996 +600279 +141996 +600579 +147996 +178992 +190890 +600589 +150296 +1009227 +1007619 +1009246 +1008628 +1007377 +1001699 +1009150 +1058921 +1050995 +1003569 +1036974 +1490991 +3009179 +1008595 +1064912 +1998999 +7008429 +1000689 +1005744 +1007601 +7008899 +9008299 +10905963 +10069785 +10089342 +11979990 +10029372 +10029826 +16207990 +90000589 +10309988 +100389898 +100055896 +110909992 +160009490 +800067199 +151033997 +100093573 +103249931 +107025910 +180005498 +100239862 +140669390 +1090001921 +7007009909 +1009049407 +9000046899 +1050027948 +1304199693 +5020089949 +1005499526 \ No newline at end of file From e521aba3cc32dd01531e22b1d3af21d269605eb2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 17 Sep 2015 10:01:10 +0530 Subject: [PATCH 305/417] test cases for parenthesis --- src/me/ramswaroop/misc/parenthesis.txt | 1587 ++++++++++++++++++++++++ 1 file changed, 1587 insertions(+) create mode 100644 src/me/ramswaroop/misc/parenthesis.txt diff --git a/src/me/ramswaroop/misc/parenthesis.txt b/src/me/ramswaroop/misc/parenthesis.txt new file mode 100644 index 00000000..077f4ab6 --- /dev/null +++ b/src/me/ramswaroop/misc/parenthesis.txt @@ -0,0 +1,1587 @@ +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{{{{}}}} +{[]}{[]} +{[()]} +{[] +{{]][[}} +{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]{]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]}{[]} +{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} \ No newline at end of file From 9a69b26880ef77378df65fe8829d78ec230d4bd6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 17 Sep 2015 11:11:09 +0530 Subject: [PATCH 306/417] minor fixes --- src/me/ramswaroop/misc/ReverseAndAdd.java | 2 +- src/me/ramswaroop/misc/reverseandadd.txt | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/misc/ReverseAndAdd.java b/src/me/ramswaroop/misc/ReverseAndAdd.java index 5e2d8445..9871fd4f 100644 --- a/src/me/ramswaroop/misc/ReverseAndAdd.java +++ b/src/me/ramswaroop/misc/ReverseAndAdd.java @@ -26,7 +26,7 @@ public static boolean isNegative(long n) { } public static long[] reverseAddAndCheck(String n) { - long additions = 0; + long additions = 1; long original = Long.valueOf(n); boolean isNegative = isNegative(original); diff --git a/src/me/ramswaroop/misc/reverseandadd.txt b/src/me/ramswaroop/misc/reverseandadd.txt index 2265b806..90f6286f 100644 --- a/src/me/ramswaroop/misc/reverseandadd.txt +++ b/src/me/ramswaroop/misc/reverseandadd.txt @@ -103,4 +103,5 @@ 1050027948 1304199693 5020089949 -1005499526 \ No newline at end of file +1005499526 +4294967294 \ No newline at end of file From f87f7479152c8bc7f02aee51712913759ed27454 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 17 Sep 2015 11:28:56 +0530 Subject: [PATCH 307/417] converted to biginteger to handle larger numbers --- src/me/ramswaroop/misc/ReverseAndAdd.java | 39 ++++++----- src/me/ramswaroop/misc/reverseandadd.txt | 84 ++++++++++++++++++++++- 2 files changed, 103 insertions(+), 20 deletions(-) diff --git a/src/me/ramswaroop/misc/ReverseAndAdd.java b/src/me/ramswaroop/misc/ReverseAndAdd.java index 9871fd4f..1d588535 100644 --- a/src/me/ramswaroop/misc/ReverseAndAdd.java +++ b/src/me/ramswaroop/misc/ReverseAndAdd.java @@ -3,6 +3,7 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; +import java.math.BigInteger; /** * Created by IntelliJ IDEA. @@ -13,36 +14,36 @@ */ public class ReverseAndAdd { - public static long getReverse(long n) { - return Long.valueOf(new StringBuilder().append(n).reverse().toString()); + public static BigInteger getReverse(BigInteger n) { + return new BigInteger(new StringBuilder().append(n).reverse().toString()); } - public static boolean isPalindrome(long n) { - return n == getReverse(n); + public static boolean isPalindrome(BigInteger n) { + return n.compareTo(getReverse(n)) == 0; } - public static boolean isNegative(long n) { - return n < 0; + public static boolean isNegative(BigInteger n) { + return n.compareTo(new BigInteger("0")) == -1; } - public static long[] reverseAddAndCheck(String n) { - long additions = 1; - long original = Long.valueOf(n); + public static BigInteger[] reverseAddAndCheck(String n) { + BigInteger additions = new BigInteger("1"); + BigInteger original = new BigInteger(n); boolean isNegative = isNegative(original); - if (isNegative) original = -original; + if (isNegative) original = original.multiply(new BigInteger("-1")); - long reverse; + BigInteger reverse; - while (!isPalindrome(original + (reverse = getReverse(original)))) { - original += reverse; - additions++; + while (!isPalindrome(original.add(reverse = getReverse(original)))) { + original = original.add(reverse); + additions = additions.add(new BigInteger("1")); } - original += reverse; - if (isNegative) original = -original; + original = original.add(reverse); + if (isNegative) original = original.multiply(new BigInteger("-1")); - return new long[]{additions, original}; + return new BigInteger[]{additions, original}; } public static void readFile(String filePath) { @@ -52,8 +53,8 @@ public static void readFile(String filePath) { String line; while ((line = br.readLine()) != null) { - long[] result = reverseAddAndCheck(line); - System.out.println(result[0] + " " + result[1]); + BigInteger[] result = reverseAddAndCheck(line); + System.out.println(result[0].toString() + " " + result[1].toString()); } } catch (IOException e) { diff --git a/src/me/ramswaroop/misc/reverseandadd.txt b/src/me/ramswaroop/misc/reverseandadd.txt index 90f6286f..79ae5976 100644 --- a/src/me/ramswaroop/misc/reverseandadd.txt +++ b/src/me/ramswaroop/misc/reverseandadd.txt @@ -104,4 +104,86 @@ 1304199693 5020089949 1005499526 -4294967294 \ No newline at end of file +10000505448 +10000922347 +10000696511 +10701592943 +10018999583 +10000442119 +10000761554 +10084899970 +10006198250 +18060009890 +11400245996 +16002897892 +18317699990 +37000488999 +10050289485 +90000626389 +10000853648 +13003696093 +10050859271 +10287799930 +10000973037 +10600713933 +10942399911 +60000180709 +11009599796 +16000097392 +10031199494 +10306095991 +10087799570 +100900509906 +100000055859 +104000146950 +180005998298 +300000185539 +100001987765 +1000007614641 +1000043902320 +1000006653746 +1000005469548 +4000096953659 +1332003929995 +1000201995662 +6000008476379 +1200004031698 +1631002019993 +1000006412206 +1090604591930 +1600005969190 +10090899969901 +40000004480279 +14104229999995 +100000109584608 +100000098743648 +100004789906151 +100079239995161 +100389619999030 +200000729975309 +107045067996994 +105420999199982 +101000269830970 +104000047066970 +700000001839569 +100000050469737 +101000789812993 +100907098999571 +100017449991820 +890000023937399 +100009989989199 +101507024989944 +107405139999943 +100057569996821 +103500369729970 +900000076152049 +100000439071028 +120000046510993 +103000015331997 +100617081999573 +100009029910821 +107000020928910 +100000090745299 +102000149322944 +130000074931591 +100120849299260 \ No newline at end of file From 729a0feb26286a57338b5f5cb0ba84c1ffb96c08 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 17 Sep 2015 11:42:21 +0530 Subject: [PATCH 308/417] added test cases --- src/me/ramswaroop/misc/ReverseAndAdd.java | 36 +++++++++++++++++++++ src/me/ramswaroop/misc/reverseandadd.txt | 38 ++++++++++++++++++++++- 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/misc/ReverseAndAdd.java b/src/me/ramswaroop/misc/ReverseAndAdd.java index 1d588535..c519b360 100644 --- a/src/me/ramswaroop/misc/ReverseAndAdd.java +++ b/src/me/ramswaroop/misc/ReverseAndAdd.java @@ -14,18 +14,43 @@ */ public class ReverseAndAdd { + /** + * Reverses the number {@param n}. + * + * @param n + * @return the reverse of the number {@param n}. + */ public static BigInteger getReverse(BigInteger n) { return new BigInteger(new StringBuilder().append(n).reverse().toString()); } + /** + * Checks if {@param n} is palindrome. + * + * @param n + * @return {@code true} if {@param n} is palindrome. + */ public static boolean isPalindrome(BigInteger n) { return n.compareTo(getReverse(n)) == 0; } + /** + * Checks if {@param n} is negative. + * + * @param n + * @return {@code true} if {@param n} is negative, {@code false} otherwise. + */ public static boolean isNegative(BigInteger n) { return n.compareTo(new BigInteger("0")) == -1; } + /** + * Reverses the number {@param n}, adds to itself and then checks + * for palindrome. + * + * @param n + * @return an array of {@code BigInteger} with number of additions and final palindrome number respectively. + */ public static BigInteger[] reverseAddAndCheck(String n) { BigInteger additions = new BigInteger("1"); BigInteger original = new BigInteger(n); @@ -46,6 +71,12 @@ public static BigInteger[] reverseAddAndCheck(String n) { return new BigInteger[]{additions, original}; } + /** + * Reads the input file mentioned in {@param filePath} line by line + * and calls {@code reverseAddAndCheck()} for every line. + * + * @param filePath + */ public static void readFile(String filePath) { try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { @@ -62,6 +93,11 @@ public static void readFile(String filePath) { } } + /** + * Starting point of the program. + * + * @param a + */ public static void main(String a[]) { readFile(a[0]); System.exit(0); diff --git a/src/me/ramswaroop/misc/reverseandadd.txt b/src/me/ramswaroop/misc/reverseandadd.txt index 79ae5976..9e1727db 100644 --- a/src/me/ramswaroop/misc/reverseandadd.txt +++ b/src/me/ramswaroop/misc/reverseandadd.txt @@ -186,4 +186,40 @@ 100000090745299 102000149322944 130000074931591 -100120849299260 \ No newline at end of file +100120849299260 +-1 +-5 +-59 +-69 +-79 +-89 +-166 +-188 +-193 +-829 +-167 +-849 +-177 +-999 +-739 +-989 +-869 +-187 +-1397 +-2069 +-1797 +-1798 +-6999 +-1297 +-103500369729970 +-900000076152049 +-100000439071028 +-120000046510993 +-103000015331997 +-100617081999573 +-100009029910821 +-107000020928910 +-100000090745299 +-102000149322944 +-130000074931591 +-100120849299260 \ No newline at end of file From f7fb803dbedeb015a20b956c7e953a7cdcb589ba Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 18 Sep 2015 17:38:23 +0530 Subject: [PATCH 309/417] coded + unit tested --- .../arrays/LongestBitonicSubArray.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/me/ramswaroop/arrays/LongestBitonicSubArray.java diff --git a/src/me/ramswaroop/arrays/LongestBitonicSubArray.java b/src/me/ramswaroop/arrays/LongestBitonicSubArray.java new file mode 100644 index 00000000..e804b8fa --- /dev/null +++ b/src/me/ramswaroop/arrays/LongestBitonicSubArray.java @@ -0,0 +1,64 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/18/15 + * @time: 5:10 PM + */ +public class LongestBitonicSubArray { + + /** + * Returns the length of the longest bitonic sub-array in + * array {@param a}. + *

+ * A subarray A[i … j] is bitonic if there is a k with i <= k <= j such + * that A[i] <= A[i + 1] ... <= A[k] >= A[k + 1] >= ... A[j – 1] > = A[j]. + * + * @param a + * @return + */ + public static int getLongestBitonicSubArrayLength(int[] a) { + int len = a.length; + int bitonicLength; + int[] increasingSequence = new int[len]; + int[] decreasingSequence = new int[len]; + + increasingSequence[0] = 1; // stores the length of the increasing sequence so far + decreasingSequence[len - 1] = 1; // stores the length of the decreasing sequence so far + + for (int i = 1; i < len; i++) { + if (a[i] > a[i - 1]) { + increasingSequence[i] = increasingSequence[i - 1] + 1; + } else { + increasingSequence[i] = 1; + } + } + + for (int i = len - 2; i >= 0; i--) { + if (a[i] > a[i + 1]) { + decreasingSequence[i] = decreasingSequence[i + 1] + 1; + } else { + decreasingSequence[i] = 1; + } + } + + bitonicLength = increasingSequence[0] + decreasingSequence[0] - 1; + for (int i = 0; i < len; i++) { + if ((increasingSequence[i] + decreasingSequence[i] - 1) > bitonicLength) { + bitonicLength = increasingSequence[i] + decreasingSequence[i] - 1; + } + } + + return bitonicLength; + } + + public static void main(String a[]) { + System.out.println(getLongestBitonicSubArrayLength(new int[]{1, 2, 5, 4, 3})); + System.out.println(getLongestBitonicSubArrayLength(new int[]{12, 4, 78, 90, 45, 23})); + System.out.println(getLongestBitonicSubArrayLength(new int[]{10, 20, 30, 40})); + System.out.println(getLongestBitonicSubArrayLength(new int[]{40, 30, 20, 10})); + System.out.println(getLongestBitonicSubArrayLength(new int[]{10})); + } +} From 822c69a2acb53dc49242cae0f8219a76dc559851 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 19 Sep 2015 23:54:22 +0530 Subject: [PATCH 310/417] initial commit --- .../arrays/CountSmallerElementsOnRHS.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java diff --git a/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java b/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java new file mode 100644 index 00000000..bab78097 --- /dev/null +++ b/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java @@ -0,0 +1,31 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/19/15 + * @time: 11:33 PM + */ +public class CountSmallerElementsOnRHS { + + public static int[] getSmallerElementsCountOnRHSNaive(int[] a) { + int[] result = new int[a.length]; + int i, j, temp; + for (i = a.length - 2; i >= 0; i--) { + for (j = i + 1; a[i] < a[j]; j++) { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + result[i] = j - i; + } + return result; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{12, 1, 2, 3, 0, 11, 4}))); + } +} From c9bc6fc2a6ab5f3e6cbb759b01769351a25d7ba5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 19 Sep 2015 23:54:48 +0530 Subject: [PATCH 311/417] code refactoring --- src/me/ramswaroop/misc/BotTesting.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/misc/BotTesting.java b/src/me/ramswaroop/misc/BotTesting.java index 7fa425c4..903491cb 100644 --- a/src/me/ramswaroop/misc/BotTesting.java +++ b/src/me/ramswaroop/misc/BotTesting.java @@ -7,6 +7,7 @@ * Time: 4:16 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -21,6 +22,7 @@ public static void main(String args[]) throws MalformedURLException { final URL myURL = new URL("http://localhost:8080/ifb.html"); ExecutorService executorService = Executors.newFixedThreadPool(20); Long start = System.currentTimeMillis(); + for (int i = 0; i <= 50; i++) { executorService.execute(new Runnable() { @@ -53,12 +55,4 @@ public void run() { System.out.println("Difference: " + diff + "ms"); executorService.shutdown(); } - - private class MyThread extends Thread { - - @Override - public void run(){ - - } - } } From ad9be85665733cb50630e7b8e96c61726991d808 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 20 Sep 2015 00:33:28 +0530 Subject: [PATCH 312/417] todo --- .../arrays/CountSmallerElementsOnRHS.java | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java b/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java index bab78097..295b50ec 100644 --- a/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java +++ b/src/me/ramswaroop/arrays/CountSmallerElementsOnRHS.java @@ -12,20 +12,13 @@ public class CountSmallerElementsOnRHS { public static int[] getSmallerElementsCountOnRHSNaive(int[] a) { - int[] result = new int[a.length]; - int i, j, temp; - for (i = a.length - 2; i >= 0; i--) { - for (j = i + 1; a[i] < a[j]; j++) { - temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } - result[i] = j - i; - } - return result; + // TODO + return null; } public static void main(String a[]) { System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{12, 1, 2, 3, 0, 11, 4}))); + System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{5, 4, 3, 2, 1}))); + System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{1, 2, 3, 4, 5}))); } } From dcbda029d667a99dac8342b5479f590c2d0880a7 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 20 Sep 2015 15:45:53 +0530 Subject: [PATCH 313/417] minor change --- src/me/ramswaroop/misc/ReverseAndAdd.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/misc/ReverseAndAdd.java b/src/me/ramswaroop/misc/ReverseAndAdd.java index c519b360..029d7905 100644 --- a/src/me/ramswaroop/misc/ReverseAndAdd.java +++ b/src/me/ramswaroop/misc/ReverseAndAdd.java @@ -85,7 +85,7 @@ public static void readFile(String filePath) { while ((line = br.readLine()) != null) { BigInteger[] result = reverseAddAndCheck(line); - System.out.println(result[0].toString() + " " + result[1].toString()); + System.out.println(result[0] + " " + result[1]); } } catch (IOException e) { From 5bafb279eb8ad0ceafddb0b2d8e163385daad7b6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 20 Sep 2015 19:46:37 +0530 Subject: [PATCH 314/417] coded naive approach + unit tested --- .../MinimumJumpsToReachEnd.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java diff --git a/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java b/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java new file mode 100644 index 00000000..ceb70117 --- /dev/null +++ b/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java @@ -0,0 +1,54 @@ +package me.ramswaroop.dynamicprogramming; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/20/15 + * @time: 1:18 PM + */ +public class MinimumJumpsToReachEnd { + + /** + * Given an array of integers where each element represents the max number of steps that + * can be made forward from that element. Write a function to return the minimum number + * of jumps to reach the end of the array (starting from the first element). If an element + * is 0, then we cannot move through that element. + * + * A naive approach is to start from the first element and recursively call for all the elements + * reachable from first element. The minimum number of jumps to reach end from first can be calculated + * using minimum number of jumps needed to reach end from the elements reachable from first. + * + * minJumps(start, end) = Min ( minJumps(k, end) ) for all k reachable from start + * + * @param a + * @param l + * @param h + * @return + */ + public static int getMinimumJumpsToReachEndNaive(int[] a, int l, int h) { + // base cases + if (l == h) return 0; + if (a[l] == 0) return Integer.MAX_VALUE; + + int minJumps = Integer.MAX_VALUE; + for (int i = l + 1; i <= h && i <= a[l] + l; i++) { + int jumps = getMinimumJumpsToReachEndNaive(a, i, h); + if (jumps + 1 < minJumps) { + minJumps = jumps + 1; + } + } + return minJumps; + } + + public static void main(String a[]) { + int[] ar = new int[]{1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}; + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); + ar = new int[]{5, 4, 3, 2, 1}; + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); + ar = new int[]{1, 2, 3, 4, 5}; + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); + ar = new int[]{1, 2}; + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); + } +} From 64e87ff228937c7abac894eab7ee36a7a333e8bb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 21 Sep 2015 19:03:46 +0530 Subject: [PATCH 315/417] coded + unit tested --- .../arrays/TwoStacksInOneArray.java | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 src/me/ramswaroop/arrays/TwoStacksInOneArray.java diff --git a/src/me/ramswaroop/arrays/TwoStacksInOneArray.java b/src/me/ramswaroop/arrays/TwoStacksInOneArray.java new file mode 100644 index 00000000..f0e626a8 --- /dev/null +++ b/src/me/ramswaroop/arrays/TwoStacksInOneArray.java @@ -0,0 +1,93 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * Implement two stacks using a single array with efficient use of space. + * We could do this by dividing the array into two equal halves or storing stack + * elements alternatively in the array but that wouldn't utilize the space fully. + * So we stored stack1's elements at one end of the array and stack2's elements at + * the other end. + * + * @author: ramswaroop + * @date: 9/21/15 + * @time: 6:18 PM + */ +public class TwoStacksInOneArray { + + int[] array; + int top1, top2, size; + + TwoStacksInOneArray(int size) { + array = new int[size]; + this.size = size; + top1 = -1; + top2 = size; + } + + void push(int stack, int item) { + if (top1 == top2 - 1) { + System.out.println("Stack is full"); + return; + } + + if (stack == 1) { + top1++; + array[top1] = item; + } else { + top2--; + array[top2] = item; + } + } + + int pop(int stack) { + if (stack == 1) { + if (top1 == -1) { + System.out.println("Stack 1 is empty"); + return -1; + } + int pop = array[top1]; + top1--; + return pop; + } else { + if (top2 == size) { + System.out.println("Stack 2 is empty"); + return -1; + } + int pop = array[top2]; + top2++; + return pop; + } + } + + void printStack(int stack) { + if (stack == 1) { + System.out.println(Arrays.toString(Arrays.copyOfRange(array, 0, top1 + 1))); + } else { + System.out.println(Arrays.toString(Arrays.copyOfRange(array, top2, size))); + } + } + + public static void main(String a[]) { + TwoStacksInOneArray twoStack = new TwoStacksInOneArray(5); + twoStack.push(1, 3); + twoStack.push(1, 4); + twoStack.push(1, 5); + twoStack.push(2, 1); + twoStack.push(1, 6); + twoStack.push(1, 7); + twoStack.printStack(1); + twoStack.pop(1); + twoStack.pop(1); + twoStack.pop(1); + twoStack.pop(1); + twoStack.pop(1); + twoStack.pop(1); + twoStack.printStack(2); + twoStack.pop(2); + twoStack.pop(2); + twoStack.printStack(2); + } +} From 71e46b0e8b6f1294d14a33ab44d8a729ee3df00f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 22 Sep 2015 23:04:20 +0530 Subject: [PATCH 316/417] trie code done + basic unit tested --- src/me/ramswaroop/common/Trie.java | 81 ++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/me/ramswaroop/common/Trie.java diff --git a/src/me/ramswaroop/common/Trie.java b/src/me/ramswaroop/common/Trie.java new file mode 100644 index 00000000..df02ae41 --- /dev/null +++ b/src/me/ramswaroop/common/Trie.java @@ -0,0 +1,81 @@ +package me.ramswaroop.common; + +import java.util.HashMap; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/22/15 + * @time: 8:19 PM + */ +public class Trie { + + TrieNode root; + + Trie() { + root = new TrieNode<>(null, new HashMap>()); + } + + public void insert(E data) { + + int i = 0; + String str = data.toString(); + TrieNode curr = root; + + while (i < str.length()) { + if (curr.children.get(str.substring(i, i + 1)) != null) { + curr = curr.children.get(str.substring(i, i + 1)); + i++; + } else { + break; + } + } + + while (i < str.length()) { + curr.children.put(str.substring(i, i + 1), new TrieNode<>(null, new HashMap>())); + curr = curr.children.get(str.substring(i, i + 1)); + i++; + } + + curr.data = data; + } + + public boolean search(E data) { + + int i = 0; + String str = data.toString(); + TrieNode curr = root; + + while (i < str.length()) { + if (curr.children.get(str.substring(i, i + 1)) == null) { + return false; + } + curr = curr.children.get(str.substring(i, i + 1)); + i++; + } + + return curr.data == data; + } + + private class TrieNode { + E data; + HashMap> children; + + TrieNode(E data, HashMap> children) { + this.data = data; + this.children = children; + } + } + + public static void main(String[] a) { + Trie trie = new Trie<>(); + trie.insert("ram"); + trie.insert("rama"); + trie.insert("ramswaroop"); + System.out.println(trie.search("ram")); + System.out.println(trie.search("ra")); + System.out.println(trie.search("raz")); + System.out.println(trie.search("ramswaroop")); + } +} From 6a71c73473dc5f3bebf8e8732a298ad3938511fc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 22 Sep 2015 23:58:22 +0530 Subject: [PATCH 317/417] added comments --- src/me/ramswaroop/common/Trie.java | 40 +++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/common/Trie.java b/src/me/ramswaroop/common/Trie.java index df02ae41..f16be88b 100644 --- a/src/me/ramswaroop/common/Trie.java +++ b/src/me/ramswaroop/common/Trie.java @@ -5,6 +5,14 @@ /** * Created by IntelliJ IDEA. * + * Trie also called digital tree and sometimes radix tree or prefix tree (as they can be + * searched by prefixes), is an ordered tree data structure that is used to store a dynamic + * set or associative array where the keys are usually strings. + * + * You can think it as HashMap of HashMap of HashMap and so on. Each key in the HashMap is a + * single digit/letter of the data you want to store and {@code data} is the final full word + * you want to save in trie. + * * @author: ramswaroop * @date: 9/22/15 * @time: 8:19 PM @@ -17,12 +25,17 @@ public class Trie { root = new TrieNode<>(null, new HashMap>()); } + /** + * Inserts {@param data} in trie. + * + * @param data + */ public void insert(E data) { - + int i = 0; String str = data.toString(); TrieNode curr = root; - + while (i < str.length()) { if (curr.children.get(str.substring(i, i + 1)) != null) { curr = curr.children.get(str.substring(i, i + 1)); @@ -37,16 +50,22 @@ public void insert(E data) { curr = curr.children.get(str.substring(i, i + 1)); i++; } - + curr.data = data; } - + + /** + * Searches {@param data} in trie. + * + * @param data + * @return {@code true} if {@param data} is present, {@code false} otherwise. + */ public boolean search(E data) { - + int i = 0; String str = data.toString(); TrieNode curr = root; - + while (i < str.length()) { if (curr.children.get(str.substring(i, i + 1)) == null) { return false; @@ -54,12 +73,12 @@ public boolean search(E data) { curr = curr.children.get(str.substring(i, i + 1)); i++; } - + return curr.data == data; } private class TrieNode { - E data; + E data; // stores the complete string (required to determine whether the string is in the trie) HashMap> children; TrieNode(E data, HashMap> children) { @@ -67,13 +86,16 @@ private class TrieNode { this.children = children; } } - + + // unit testing public static void main(String[] a) { Trie trie = new Trie<>(); trie.insert("ram"); + trie.insert("r"); trie.insert("rama"); trie.insert("ramswaroop"); System.out.println(trie.search("ram")); + System.out.println(trie.search("r")); System.out.println(trie.search("ra")); System.out.println(trie.search("raz")); System.out.println(trie.search("ramswaroop")); From 3a94da8de87d1833d54444feef607a4deef9f725 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 23 Sep 2015 11:27:56 +0530 Subject: [PATCH 318/417] minor fix --- src/me/ramswaroop/common/Trie.java | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/common/Trie.java b/src/me/ramswaroop/common/Trie.java index f16be88b..75afdcc3 100644 --- a/src/me/ramswaroop/common/Trie.java +++ b/src/me/ramswaroop/common/Trie.java @@ -4,18 +4,20 @@ /** * Created by IntelliJ IDEA. - * - * Trie also called digital tree and sometimes radix tree or prefix tree (as they can be - * searched by prefixes), is an ordered tree data structure that is used to store a dynamic + *

+ * Trie also called digital tree and sometimes radix tree or prefix tree (as they can be + * searched by prefixes), is an ordered tree data structure that is used to store a dynamic * set or associative array where the keys are usually strings. - * - * You can think it as HashMap of HashMap of HashMap and so on. Each key in the HashMap is a + *

+ * You can think it as HashMap of HashMap of HashMap and so on. Each key in the HashMap is a * single digit/letter of the data you want to store and {@code data} is the final full word * you want to save in trie. - * + * * @author: ramswaroop * @date: 9/22/15 * @time: 8:19 PM + * @see: https://en.wikipedia.org/wiki/Trie + * @see: https://www.topcoder.com/community/data-science/data-science-tutorials/using-tries */ public class Trie { @@ -27,7 +29,7 @@ public class Trie { /** * Inserts {@param data} in trie. - * + * * @param data */ public void insert(E data) { @@ -56,7 +58,7 @@ public void insert(E data) { /** * Searches {@param data} in trie. - * + * * @param data * @return {@code true} if {@param data} is present, {@code false} otherwise. */ @@ -74,7 +76,7 @@ public boolean search(E data) { i++; } - return curr.data == data; + return curr.data != null && curr.data.equals(data); } private class TrieNode { From 5e3c4c60400d004a84bd3beb56b6f0a9e4f6d0b9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 23 Sep 2015 20:48:00 +0530 Subject: [PATCH 319/417] coded + unit tested --- .../arrays/PrintAnagramsTogether.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/me/ramswaroop/arrays/PrintAnagramsTogether.java diff --git a/src/me/ramswaroop/arrays/PrintAnagramsTogether.java b/src/me/ramswaroop/arrays/PrintAnagramsTogether.java new file mode 100644 index 00000000..050bedce --- /dev/null +++ b/src/me/ramswaroop/arrays/PrintAnagramsTogether.java @@ -0,0 +1,42 @@ +package me.ramswaroop.arrays; + +import java.util.*; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/23/15 + * @time: 8:11 PM + */ +public class PrintAnagramsTogether { + + public static void printAnagramsTogether(String[] s) { + + HashMap> hashMap = new HashMap<>(); + + for (int i = 0; i < s.length; i++) { + char[] chars = s[i].toCharArray(); + Arrays.sort(chars); + + List indexes = hashMap.get(String.valueOf(chars)); + if (indexes == null) { + indexes = new ArrayList<>(); + } + indexes.add(i); + hashMap.put(String.valueOf(chars), indexes); + } + + for (Map.Entry> entry : hashMap.entrySet()) { + for (int i = 0; i < entry.getValue().size(); i++) { + System.out.println(s[entry.getValue().get(i)]); + } + System.out.println("------"); + } + } + + public static void main(String a[]) { + printAnagramsTogether(new String[]{"cat", "dog", "tac", "god", "act"}); + printAnagramsTogether(new String[]{"cat", "tac", "act", "god", "dog"}); + } +} From 559c8609f36e900f7900af0563cc4c94893f7a85 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 23 Sep 2015 22:02:35 +0530 Subject: [PATCH 320/417] code refactoring --- src/me/ramswaroop/bits/Addition.java | 81 +++++++++---------- .../MinimumJumpsToReachEnd.java | 2 + 2 files changed, 42 insertions(+), 41 deletions(-) diff --git a/src/me/ramswaroop/bits/Addition.java b/src/me/ramswaroop/bits/Addition.java index b4ced8d0..1b19af0f 100644 --- a/src/me/ramswaroop/bits/Addition.java +++ b/src/me/ramswaroop/bits/Addition.java @@ -10,7 +10,25 @@ public class Addition { /** - * Better solution. + * Best method. + *

+ * -n = ~n + 1. + * ~n = -(n+1). Therefore, n+1 = -(~n). + *

+ * Works for -ve numbers. + *

+ * Note: This method works only if the numbers + * are stored in 2’s complement form. + * + * @param n + * @return + */ + public static int add(int n) { + return -(~n); + } + + /** + * Good solution. *

* Adds two numbers without using any * arithmetic operators. @@ -39,7 +57,7 @@ public static int add(int x, int y) { * @param y * @return sum of {@param x} and {@param y} */ - public static int add_V1(int x, int y) { + public static int addNaive(int x, int y) { int carry = 0, sum = 0, c = 0, xLSB, yLSB; while (c < 32) { xLSB = x & 1; @@ -57,25 +75,6 @@ public static int add_V1(int x, int y) { return sum; } - - /** - * Best method. - *

- * -n = ~n + 1. - * ~n = -(n+1). Therefore, n+1 = -(~n). - *

- * Works for -ve numbers. - *

- * Note: This method works only if the numbers - * are stored in 2’s complement form. - * - * @param n - * @return - */ - public static int add1(int n) { - return -(~n); - } - /** * Idea is to flip all the bits of {@param n} till * rightmost 0 bit in {@param n}. @@ -85,7 +84,7 @@ public static int add1(int n) { * @param n * @return */ - public static int add1_V1(int n) { + public static int addByFlip(int n) { int mask = 1; // flip all bits in n until rightmost 0 bit while ((n & mask) != 0) { @@ -106,26 +105,26 @@ public static void main(String a[]) { System.out.println(add(456, 982348234)); // 982348690 System.out.println(add(1, 0xffffffff)); // 0 System.out.println("------"); - System.out.println(add_V1(0, 0)); //0 - System.out.println(add_V1(12, 12)); //24 - System.out.println(add_V1(12, 5)); //17 - System.out.println(add_V1(3, 5)); //8 - System.out.println(add_V1(8, 5)); //13 - System.out.println(add_V1(13, 256)); // 269 - System.out.println(add_V1(456, 982348234)); // 982348690 - System.out.println(add_V1(1, 0xffffffff)); // 0 + System.out.println(addNaive(0, 0)); //0 + System.out.println(addNaive(12, 12)); //24 + System.out.println(addNaive(12, 5)); //17 + System.out.println(addNaive(3, 5)); //8 + System.out.println(addNaive(8, 5)); //13 + System.out.println(addNaive(13, 256)); // 269 + System.out.println(addNaive(456, 982348234)); // 982348690 + System.out.println(addNaive(1, 0xffffffff)); // 0 System.out.println("------"); - System.out.println(add1_V1(0)); - System.out.println(add1_V1(1)); - System.out.println(add1_V1(2)); - System.out.println(add1_V1(3)); - System.out.println(add1_V1(4)); - System.out.println(add1_V1(5)); - System.out.println(add1_V1(7)); + System.out.println(addByFlip(0)); + System.out.println(addByFlip(1)); + System.out.println(addByFlip(2)); + System.out.println(addByFlip(3)); + System.out.println(addByFlip(4)); + System.out.println(addByFlip(5)); + System.out.println(addByFlip(7)); System.out.println("------"); - System.out.println(add1(1)); - System.out.println(add1(5)); - System.out.println(add1(-0)); - System.out.println(add1(-5)); + System.out.println(add(1)); + System.out.println(add(5)); + System.out.println(add(-0)); + System.out.println(add(-5)); } } diff --git a/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java b/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java index ceb70117..94301e56 100644 --- a/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java +++ b/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java @@ -40,6 +40,8 @@ public static int getMinimumJumpsToReachEndNaive(int[] a, int l, int h) { } return minJumps; } + + // TODO dp approach public static void main(String a[]) { int[] ar = new int[]{1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}; From 36d95aee03bf3d69b31e3e4b249836cf16ee08fd Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 23 Sep 2015 22:19:39 +0530 Subject: [PATCH 321/417] comments added --- src/me/ramswaroop/bits/Addition.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/bits/Addition.java b/src/me/ramswaroop/bits/Addition.java index 1b19af0f..75b3edd4 100644 --- a/src/me/ramswaroop/bits/Addition.java +++ b/src/me/ramswaroop/bits/Addition.java @@ -77,7 +77,7 @@ public static int addNaive(int x, int y) { /** * Idea is to flip all the bits of {@param n} till - * rightmost 0 bit in {@param n}. + * rightmost 0 bit (inclusive). *

* Doesn't work for -ve numbers. * From b846a6bc483e1333dcc9701aa911276803ed610a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 24 Sep 2015 14:32:28 +0530 Subject: [PATCH 322/417] coded + unit tested --- .../ramswaroop/arrays/StringPermutations.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/me/ramswaroop/arrays/StringPermutations.java diff --git a/src/me/ramswaroop/arrays/StringPermutations.java b/src/me/ramswaroop/arrays/StringPermutations.java new file mode 100644 index 00000000..b8abb9b2 --- /dev/null +++ b/src/me/ramswaroop/arrays/StringPermutations.java @@ -0,0 +1,30 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/24/15 + * @time: 2:27 PM + */ +public class StringPermutations { + + public static void printAllPermutations(String prefix, String s) { + int len = s.length(); + if (len == 0) { + System.out.println(prefix); + } else { + for (int i = 0; i < len; i++) { + printAllPermutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, len)); + } + } + } + + public static void main(String a[]) { + printAllPermutations("", "a"); + System.out.println("-------"); + printAllPermutations("", "ab"); + System.out.println("-------"); + printAllPermutations("", "abc"); + } +} From 4e8df7598dab169fbcf115ef0c6ed5a458549d18 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 25 Sep 2015 12:31:38 +0530 Subject: [PATCH 323/417] coded + unit tested --- src/me/ramswaroop/misc/BreakParagraph.java | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/me/ramswaroop/misc/BreakParagraph.java diff --git a/src/me/ramswaroop/misc/BreakParagraph.java b/src/me/ramswaroop/misc/BreakParagraph.java new file mode 100644 index 00000000..bc60c1b6 --- /dev/null +++ b/src/me/ramswaroop/misc/BreakParagraph.java @@ -0,0 +1,47 @@ +package me.ramswaroop.misc; + +import java.text.BreakIterator; +import java.util.Locale; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/22/15 + * @time: 10:02 AM + */ +public class BreakParagraph { + public static void main(String[] args) { + String paragraph = + "Line boundary analysis determines where a text " + + "string can be broken when line-wrapping. The " + + "mechanism correctly handles punctuation and " + + "hyphenated words. Mr.Ram is a good boy. Actual line breaking needs to " + + "also consider the available line width and is " + + "handled by higher-level software. "; + + BreakIterator iterator = + BreakIterator.getSentenceInstance(Locale.US); + + int sentences = count(iterator, paragraph); + System.out.println("Number of sentences: " + sentences); + } + + private static int count(BreakIterator bi, String source) { + int counter = 0; + bi.setText(source); + + int lastIndex = bi.first(); + while (lastIndex != BreakIterator.DONE) { + int firstIndex = lastIndex; + lastIndex = bi.next(); + + if (lastIndex != BreakIterator.DONE) { + String sentence = source.substring(firstIndex, lastIndex); + System.out.println("sentence = " + sentence); + counter++; + } + } + return counter; + } +} From 6bccb40112240bf076d446024f276d043b0f651c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 25 Sep 2015 12:31:59 +0530 Subject: [PATCH 324/417] code refactoring --- src/me/ramswaroop/bits/MultipleOf3.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/MultipleOf3.java b/src/me/ramswaroop/bits/MultipleOf3.java index 934212dc..cfcd9304 100644 --- a/src/me/ramswaroop/bits/MultipleOf3.java +++ b/src/me/ramswaroop/bits/MultipleOf3.java @@ -55,6 +55,6 @@ public static void main(String a[]) { * * If sum of digits in a number is multiple of 3 then number is multiple of * 3 e.g., for 612 sum of digits is 9 so it’s a multiple of 3. But this solution - * is not efficient. You have to get all decimal digits one by one, add them and then check if sum is multiple of 3. - * + * is not efficient. You have to get all decimal digits one by one, add them and + * then check if sum is multiple of 3. */ \ No newline at end of file From 566ddd4ebdcbef3de74c2fc862ea2ab8278739f6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 25 Sep 2015 12:38:05 +0530 Subject: [PATCH 325/417] comments added --- src/me/ramswaroop/arrays/StringPermutations.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/me/ramswaroop/arrays/StringPermutations.java b/src/me/ramswaroop/arrays/StringPermutations.java index b8abb9b2..62b611ea 100644 --- a/src/me/ramswaroop/arrays/StringPermutations.java +++ b/src/me/ramswaroop/arrays/StringPermutations.java @@ -6,9 +6,18 @@ * @author: ramswaroop * @date: 9/24/15 * @time: 2:27 PM + * @see: http://www.ericleschinski.com/c/java_permutations_recursion/ + * @see: http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html */ public class StringPermutations { + /** + * Generates and prints all possible permutations (in order) + * of string {@param s}. + * + * @param prefix + * @param s + */ public static void printAllPermutations(String prefix, String s) { int len = s.length(); if (len == 0) { From 1d725939494bf53dd63bdd202445658ac6bf7f20 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 25 Sep 2015 14:35:46 +0530 Subject: [PATCH 326/417] minor corrections --- src/me/ramswaroop/arrays/sorting/QuickSort.java | 6 ++++-- src/me/ramswaroop/arrays/sorting/SelectionSort.java | 2 +- src/me/ramswaroop/common/MaxHeap.java | 12 ++++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/arrays/sorting/QuickSort.java b/src/me/ramswaroop/arrays/sorting/QuickSort.java index 83cdcd09..1370a2bb 100644 --- a/src/me/ramswaroop/arrays/sorting/QuickSort.java +++ b/src/me/ramswaroop/arrays/sorting/QuickSort.java @@ -28,9 +28,10 @@ public static int partition(int[] ar, int low, int high) { for (int i = low; i < high; i++) { /** * if ith element is smaller than pivot element then - * swap it with the last larger element known. + * swap it with the last larger element known */ if (ar[i] < ar[pivot]) { + // swap a[low] with a[i] temp = ar[low]; ar[low] = ar[i]; ar[i] = temp; @@ -48,7 +49,8 @@ public static int partition(int[] ar, int low, int high) { /** * Recursive Quick sort. - * NOTE: This function is tail-recursive. + * NOTE: This function is tail-recursive (doesn't use + * extra stack space per recursive call). *

* Time complexity: * Best Case: O(nlogn) diff --git a/src/me/ramswaroop/arrays/sorting/SelectionSort.java b/src/me/ramswaroop/arrays/sorting/SelectionSort.java index 3944d945..ef0b4bc5 100644 --- a/src/me/ramswaroop/arrays/sorting/SelectionSort.java +++ b/src/me/ramswaroop/arrays/sorting/SelectionSort.java @@ -19,7 +19,7 @@ public class SelectionSort { * element is chosen and placed at the appropriate position and then again the * logic is applied on rest of the elements till the entire array is sorted. *

- * Time complexity: O(n) for all cases. + * Time complexity: O(n*n) for all cases. *

* NOTE: Advantage of this sort is that it requires minimum number of memory writes * like Cycle sort. diff --git a/src/me/ramswaroop/common/MaxHeap.java b/src/me/ramswaroop/common/MaxHeap.java index 4eb7c87c..77bf10a7 100644 --- a/src/me/ramswaroop/common/MaxHeap.java +++ b/src/me/ramswaroop/common/MaxHeap.java @@ -73,10 +73,22 @@ public void buildMaxHeap() { } } + /** + * Insert a new element into the heap satisfying + * the heap property. + * + * Time complexity: O(log n) where 'n' is total no. of + * elements in heap or O(h) where 'h' is the height of + * heap. + * + * @param elem + */ public void insert(int elem) { + // increase heap size heap = Arrays.copyOf(heap, size + 1); int i = size; int parentIndex = (int) Math.floor((i - 1) / 2); + // move up through the heap till you find the right position while (i > 0 && elem > heap[parentIndex]) { heap[i] = heap[parentIndex]; i = parentIndex; From ab635b14c46f6a99f3aefe47f31814e6547d4b59 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 26 Sep 2015 19:08:15 +0530 Subject: [PATCH 327/417] coded + unit tested --- .../ramswaroop/arrays/StringPermutations.java | 2 +- .../UppercaseLowercasePermutations.java | 57 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java diff --git a/src/me/ramswaroop/arrays/StringPermutations.java b/src/me/ramswaroop/arrays/StringPermutations.java index 62b611ea..38da054b 100644 --- a/src/me/ramswaroop/arrays/StringPermutations.java +++ b/src/me/ramswaroop/arrays/StringPermutations.java @@ -24,7 +24,7 @@ public static void printAllPermutations(String prefix, String s) { System.out.println(prefix); } else { for (int i = 0; i < len; i++) { - printAllPermutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, len)); + printAllPermutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1)); } } } diff --git a/src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java b/src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java new file mode 100644 index 00000000..326d3a74 --- /dev/null +++ b/src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java @@ -0,0 +1,57 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/26/15 + * @time: 4:43 PM + */ +public class UppercaseLowercasePermutations { + + /** + * Generates all possible case combinations for string {@param s}. + *

+ * For example, + * Input: 0ab + * Output: ["0ab","0AB","0aB","0Ab"] + * + * @param prefix + * @param s + */ + public static void printUppercaseLowercasePermutations(String prefix, String s) { + + if (s.isEmpty()) { + System.out.println(prefix); + return; + } + + if (!isNumber(s.charAt(0))) { + printUppercaseLowercasePermutations(prefix + Character.toUpperCase(s.charAt(0)), s.substring(1)); + printUppercaseLowercasePermutations(prefix + Character.toLowerCase(s.charAt(0)), s.substring(1)); + } else { + printUppercaseLowercasePermutations(prefix + s.charAt(0), s.substring(1)); + + } + + } + + public static boolean isNumber(char s) { + try { + Integer.parseInt(String.valueOf(s)); + } catch (Exception e) { + return false; + } + return true; + } + + public static void main(String a[]) { + printUppercaseLowercasePermutations("", "0ab"); + System.out.println("========"); + printUppercaseLowercasePermutations("", "01"); + System.out.println("========"); + printUppercaseLowercasePermutations("", "0a1"); + System.out.println("========"); + printUppercaseLowercasePermutations("", "0ab1c"); + } +} From 6790225611bede28fa6df1e6e10eac06703bddd3 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 27 Sep 2015 19:19:26 +0530 Subject: [PATCH 328/417] comment corrections --- src/me/ramswaroop/arrays/EquilibriumIndex.java | 2 +- src/me/ramswaroop/arrays/SubsetOfArray.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/arrays/EquilibriumIndex.java b/src/me/ramswaroop/arrays/EquilibriumIndex.java index 0fe83838..89f129ff 100644 --- a/src/me/ramswaroop/arrays/EquilibriumIndex.java +++ b/src/me/ramswaroop/arrays/EquilibriumIndex.java @@ -34,7 +34,7 @@ public static int getEquilibriumIndex(int[] a) { } for (int i = 0; i < a.length; i++) { - totalSum -= a[i]; // totalSum now holds the right sum + totalSum -= a[i]; // totalSum now holds the right sum from ith index to end if (leftSum == totalSum) { return i; // left sum == right sum } diff --git a/src/me/ramswaroop/arrays/SubsetOfArray.java b/src/me/ramswaroop/arrays/SubsetOfArray.java index 7f19f84b..47e3154f 100644 --- a/src/me/ramswaroop/arrays/SubsetOfArray.java +++ b/src/me/ramswaroop/arrays/SubsetOfArray.java @@ -16,8 +16,8 @@ public class SubsetOfArray { *

* Explanation: The below method uses sorting + merge method of merge sort. Time * complexity is O(mlogm + nlogn) where m and n are lengths of array a and b resp. - * You could also have used sorting + binary search but this fails when superset - * array has repeating elements for example, a={1,4,4,2} and b={1,4,2}. Time + * You could also have used sorting + binary search but this fails when array + * {@param b} has repeating elements for example, a={1,4,2} and b={1,4,4,2}. Time * complexity would be O(mlogm + nlogm). * * @param a From ffc885366e38cbdbd98db3c7ddbe7b649764f6d6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 27 Sep 2015 20:12:41 +0530 Subject: [PATCH 329/417] coded + unit tested --- src/me/ramswaroop/arrays/SubArrayOfSum.java | 49 +++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SubArrayOfSum.java diff --git a/src/me/ramswaroop/arrays/SubArrayOfSum.java b/src/me/ramswaroop/arrays/SubArrayOfSum.java new file mode 100644 index 00000000..78ded53f --- /dev/null +++ b/src/me/ramswaroop/arrays/SubArrayOfSum.java @@ -0,0 +1,49 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/27/15 + * @time: 7:32 PM + */ +public class SubArrayOfSum { + + /** + * Prints the sub-array in array {@param a} with sum {@param sum}. + *

+ * Algorithm: Keep on adding the elements, once the sum is larger + * than the required sum start deleting the elements from the sum. + * (Google Interview Question) + * + * @param a + * @param sum + */ + public static void printSubArrayOfSum(int[] a, int sum) { + int currSum = 0, startIndex = 0; + for (int i = 0; i < a.length; i++) { + + currSum += a[i]; + + while (currSum > sum && startIndex < i) { + currSum -= a[startIndex++]; + } + + if (currSum == sum) { + System.out.println("Sub-array lies between indexes: " + startIndex + " and " + i); + return; + } + } + System.out.println("Sub-array with sum " + sum + " not found!"); + } + + public static void main(String a[]) { + printSubArrayOfSum(new int[]{1, 4, 20, 3, 10, 5}, 33); + printSubArrayOfSum(new int[]{1, 4, 20, 3, 10, 5}, 38); + printSubArrayOfSum(new int[]{1, 4, 20, 3, 10, 5}, 13); + printSubArrayOfSum(new int[]{1, 4, 0, 0, 3, 10, 5}, 0); + printSubArrayOfSum(new int[]{1, 4}, 0); + printSubArrayOfSum(new int[]{1, 4}, -4); + printSubArrayOfSum(new int[]{1, -4}, -3); + } +} From ad96c63f07bcfcbe5e432d9edbe4f954b7f25c33 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 28 Sep 2015 23:41:55 +0530 Subject: [PATCH 330/417] coded + unit tested --- src/me/ramswaroop/arrays/TripletOfSum.java | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/me/ramswaroop/arrays/TripletOfSum.java diff --git a/src/me/ramswaroop/arrays/TripletOfSum.java b/src/me/ramswaroop/arrays/TripletOfSum.java new file mode 100644 index 00000000..087cb343 --- /dev/null +++ b/src/me/ramswaroop/arrays/TripletOfSum.java @@ -0,0 +1,50 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.arrays.sorting.QuickSort; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/28/15 + * @time: 10:39 PM + */ +public class TripletOfSum { + + /** + * Finds any 3 numbers in array {@param a} + * whose sum is equal to {@param sum}. + *

+ * Time complexity: O(n^2) + * + * @param a + * @param sum + * @return + */ + public static int[] getTripletOfSum(int[] a, int sum) { + + QuickSort.quickSort(a); + + int len = a.length; + for (int i = 0, j = i + 1, k = len - 1; i < len - 2; i++) { + while (j < k) { + if (a[i] + a[j] + a[k] == sum) { + return new int[]{a[i], a[j], a[k]}; + } else if (a[i] + a[j] + a[k] < sum) { + j++; + } else { + k--; + } + } + } + return new int[]{-1}; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getTripletOfSum(new int[]{12, 3, 4, 5, 1, 6, 9}, 24))); + System.out.println(Arrays.toString(getTripletOfSum(new int[]{12, 3, 4, 5, 1, 6, 9}, 19))); + System.out.println(Arrays.toString(getTripletOfSum(new int[]{1, 2, 3}, 6))); + } +} From 432e046635f6f0a0aecf1ca99fcb09bb067897aa Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 29 Sep 2015 22:30:44 +0530 Subject: [PATCH 331/417] coded + unit tested --- .../LongestIncreasingSubsequence.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/me/ramswaroop/dynamicprogramming/LongestIncreasingSubsequence.java diff --git a/src/me/ramswaroop/dynamicprogramming/LongestIncreasingSubsequence.java b/src/me/ramswaroop/dynamicprogramming/LongestIncreasingSubsequence.java new file mode 100644 index 00000000..77a7a0d5 --- /dev/null +++ b/src/me/ramswaroop/dynamicprogramming/LongestIncreasingSubsequence.java @@ -0,0 +1,61 @@ +package me.ramswaroop.dynamicprogramming; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/29/15 + * @time: 10:15 PM + */ +public class LongestIncreasingSubSequence { + + /** + * TODO: Properly document and understand + * The Longest Increasing SubSequence (LIS) problem is to find the length of + * the longest sub-sequence of a given sequence such that all elements of the + * sub-sequence are sorted in increasing order. + * + * For example, + * Length of LIS for { 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6 and LIS + * is {10, 22, 33, 50, 60, 80}. + * + * Optimal Substructure: + * Let arr[0..n-1] be the input array and L(i) be the length of the LIS till index i such that arr[i] is part + * of LIS and arr[i] is the last element in LIS, then L(i) can be recursively written as. + * L(i) = { 1 + Max ( L(j) ) } where j < i and arr[j] < arr[i] and if there is no such j then L(i) = 1 + * To get LIS of a given array, we need to return max(L(i)) where 0 < i < n So the LIS problem has optimal + * substructure property as the main problem can be solved using solutions to sub-problems. + * + * @param a + * @return + */ + public static int getLongestIncreasingSubSequenceLength(int[] a) { + int len = a.length, maxLisLength = 0; + int[] lis = new int[len]; + + for (int i = 0; i < len; i++) { + lis[i] = 1; + } + + for (int i = 1; i < len; i++) { + for (int j = 0; j < i; j++) { + if (a[i] > a[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + } + } + + for (int i = 0; i < len; i++) { + if (lis[i] > maxLisLength) { + maxLisLength = lis[i]; + } + } + + return maxLisLength; + } + + public static void main(String a[]) { + System.out.println(getLongestIncreasingSubSequenceLength(new int[]{2, 3, 7, 8, 15})); + System.out.println(getLongestIncreasingSubSequenceLength(new int[]{2, 20, 7, 8, 1})); + System.out.println(getLongestIncreasingSubSequenceLength(new int[]{20, 10, 5})); + } +} From c40271e1a543cb1f96bc07e9ac6bd0324ce56f48 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 1 Oct 2015 08:50:55 +0530 Subject: [PATCH 332/417] coded + unit tested --- src/me/ramswaroop/misc/RecursiveWarmup.java | 118 ++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 src/me/ramswaroop/misc/RecursiveWarmup.java diff --git a/src/me/ramswaroop/misc/RecursiveWarmup.java b/src/me/ramswaroop/misc/RecursiveWarmup.java new file mode 100644 index 00000000..db47ed0a --- /dev/null +++ b/src/me/ramswaroop/misc/RecursiveWarmup.java @@ -0,0 +1,118 @@ +package me.ramswaroop.misc; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/28/15 + * @time: 8:37 PM + */ +public class RecursiveWarmup { + + /** + * Reverses the string {@param input} iteratively. + * + * @param input + * @return the reversed {@code String}. + */ + public String reverse(String input) { + + int len = input.length(); + char[] charArray = input.toCharArray(); + char[] revCharArray = new char[len]; + + for (int i = 0; i < len; i++) { + revCharArray[len - i - 1] = charArray[i]; + } + + return String.valueOf(revCharArray); + } + + /** + * Reverses the string {@param input} recursively. + * NOTE: This is BAD programming practice. + * + * @param input + * @return the reversed {@code String}. + */ + public String reverseRecursive(String input) { + if (input.length() > 1) { + char c = input.charAt(0); + String rev = reverseRecursive(input.substring(1)); + input = rev + c; + } + return input; + } + + + /** + * Reverses a list {@param input}. + * + * @param input + * @return reversed {@code List}. + */ + public List reverse(List input) { + + List revList = new ArrayList<>(); + + for (int i = input.size() - 1; i >= 0; i--) { + revList.add(input.get(i)); + } + + return revList; + } + + /** + * Reverses a list {@param input} recursively. + * NOTE: This is BAD programming practice. + * + * @param input + * @return reversed {@code List}. + */ + public List reverseRecursive(List input) { + + if (!input.isEmpty()) { + Integer item = input.remove(0); + reverseRecursive(input); + input.add(item); + } + return input; + } + + /** + * Starting point of the program. + * + * @param a + */ + public static void main(String a[]) { + RecursiveWarmup RecursiveWarmup = new RecursiveWarmup(); + List list1 = new ArrayList<>(); + list1.add(1); + list1.add(2); + list1.add(3); + list1.add(4); + List list2 = new ArrayList<>(); + list2.add(1); + List list3 = new ArrayList<>(); + System.out.println("========= String reverse test cases ========="); + System.out.println(RecursiveWarmup.reverse("apple")); + System.out.println(RecursiveWarmup.reverse("a")); + System.out.println(RecursiveWarmup.reverse("")); + System.out.println("========= String reverse recursive test cases ========="); + System.out.println(RecursiveWarmup.reverseRecursive("apple")); + System.out.println(RecursiveWarmup.reverseRecursive("a")); + System.out.println(RecursiveWarmup.reverseRecursive("")); + System.out.println("========== List reverse test cases =========="); + System.out.println(RecursiveWarmup.reverse(list1)); + System.out.println(RecursiveWarmup.reverse(list2)); + System.out.println(RecursiveWarmup.reverse(list3)); + System.out.println("========== List reverse recursive test cases =========="); + System.out.println(RecursiveWarmup.reverseRecursive(list1)); + System.out.println(RecursiveWarmup.reverseRecursive(list2)); + System.out.println(RecursiveWarmup.reverseRecursive(list3)); + System.exit(0); + } +} From 751393e499473aa99499c4c8287a9dfdb1f9bb6e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 2 Oct 2015 21:26:59 +0530 Subject: [PATCH 333/417] simple gc example --- src/me/ramswaroop/misc/GarbageCollection.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/me/ramswaroop/misc/GarbageCollection.java diff --git a/src/me/ramswaroop/misc/GarbageCollection.java b/src/me/ramswaroop/misc/GarbageCollection.java new file mode 100644 index 00000000..fd280a7e --- /dev/null +++ b/src/me/ramswaroop/misc/GarbageCollection.java @@ -0,0 +1,22 @@ +package me.ramswaroop.misc; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/2/15 + * @time: 12:44 AM + */ +public class GarbageCollection { + public void finalize() { + System.out.println("object is garbage collected"); + } + + public static void main(String args[]) { + GarbageCollection s1 = new GarbageCollection(); + GarbageCollection s2 = new GarbageCollection(); + s1 = null; + s2 = null; + System.gc(); + } +} From 89b8af9d1b81e2d5094712b591c48fc1a963ed7a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 2 Oct 2015 23:06:09 +0530 Subject: [PATCH 334/417] coded + unit tested --- .../ramswaroop/arrays/CelebrityProblem.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/me/ramswaroop/arrays/CelebrityProblem.java diff --git a/src/me/ramswaroop/arrays/CelebrityProblem.java b/src/me/ramswaroop/arrays/CelebrityProblem.java new file mode 100644 index 00000000..5a2253e2 --- /dev/null +++ b/src/me/ramswaroop/arrays/CelebrityProblem.java @@ -0,0 +1,68 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.common.LinkedStack; +import me.ramswaroop.common.Stack; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/2/15 + * @time: 10:48 PM + */ +public class CelebrityProblem { + + /** + * Checks if person {@param a} knows person {@param b}. + * + * @param peoples + * @param a + * @param b + * @return + */ + public static boolean haveAcquaintance(int[][] peoples, int a, int b) { + return peoples[a][b] == 1; + } + + /** + * Finds the celebrity in {@param peoples} where + * peoples[i][j] is 1 when person i knows person j. + * + * @param peoples + * @return + */ + public static int findCelebrity(int[][] peoples) { + + Stack possibleCelebrities = new LinkedStack<>(); + + for (int i = 0; i < peoples.length; i++) { + for (int j = 0; j < peoples[0].length; j++) { + if (haveAcquaintance(peoples, i, j)) { + possibleCelebrities.push(j); + } + } + } + + int firstPerson = -1, secondPerson; + while (!possibleCelebrities.isEmpty()) { + firstPerson = possibleCelebrities.pop(); + + // we have found the celebrity + if (possibleCelebrities.isEmpty()) break; + + secondPerson = possibleCelebrities.pop(); + if (haveAcquaintance(peoples, firstPerson, secondPerson)) { + possibleCelebrities.push(secondPerson); + } else { + possibleCelebrities.push(firstPerson); + } + } + + return firstPerson; + } + + public static void main(String a[]) { + System.out.println(findCelebrity(new int[][]{{0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}, {0, 0, 1, 0}})); + System.out.println(findCelebrity(new int[][]{{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}})); + } +} From e9434c4e13ab8a36a0e389ddbda8d8721bbe4302 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 3 Oct 2015 15:53:22 +0530 Subject: [PATCH 335/417] code refactoring + comments added --- .../ramswaroop/arrays/CelebrityProblem.java | 19 ++++++++++++++++++- .../arrays/NumberOccurringOddTimes.java | 3 +++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/CelebrityProblem.java b/src/me/ramswaroop/arrays/CelebrityProblem.java index 5a2253e2..3be0049e 100644 --- a/src/me/ramswaroop/arrays/CelebrityProblem.java +++ b/src/me/ramswaroop/arrays/CelebrityProblem.java @@ -9,6 +9,12 @@ * @author: ramswaroop * @date: 10/2/15 * @time: 10:48 PM + *

+ * In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, + * (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger + * (celebrity) in minimum number of questions. + * + * TODO: Not tested. */ public class CelebrityProblem { @@ -27,7 +33,18 @@ public static boolean haveAcquaintance(int[][] peoples, int a, int b) { /** * Finds the celebrity in {@param peoples} where * peoples[i][j] is 1 when person i knows person j. - * + *

+ * Algorithm: + * - If A knows B, then A can’t be celebrity. Discard A, but B may be celebrity. + * - If A does not know B, then B can’t be celebrity. Discard B, but A may be celebrity. + * - Repeat above two steps till we left with only one person. + * Find celebrity within remaining persons by performing the below operations: + * - Push all the celebrities into a stack. + * - Pop off top two persons from the stack, discard one person based on return status of HaveAcquaintance(A, B). + * - Push the remained person onto stack. + * - Repeat step 2 and 3 until only one person remains in the stack. + * - Check the remained person in stack does not have acquaintance with anyone else. + * * @param peoples * @return */ diff --git a/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java b/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java index c8e3fc85..71902bb0 100644 --- a/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java +++ b/src/me/ramswaroop/arrays/NumberOccurringOddTimes.java @@ -12,6 +12,9 @@ * Given an array of positive integers. All numbers occur * even number of times except one number which occurs odd * number of times. Find the number in O(n) time & constant space. + * + * See {@link me.ramswaroop.bits.TwoNonRepeatingElements} for a more + * complex problem which is solved in a similar approach. */ public class NumberOccurringOddTimes { From 24224394012a78304de2ca9919a698af67866637 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 4 Oct 2015 23:26:30 +0530 Subject: [PATCH 336/417] added new method --- src/me/ramswaroop/bits/ReverseBits.java | 29 +++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index 6ff2dcc7..6c2eaa64 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -42,7 +42,7 @@ public static int getNumberByReversingBits(int n) { * @param n * @return */ - public static int getNumberByReversingBits_V1(int n) { + public static int getNumberByReversingBitsV1(int n) { int reverseNum = 0, i = 0; while (n > 0) { @@ -56,8 +56,33 @@ public static int getNumberByReversingBits_V1(int n) { return reverseNum; } + /** + * This method is similar to {@link #getNumberByReversingBitsV1(int)} but here we put + * the set bits of {@param n} in {@code reverse number} and keep on shifting the reverse number + * left until {@param n} becomes {@code zero} and finally shift left for the remaining number of + * bits used to represent the number. + * + * @param n + * @return + */ + public static int getNumberByReversingBitsV2(int n) { + int noOfBits = 32; + int reverse = 0; + + while (n > 0) { + reverse <<= 1; + reverse |= n & 1; + n >>>= 1; + noOfBits--; + } + reverse <<= noOfBits; + return reverse; + } + public static void main(String a[]) { System.out.println(getNumberByReversingBits(79876)); - System.out.println(getNumberByReversingBits_V1(79876)); + System.out.println(getNumberByReversingBitsV1(79876)); + System.out.println(getNumberByReversingBitsV2(79876)); + System.out.println(getNumberByReversingBitsV2(5)); } } From 4b39cb8890f997ba2548707be3f05d70bb3a197b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 4 Oct 2015 23:29:11 +0530 Subject: [PATCH 337/417] added comments --- src/me/ramswaroop/bits/ReverseBits.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index 6c2eaa64..2dec8f10 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -57,10 +57,12 @@ public static int getNumberByReversingBitsV1(int n) { } /** - * This method is similar to {@link #getNumberByReversingBitsV1(int)} but here we put - * the set bits of {@param n} in {@code reverse number} and keep on shifting the reverse number - * left until {@param n} becomes {@code zero} and finally shift left for the remaining number of + * This method is similar to {@link #getNumberByReversingBitsV1(int)} but here we put + * the set bits of {@param n} in {@code reverse number} and keep on shifting the reverse number + * left until {@param n} becomes {@code zero} and finally shift left for the remaining number of * bits used to represent the number. + *

+ * Time complexity: O(log n) (as we are dividing 'n' by 2 in each iteration) * * @param n * @return From ea09762cb9883b724839dacc32e1a427e03a714d Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 4 Oct 2015 23:30:28 +0530 Subject: [PATCH 338/417] minor issue fixed --- src/me/ramswaroop/bits/ReverseBits.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index 2dec8f10..dbf09884 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -49,7 +49,7 @@ public static int getNumberByReversingBitsV1(int n) { if ((n & 1) == 1) { reverseNum |= 1 << 31 - i; } - n >>= 1; + n >>>= 1; i++; } From abbe0828f372238fc884cb02ac6b6176aa562f9b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 4 Oct 2015 23:31:18 +0530 Subject: [PATCH 339/417] added comments --- src/me/ramswaroop/bits/ReverseBits.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/me/ramswaroop/bits/ReverseBits.java b/src/me/ramswaroop/bits/ReverseBits.java index dbf09884..3d188f4f 100644 --- a/src/me/ramswaroop/bits/ReverseBits.java +++ b/src/me/ramswaroop/bits/ReverseBits.java @@ -63,6 +63,7 @@ public static int getNumberByReversingBitsV1(int n) { * bits used to represent the number. *

* Time complexity: O(log n) (as we are dividing 'n' by 2 in each iteration) + * Space Complexity: O(1) * * @param n * @return From e536e34ac1c393f1350ed127b722a215d9605ae1 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 5 Oct 2015 23:31:16 +0530 Subject: [PATCH 340/417] coded + unit tested --- src/me/ramswaroop/arrays/PairDiff.java | 72 ++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/me/ramswaroop/arrays/PairDiff.java diff --git a/src/me/ramswaroop/arrays/PairDiff.java b/src/me/ramswaroop/arrays/PairDiff.java new file mode 100644 index 00000000..670d1656 --- /dev/null +++ b/src/me/ramswaroop/arrays/PairDiff.java @@ -0,0 +1,72 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/18/15 + * @time: 10:24 PM + */ + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Given an array ar[] of n numbers and another number x, determine whether + * or not there exists two elements in ar[] whose difference is exactly x. + * This problem is similar to {@link me.ramswaroop.arrays.PairSum}. + */ +public class PairDiff { + + /** + * Using sorting. If we use Merge Sort or Heap Sort + * then (-)(nlogn) in worst case. If we use Quick Sort + * then O(n^2) in worst case. + * + * @param ar + * @param x + * @return + */ + static boolean pairDiff(int ar[], int x) { + Arrays.sort(ar); + + int len = ar.length; + + for (int i = 0, j = 1; i < len && j < len; ) { + if (i != j && ar[j] - ar[i] == x) { + return true; + } else if (ar[j] - ar[i] < x) { + j++; + } else { + i++; + } + } + return false; + } + + /** + * Using HashMap in O(n) time. + * + * @param ar + * @param x + * @param map + * @return + */ + static boolean pairDiff(int ar[], int x, Map map) { + for (int i = 0; i < ar.length; i++) { + if (map.containsKey(x + ar[i])) { + return true; + } + map.put(ar[i], 1); + } + return false; + } + + public static void main(String a[]) { + System.out.println(pairDiff(new int[]{-3, 4, -6, 1, 1}, -4)); + System.out.println(pairDiff(new int[]{3, 1}, 2)); + System.out.println(pairDiff(new int[]{-3, 4, -6, 1, 1}, -4, new HashMap())); + System.out.println(pairDiff(new int[]{3, 1}, 2, new HashMap())); + } +} From 784e16c3fca699604aaec8d0cf62b303778ba0c0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 6 Oct 2015 21:57:10 +0530 Subject: [PATCH 341/417] coded + unit tested --- .../Threads.java => threads/Basics.java} | 4 +- src/me/ramswaroop/threads/NamePrint.java | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) rename src/me/ramswaroop/{misc/Threads.java => threads/Basics.java} (94%) create mode 100644 src/me/ramswaroop/threads/NamePrint.java diff --git a/src/me/ramswaroop/misc/Threads.java b/src/me/ramswaroop/threads/Basics.java similarity index 94% rename from src/me/ramswaroop/misc/Threads.java rename to src/me/ramswaroop/threads/Basics.java index bc10a8b6..2f6a35fc 100644 --- a/src/me/ramswaroop/misc/Threads.java +++ b/src/me/ramswaroop/threads/Basics.java @@ -1,4 +1,4 @@ -package me.ramswaroop.misc; +package me.ramswaroop.threads; /** * Created by IntelliJ IDEA. @@ -7,7 +7,7 @@ * Time: 11:27 PM * To change this template go to Preferences | IDE Settings | File and Code Templates */ -public class Threads { +public class Basics { public static void main(String[] a) { Runnable r = new Runnable() { @Override diff --git a/src/me/ramswaroop/threads/NamePrint.java b/src/me/ramswaroop/threads/NamePrint.java new file mode 100644 index 00000000..4087aa97 --- /dev/null +++ b/src/me/ramswaroop/threads/NamePrint.java @@ -0,0 +1,63 @@ +package me.ramswaroop.threads; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/6/15 + * @time: 7:10 PM + */ +public class NamePrint { + + Object lock = new Object(); + + class PrintFirstName implements Runnable { + @Override + public void run() { + synchronized (lock) { + for (int i = 0; i < 100; i++) { + try { + if (i > 0) lock.wait(); // releases lock + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.print("Ram "); + lock.notify(); + } + } + } + } + + class PrintSecondName implements Runnable { + @Override + public void run() { + synchronized (lock) { + for (int i = 0; i < 100; i++) { + try { + lock.wait(); // releases lock + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Swaroop"); + lock.notify(); + } + } + } + } + + public void printNameUsingMultipleThreads() { + Runnable printFirstName = new PrintFirstName(); + Runnable printSecondName = new PrintSecondName(); + + Thread firstThread = new Thread(printFirstName); + Thread secondThread = new Thread(printSecondName); + + secondThread.start(); + firstThread.start(); + } + + public static void main(String a[]) { + NamePrint obj = new NamePrint(); + obj.printNameUsingMultipleThreads(); + } +} From 1aa2d215855a7933c2aee2a6a2aab3de26cd7577 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 6 Oct 2015 22:00:17 +0530 Subject: [PATCH 342/417] minor changes --- src/me/ramswaroop/threads/NamePrint.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/threads/NamePrint.java b/src/me/ramswaroop/threads/NamePrint.java index 4087aa97..c8aca980 100644 --- a/src/me/ramswaroop/threads/NamePrint.java +++ b/src/me/ramswaroop/threads/NamePrint.java @@ -3,6 +3,8 @@ /** * Created by IntelliJ IDEA. * + * Question: Print first name and last name (in order) using two different threads multiple times. + * * @author: ramswaroop * @date: 10/6/15 * @time: 7:10 PM @@ -28,7 +30,7 @@ public void run() { } } - class PrintSecondName implements Runnable { + class PrintLastName implements Runnable { @Override public void run() { synchronized (lock) { @@ -47,10 +49,10 @@ public void run() { public void printNameUsingMultipleThreads() { Runnable printFirstName = new PrintFirstName(); - Runnable printSecondName = new PrintSecondName(); + Runnable printLastName = new PrintLastName(); Thread firstThread = new Thread(printFirstName); - Thread secondThread = new Thread(printSecondName); + Thread secondThread = new Thread(printLastName); secondThread.start(); firstThread.start(); From 7473e9ac394f69ea466b4d399c97181691792e7e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 6 Oct 2015 22:07:07 +0530 Subject: [PATCH 343/417] added comments --- src/me/ramswaroop/threads/NamePrint.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/threads/NamePrint.java b/src/me/ramswaroop/threads/NamePrint.java index c8aca980..5d8ec677 100644 --- a/src/me/ramswaroop/threads/NamePrint.java +++ b/src/me/ramswaroop/threads/NamePrint.java @@ -2,9 +2,9 @@ /** * Created by IntelliJ IDEA. + *

+ * Question: Print first name and last name (in order) using two different threads multiple times. * - * Question: Print first name and last name (in order) using two different threads multiple times. - * * @author: ramswaroop * @date: 10/6/15 * @time: 7:10 PM @@ -54,6 +54,12 @@ public void printNameUsingMultipleThreads() { Thread firstThread = new Thread(printFirstName); Thread secondThread = new Thread(printLastName); + /** + * Starting secondThread first so that secondThread starts waiting before the firstThread + * calls notify(). But this behavior is not guaranteed as you cannot be 100% sure that + * secondThread will actually run before firstThread (though it may run before most of the + * time). + */ secondThread.start(); firstThread.start(); } From 8b97eb8628a5b6d6192463214003ed536993df4a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 7 Oct 2015 15:23:40 +0530 Subject: [PATCH 344/417] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a7afded1..201d756b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Algorithms and Data Structures in Java -The repo consists of solutions to numerous problems involving different data structures and algorithms. All solutions are coded in Java. +The repo consists of solutions to numerous problems using different data structures and algorithms, where all solutions are coded purely in Java. You can also refer my [Java Notes](http://java.ramswaroop.me) for a quick refresh on the Java concepts. ## Environment From e1379593c5ca9151a4015cc0bd02cff210159498 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 7 Oct 2015 22:12:51 +0530 Subject: [PATCH 345/417] code improvement --- src/me/ramswaroop/threads/NamePrint.java | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/me/ramswaroop/threads/NamePrint.java b/src/me/ramswaroop/threads/NamePrint.java index 5d8ec677..0d559fa8 100644 --- a/src/me/ramswaroop/threads/NamePrint.java +++ b/src/me/ramswaroop/threads/NamePrint.java @@ -12,18 +12,21 @@ public class NamePrint { Object lock = new Object(); + boolean isFirstNamePrinted = false; class PrintFirstName implements Runnable { @Override public void run() { synchronized (lock) { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < 1000; i++) { try { - if (i > 0) lock.wait(); // releases lock + // wait if first name is printed but not the last name + if (isFirstNamePrinted) lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print("Ram "); + isFirstNamePrinted = true; lock.notify(); } } @@ -34,13 +37,15 @@ class PrintLastName implements Runnable { @Override public void run() { synchronized (lock) { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < 1000; i++) { try { - lock.wait(); // releases lock + // wait if first name is not printed + if(!isFirstNamePrinted) lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Swaroop"); + isFirstNamePrinted = false; lock.notify(); } } @@ -54,14 +59,8 @@ public void printNameUsingMultipleThreads() { Thread firstThread = new Thread(printFirstName); Thread secondThread = new Thread(printLastName); - /** - * Starting secondThread first so that secondThread starts waiting before the firstThread - * calls notify(). But this behavior is not guaranteed as you cannot be 100% sure that - * secondThread will actually run before firstThread (though it may run before most of the - * time). - */ - secondThread.start(); firstThread.start(); + secondThread.start(); } public static void main(String a[]) { From 5cdd62712ba7d86714a1c1343e0d2a78b3f0ee53 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 8 Oct 2015 09:12:18 +0530 Subject: [PATCH 346/417] made the variable volatile --- src/me/ramswaroop/threads/NamePrint.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/me/ramswaroop/threads/NamePrint.java b/src/me/ramswaroop/threads/NamePrint.java index 0d559fa8..663f5773 100644 --- a/src/me/ramswaroop/threads/NamePrint.java +++ b/src/me/ramswaroop/threads/NamePrint.java @@ -12,7 +12,7 @@ public class NamePrint { Object lock = new Object(); - boolean isFirstNamePrinted = false; + volatile boolean isFirstNamePrinted = false; class PrintFirstName implements Runnable { @Override From e0c9980561e8b3c5d5e0c51360faff79033e36e6 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 8 Oct 2015 22:11:17 +0530 Subject: [PATCH 347/417] added comments --- src/me/ramswaroop/arrays/sorting/QuickSort.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/arrays/sorting/QuickSort.java b/src/me/ramswaroop/arrays/sorting/QuickSort.java index 1370a2bb..946265db 100644 --- a/src/me/ramswaroop/arrays/sorting/QuickSort.java +++ b/src/me/ramswaroop/arrays/sorting/QuickSort.java @@ -15,12 +15,13 @@ public class QuickSort { /** * In-place partition method which moves all elements smaller than * the pivot element to its left and all elements larger than the - * pivot element to its right. + * pivot element to its right and finally places the pivot element + * at its correct position. * * @param ar * @param low * @param high - * @return + * @return position of the pivot element */ public static int partition(int[] ar, int low, int high) { int pivot = high, temp; @@ -49,7 +50,7 @@ public static int partition(int[] ar, int low, int high) { /** * Recursive Quick sort. - * NOTE: This function is tail-recursive (doesn't use + * NOTE: This function is tail-recursive (doesn't use * extra stack space per recursive call). *

* Time complexity: From b0ea07b0b26989d6280b6e336e54606d8f5fa96e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 8 Oct 2015 22:15:30 +0530 Subject: [PATCH 348/417] code refactoring --- src/me/ramswaroop/trees/LeafNodes.java | 12 ++++-------- src/me/ramswaroop/trees/LeastCommonAncestor.java | 2 +- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/trees/LeafNodes.java b/src/me/ramswaroop/trees/LeafNodes.java index 0375338a..0c9f3f61 100644 --- a/src/me/ramswaroop/trees/LeafNodes.java +++ b/src/me/ramswaroop/trees/LeafNodes.java @@ -10,18 +10,14 @@ * @date: 6/26/15 * @time: 6:08 PM */ -public class LeafNodes> extends BinaryTree { +public class LeafNodes { /** * Returns the number of leaf nodes in a binary tree. * * @return */ - public int countLeafNodes() { - return countLeafNodes(root); - } - - public int countLeafNodes(BinaryNode node) { + public static > int countLeafNodes(BinaryNode node) { if (node == null) { return 0; } else if (node.left == null && node.right == null) { @@ -32,13 +28,13 @@ public int countLeafNodes(BinaryNode node) { } public static void main(String a[]) { - LeafNodes bt = new LeafNodes<>(); + BinaryTree bt = new BinaryTree<>(); bt.put(6); bt.put(3); bt.put(5); bt.put(7); bt.put(8); bt.put(9); - System.out.println(bt.countLeafNodes()); + System.out.println(countLeafNodes(bt.root)); } } diff --git a/src/me/ramswaroop/trees/LeastCommonAncestor.java b/src/me/ramswaroop/trees/LeastCommonAncestor.java index 41a48828..c8bb3a04 100644 --- a/src/me/ramswaroop/trees/LeastCommonAncestor.java +++ b/src/me/ramswaroop/trees/LeastCommonAncestor.java @@ -12,7 +12,7 @@ * @date: 6/26/15 * @time: 7:38 PM */ -public class LeastCommonAncestor> extends BinarySearchTree { +public class LeastCommonAncestor { public void leastCommonAncestor() { From f05e2656974ebd7b1fc7fc2e54818c95ba0a699f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 14:33:23 +0530 Subject: [PATCH 349/417] added example --- .../MinimumJumpsToReachEnd.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java b/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java index 94301e56..074ccaf3 100644 --- a/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java +++ b/src/me/ramswaroop/dynamicprogramming/MinimumJumpsToReachEnd.java @@ -10,17 +10,17 @@ public class MinimumJumpsToReachEnd { /** - * Given an array of integers where each element represents the max number of steps that - * can be made forward from that element. Write a function to return the minimum number - * of jumps to reach the end of the array (starting from the first element). If an element + * Given an array of integers where each element represents the max number of steps that + * can be made forward from that element. Write a function to return the minimum number + * of jumps to reach the end of the array (starting from the first element). If an element * is 0, then we cannot move through that element. - * + *

* A naive approach is to start from the first element and recursively call for all the elements * reachable from first element. The minimum number of jumps to reach end from first can be calculated * using minimum number of jumps needed to reach end from the elements reachable from first. - * + *

* minJumps(start, end) = Min ( minJumps(k, end) ) for all k reachable from start - * + * * @param a * @param l * @param h @@ -40,7 +40,7 @@ public static int getMinimumJumpsToReachEndNaive(int[] a, int l, int h) { } return minJumps; } - + // TODO dp approach public static void main(String a[]) { @@ -52,5 +52,7 @@ public static void main(String a[]) { System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); ar = new int[]{1, 2}; System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); + ar = new int[]{1, 1, 1, 1, 1}; + System.out.println(getMinimumJumpsToReachEndNaive(ar, 0, ar.length - 1)); } } From 045d28885e3a9cc25b5b32dfc15e7efeeba2db71 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 19:52:10 +0530 Subject: [PATCH 350/417] code refactoring --- src/me/ramswaroop/common/BinarySearchTree.java | 4 ++-- src/me/ramswaroop/common/BinaryTree.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/me/ramswaroop/common/BinarySearchTree.java b/src/me/ramswaroop/common/BinarySearchTree.java index 37093271..1333eaef 100644 --- a/src/me/ramswaroop/common/BinarySearchTree.java +++ b/src/me/ramswaroop/common/BinarySearchTree.java @@ -18,8 +18,8 @@ public class BinarySearchTree> extends BinaryTree { * * @param value */ - public void put(E value) { - put(root, value); + public BinaryNode put(E value) { + return put(root, value); } public BinaryNode put(BinaryNode node, E value) { diff --git a/src/me/ramswaroop/common/BinaryTree.java b/src/me/ramswaroop/common/BinaryTree.java index 4019fea5..0158282f 100644 --- a/src/me/ramswaroop/common/BinaryTree.java +++ b/src/me/ramswaroop/common/BinaryTree.java @@ -20,8 +20,8 @@ public class BinaryTree> extends Tree { * * @param value */ - public void put(E value) { - put(root, value); + public BinaryNode put(E value) { + return put(root, value); } public BinaryNode put(BinaryNode node, E value) { From c36665d828d969313e1131e228e37142eac03a25 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 20:38:03 +0530 Subject: [PATCH 351/417] code refactoring --- src/me/ramswaroop/common/BinaryTree.java | 27 +++++++++---- src/me/ramswaroop/trees/CheckForBST.java | 49 ++++++++++++------------ 2 files changed, 44 insertions(+), 32 deletions(-) diff --git a/src/me/ramswaroop/common/BinaryTree.java b/src/me/ramswaroop/common/BinaryTree.java index 0158282f..d43ee677 100644 --- a/src/me/ramswaroop/common/BinaryTree.java +++ b/src/me/ramswaroop/common/BinaryTree.java @@ -4,10 +4,11 @@ /** * Created by IntelliJ IDEA. - * User: ramswaroop - * Date: 4/19/15 - * Time: 6:35 PM - * To change this template go to Preferences | IDE Settings | File and Code Templates + * + * @author: ramswaroop + * @date: 4/19/15 + * @time: 6:35 PM + * @see: https://www.cs.bu.edu/teaching/c/tree/breadth-first/ */ public class BinaryTree> extends Tree { @@ -151,7 +152,7 @@ public void delete(E value) { * * @param node */ - public void deleteChildrens(BinaryNode node) { + public void deleteChildren(BinaryNode node) { if (node == null) { return; } @@ -238,9 +239,10 @@ public int width(BinaryNode node, int width) { if (node.left == null && node.right == null) return 1; // for single/leaf node - int level_width = width(node.left, width) + width(node.right, width); + int levelWidth = width(node.left, width) + width(node.right, width); - if (level_width > width) width = level_width; + // to find max width + if (levelWidth > width) width = levelWidth; return width; } @@ -250,4 +252,15 @@ public void printValue(BinaryNode node) { out.print(node.value); } + + // test cases + public static void main(String[] a) { + BinaryTree bt = new BinaryTree<>(); + bt.put(1); + bt.put(2); + bt.put(3); + bt.put(4); + bt.put(5); + bt.breadthFirstTraversal(); + } } diff --git a/src/me/ramswaroop/trees/CheckForBST.java b/src/me/ramswaroop/trees/CheckForBST.java index 7335ff63..2f8aaeb2 100644 --- a/src/me/ramswaroop/trees/CheckForBST.java +++ b/src/me/ramswaroop/trees/CheckForBST.java @@ -1,6 +1,7 @@ package me.ramswaroop.trees; import me.ramswaroop.common.BinaryNode; +import me.ramswaroop.common.BinarySearchTree; import me.ramswaroop.common.BinaryTree; import java.util.List; @@ -13,22 +14,11 @@ * @author: ramswaroop * @date: 6/26/15 * @time: 7:14 PM + * + * Concept: Perform in-order traversal of the tree and if + * the result isn't in ascending order then returns false. */ -public class CheckForBST> extends BinaryTree { - - /** - * Checks whether the binary tree is a BST or not. - *

- * Approach: Performs in-order traversal of the tree and if - * the result isn't in ascending order then returns false. - * - * @return - */ - public boolean isBST() { - //List> list = new ArrayList<>(); - BinaryNode prev = new BinaryNode<>(null); - return isBST(root, prev); - } +public class CheckForBST { /** * Traverse the tree in in-order fashion and insert all nodes @@ -38,7 +28,7 @@ public boolean isBST() { * @param list * @return */ - public boolean isBST(BinaryNode node, List> list) { + public static > boolean isBST(BinaryNode node, List> list) { if (node == null) return true; boolean left = isBST(node.left, list); @@ -62,7 +52,7 @@ public boolean isBST(BinaryNode node, List> list) { * @param prev * @return */ - public boolean isBST(BinaryNode node, BinaryNode prev) { + public static > boolean isBST(BinaryNode node, BinaryNode prev) { if (node == null) return true; boolean left = isBST(node.left, prev); @@ -79,14 +69,23 @@ public boolean isBST(BinaryNode node, BinaryNode prev) { } public static void main(String a[]) { - CheckForBST bt = new CheckForBST<>(); - bt.put(6); - bt.put(3); - bt.put(5); - bt.put(7); - bt.put(8); - bt.put(9); + BinarySearchTree binarySearchTree = new BinarySearchTree<>(); + binarySearchTree.put(6); + binarySearchTree.put(3); + binarySearchTree.put(5); + binarySearchTree.put(7); + binarySearchTree.put(8); + binarySearchTree.put(9); + out.println("Is BST: "); + out.println(isBST(binarySearchTree.root, new BinaryNode(null))); + BinaryTree binaryTree = new BinaryTree<>(); + binaryTree.put(6); + binaryTree.put(3); + binaryTree.put(5); + binaryTree.put(7); + binaryTree.put(8); + binaryTree.put(9); out.println("Is BST: "); - out.println(bt.isBST()); + out.println(isBST(binaryTree.root, new BinaryNode(null))); } } From a8d36b4d65b59777c82a8e7bff9ee67a62388d9b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 20:50:17 +0530 Subject: [PATCH 352/417] code refactoring --- src/me/ramswaroop/trees/BFSUsingQueue.java | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/me/ramswaroop/trees/BFSUsingQueue.java b/src/me/ramswaroop/trees/BFSUsingQueue.java index 7a161da0..992f2e17 100644 --- a/src/me/ramswaroop/trees/BFSUsingQueue.java +++ b/src/me/ramswaroop/trees/BFSUsingQueue.java @@ -7,6 +7,8 @@ import java.util.NoSuchElementException; +import static java.lang.System.out; + /** * Created by IntelliJ IDEA. * @@ -14,17 +16,18 @@ * @date: 6/26/15 * @time: 7:34 PM */ -public class BFSUsingQueue> extends BinaryTree { +public class BFSUsingQueue { /** * Breadth first traversal (Level-order traversal using Queue). */ - public void breadthFirstTraversalUsingQueue() { + public static > void breadthFirstTraversalUsingQueue(BinaryNode node) { Queue> queue = new LinkedQueue<>(); - breadthFirstTraversalUsingQueue(root, queue); + breadthFirstTraversalUsingQueue(node, queue); } - public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue> queue) { + public static > void breadthFirstTraversalUsingQueue(BinaryNode node, + Queue> queue) { if (node != null) { printValue(node); @@ -39,14 +42,20 @@ public void breadthFirstTraversalUsingQueue(BinaryNode node, Queue> void printValue(BinaryNode node) { + if (node == null) return; + + out.print(node.value); + } + public static void main(String a[]) { - BFSUsingQueue bt = new BFSUsingQueue<>(); + BinaryTree bt = new BinaryTree<>(); bt.put(6); bt.put(3); bt.put(5); bt.put(7); bt.put(8); bt.put(9); - bt.breadthFirstTraversalUsingQueue(); + breadthFirstTraversalUsingQueue(bt.root); } } From d47ea5fd343357a615b264103501555ebb05f648 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 21:12:40 +0530 Subject: [PATCH 353/417] code refactoring --- src/me/ramswaroop/trees/ChildrenSum.java | 42 ++++++++++-------------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/me/ramswaroop/trees/ChildrenSum.java b/src/me/ramswaroop/trees/ChildrenSum.java index 8b0f8a36..88e0cef7 100644 --- a/src/me/ramswaroop/trees/ChildrenSum.java +++ b/src/me/ramswaroop/trees/ChildrenSum.java @@ -12,20 +12,18 @@ * @date: 6/26/15 * @time: 7:01 PM */ -public class ChildrenSum> extends BinaryTree { +public class ChildrenSum { /** * Children Sum Invariant: For every node, the value must be equal to * sum of values in the left and right child. * Consider data value as 0 for NULL child. * + * @param node + * @param * @return */ - public boolean isChildrenSum() { - return isChildrenSum(root); - } - - public boolean isChildrenSum(BinaryNode node) { + public static > boolean isChildrenSum(BinaryNode node) { if (node == null || node.left == null && node.right == null) return true; E leftChildValue = (E) (node.left == null ? 0 : node.left.value); @@ -41,18 +39,18 @@ public boolean isChildrenSum(BinaryNode node) { return isChildrenSum(node.left) && isChildrenSum(node.right); } + /** * Converts a tree to hold the children sum invariant. *

* It only increments data values in any node (Does not * change structure of tree and cannot decrement value of * any node). + * + * @param node + * @param */ - public void toChildrenSum() { - toChildrenSum(root); - } - - public void toChildrenSum(BinaryNode node) { + public static > void toChildrenSum(BinaryNode node) { if (node == null || node.left == null && node.right == null) return; @@ -63,32 +61,28 @@ public void toChildrenSum(BinaryNode node) { Integer leftChildValue = (Integer) (node.left == null ? 0 : node.left.value); Integer rightChildValue = (Integer) (node.right == null ? 0 : node.right.value); - int diff = (nodeValue - (leftChildValue + rightChildValue)); + int diff = leftChildValue + rightChildValue - nodeValue; if (diff < 0) { - increment(node, diff); + increment(node, -diff); } else if (diff > 0) { - if (node.left != null) { - increment(node.left, diff); - } else { - increment(node.right, diff); - } + //node.value += diff; } } - // TODO - private void increment(BinaryNode node, int diff) { + // TODO: Not done due to generics + private static > void increment(BinaryNode node, int diff) { if (node.left != null) { - //node.value += Math.abs(diff); + //node.left.value += Math.abs(diff); increment(node.left, diff); } else if (node.right != null) { - //node.value += Math.abs(diff); + //node.right.value += Math.abs(diff); increment(node.right, diff); } } public static void main(String a[]) { - ChildrenSum bt = new ChildrenSum<>(); + BinaryTree bt = new BinaryTree<>(); bt.put(6); bt.put(3); bt.put(5); @@ -96,7 +90,7 @@ public static void main(String a[]) { bt.put(8); bt.put(9); out.println("Is Children Sum : "); - out.println(bt.isChildrenSum()); + out.println(isChildrenSum(bt.root)); /*binaryTree.toChildrenSum(); out.print("\nBreadth-first Traversal after to children sum: "); binaryTree.breadthFirstTraversal();*/ From 857100510f089ed8f7bf8617ccb5ab55b1fedf14 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 21:15:08 +0530 Subject: [PATCH 354/417] added comments --- src/me/ramswaroop/trees/ChildrenSum.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/trees/ChildrenSum.java b/src/me/ramswaroop/trees/ChildrenSum.java index 88e0cef7..28e90a6c 100644 --- a/src/me/ramswaroop/trees/ChildrenSum.java +++ b/src/me/ramswaroop/trees/ChildrenSum.java @@ -63,9 +63,9 @@ public static > void toChildrenSum(BinaryNode node) { int diff = leftChildValue + rightChildValue - nodeValue; - if (diff < 0) { + if (diff < 0) { // tricky: children sum is less increment(node, -diff); - } else if (diff > 0) { + } else if (diff > 0) { // simple: children sum is more, so just add the diff to parent node //node.value += diff; } } From a6c337d2f47268391852608cf282bab05964a8c2 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 21:22:13 +0530 Subject: [PATCH 355/417] code refactoring --- .../trees/ConstructTreeFromInorderAndPreorder.java | 6 +++--- src/me/ramswaroop/trees/DoubleTree.java | 14 ++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java index cefee4b9..408eb573 100644 --- a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java +++ b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java @@ -1,7 +1,6 @@ package me.ramswaroop.trees; import me.ramswaroop.common.BinaryNode; -import me.ramswaroop.common.BinaryTree; import java.util.List; @@ -12,9 +11,10 @@ * @date: 6/26/15 * @time: 5:34 PM */ -public class ConstructTreeFromInorderAndPreorder> extends BinaryTree { +public class ConstructTreeFromInOrderAndPreorder { - public void constructTreeWithInOrderAndPreOrder(List> inOrder, List> preOrder) { + public > void constructTreeWithInOrderAndPreOrder(List> inOrder, + List> preOrder) { for (int i = 0; i < preOrder.size(); i++) { } diff --git a/src/me/ramswaroop/trees/DoubleTree.java b/src/me/ramswaroop/trees/DoubleTree.java index ca276e5b..6b1b9bc7 100644 --- a/src/me/ramswaroop/trees/DoubleTree.java +++ b/src/me/ramswaroop/trees/DoubleTree.java @@ -12,18 +12,16 @@ * @date: 6/26/15 * @time: 6:02 PM */ -public class DoubleTree> extends BinaryTree { +public class DoubleTree { /** * Converts a given tree to its Double tree. To create a Double tree * of the given tree, create a new duplicate for each node, and insert * the duplicate as the left child of the original node. + * + * @param node */ - public void doubleTree() { - doubleTree(root); - } - - public void doubleTree(BinaryNode node) { + public static > void doubleTree(BinaryNode node) { if (node == null) return; BinaryNode newNode = new BinaryNode<>(node.value, node.left, null); @@ -35,7 +33,7 @@ public void doubleTree(BinaryNode node) { } public static void main(String a[]) { - DoubleTree bt = new DoubleTree<>(); + BinaryTree bt = new BinaryTree<>(); bt.put(6); bt.put(3); bt.put(5); @@ -44,7 +42,7 @@ public static void main(String a[]) { bt.put(9); bt.breadthFirstTraversal(); out.println(); - bt.doubleTree(); + doubleTree(bt.root); out.println("BFS after Double tree: "); bt.breadthFirstTraversal(); } From f5b3b5bf8edf2f077b5aa4fce2b07ddacbae00a5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 9 Oct 2015 22:41:33 +0530 Subject: [PATCH 356/417] code refactoring --- src/me/ramswaroop/trees/IdenticalTrees.java | 14 +------------- src/me/ramswaroop/trees/InOrderUsingStack.java | 12 ++++-------- 2 files changed, 5 insertions(+), 21 deletions(-) diff --git a/src/me/ramswaroop/trees/IdenticalTrees.java b/src/me/ramswaroop/trees/IdenticalTrees.java index 2236ad16..1af666e0 100644 --- a/src/me/ramswaroop/trees/IdenticalTrees.java +++ b/src/me/ramswaroop/trees/IdenticalTrees.java @@ -2,7 +2,6 @@ import me.ramswaroop.common.BinaryNode; import me.ramswaroop.common.BinarySearchTree; -import me.ramswaroop.common.BinaryTree; import static java.lang.System.out; @@ -13,18 +12,7 @@ * @date: 6/26/15 * @time: 5:36 PM */ -public class IdenticalTrees> extends BinaryTree { - - /** - * Checks whether this tree and another with {@param node} - * as root are identical or not. - * - * @param node - * @return - */ - public boolean isIdentical(BinaryNode node) { - return isIdentical(this.root, node); - } +public class IdenticalTrees { /** * Checks whether two trees having their roots at node1 and node2 diff --git a/src/me/ramswaroop/trees/InOrderUsingStack.java b/src/me/ramswaroop/trees/InOrderUsingStack.java index ce580e99..f9eb8dbf 100644 --- a/src/me/ramswaroop/trees/InOrderUsingStack.java +++ b/src/me/ramswaroop/trees/InOrderUsingStack.java @@ -14,18 +14,14 @@ * @date: 6/26/15 * @time: 7:31 PM */ -public class InOrderUsingStack> extends BinarySearchTree { - - public void inOrder() { - inOrderUsingStack(root); - } +public class InOrderUsingStack { /** * In-order traversal of tree using one stack and without recursion. * * @param node */ - public void inOrderUsingStack(BinaryNode node) { + public static > void inOrderUsingStack(BinaryNode node) { if (node == null) return; Stack> stack = new LinkedStack<>(); @@ -48,13 +44,13 @@ public void inOrderUsingStack(BinaryNode node) { } public static void main(String a[]) { - InOrderUsingStack bst = new InOrderUsingStack<>(); + BinarySearchTree bst = new BinarySearchTree<>(); bst.put(6); bst.put(3); bst.put(5); bst.put(7); bst.put(8); bst.put(9); - bst.inOrder(); + inOrderUsingStack(bst.root); } } From 12b3e04964149350303ee221912930bb8ec626a4 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 10 Oct 2015 00:33:52 +0530 Subject: [PATCH 357/417] code refactoring --- src/me/ramswaroop/common/BinaryTree.java | 33 +++++++++++--------- src/me/ramswaroop/trees/MirrorTree.java | 15 +++------ src/me/ramswaroop/trees/RootToLeafPaths.java | 2 +- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/me/ramswaroop/common/BinaryTree.java b/src/me/ramswaroop/common/BinaryTree.java index d43ee677..b7102d01 100644 --- a/src/me/ramswaroop/common/BinaryTree.java +++ b/src/me/ramswaroop/common/BinaryTree.java @@ -106,28 +106,28 @@ public void postOrder(BinaryNode node) { * DEF: Breadth-first search (BFS) is an algorithm for traversing or searching tree * or graph data structures. It starts at the tree root (or some arbitrary node of a * graph, sometimes referred to as a `search key'[1]) and explores the neighbor nodes - * first, before moving to the next level neighbors. + * first, before moving to the next level neighbors. See {@link me.ramswaroop.trees.BFSUsingQueue} + * for a O(n) solution. + * + * Time complexity: O(n^2) */ public void breadthFirstTraversal() { // assuming level starts at zero - breadthFirstTraversal(root, 0); + for (int level = 0; level < height(root); level++) { + printLevel(root, level); + } } - // todo need to correct, failing in some cases - public void breadthFirstTraversal(BinaryNode node, int level) { + public void printLevel(BinaryNode node, int level) { if (node == null) return; // print the starting node - if (level == 0) printValue(node); - - // print the neighbour nodes - printValue(node.left); - printValue(node.right); - - // go to next level - level++; - breadthFirstTraversal(node.left, level); - breadthFirstTraversal(node.right, level); + if (level == 0) { + printValue(node); + } else { // print the neighbour nodes + printLevel(node.left, level - 1); + printLevel(node.right, level - 1); + } } /** @@ -261,6 +261,11 @@ public static void main(String[] a) { bt.put(3); bt.put(4); bt.put(5); + bt.put(6); + bt.put(7); + bt.put(8); bt.breadthFirstTraversal(); + out.println(); + bt.inOrder(); } } diff --git a/src/me/ramswaroop/trees/MirrorTree.java b/src/me/ramswaroop/trees/MirrorTree.java index f9b05c60..479c92cb 100644 --- a/src/me/ramswaroop/trees/MirrorTree.java +++ b/src/me/ramswaroop/trees/MirrorTree.java @@ -10,7 +10,7 @@ * @date: 6/26/15 * @time: 7:03 PM */ -public class MirrorTree> extends BinaryTree { +public class MirrorTree { /** * Converts a Tree to its Mirror Tree. @@ -21,27 +21,22 @@ public class MirrorTree> extends BinaryTree { * TIP: In-order traversal of mirror tree is exactly the * reverse of the in-order traversal of the original tree. */ - public void mirror() { - mirror(root); - } - - public void mirror(BinaryNode node) { + public static > void mirror(BinaryNode node) { if (node == null) return; - BinaryNode tempNode; - // mirror sub-trees mirror(node.left); mirror(node.right); // swap nodes + BinaryNode tempNode; tempNode = node.left; node.left = node.right; node.right = tempNode; } public static void main(String a[]) { - MirrorTree bt = new MirrorTree<>(); + BinaryTree bt = new BinaryTree<>(); bt.put(6); bt.put(3); bt.put(5); @@ -51,7 +46,7 @@ public static void main(String a[]) { System.out.println("Original Tree"); bt.breadthFirstTraversal(); System.out.println("\nMirror Tree"); - bt.mirror(); + mirror(bt.root); bt.breadthFirstTraversal(); } } diff --git a/src/me/ramswaroop/trees/RootToLeafPaths.java b/src/me/ramswaroop/trees/RootToLeafPaths.java index f3d76931..593f6472 100644 --- a/src/me/ramswaroop/trees/RootToLeafPaths.java +++ b/src/me/ramswaroop/trees/RootToLeafPaths.java @@ -93,7 +93,7 @@ public boolean rootToLeafPathsSum(BinaryNode node, List pathList, int path if (node != null) pathList.add(node.value); - // if its either a leaf node or null then path is complete, add all in the list + // if its either a leaf node or null then path is complete, add all elements present in list if (node == null || (node.left == null && node.right == null)) { for (int i = 0; i < pathList.size(); i++) { sum += Integer.parseInt(pathList.get(i).toString()); From fce07a10c8af8b8dcadbbac786c2f352c28b16a0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 11 Oct 2015 17:41:46 +0530 Subject: [PATCH 358/417] code refactoring --- .../LargestProductContiguousSubArray.java | 25 +++++++++++++++ .../ramswaroop/arrays/Segregate0s1sAnd2s.java | 22 +++++++------ .../linkedlists/SegregateEvenOddNumbers.java | 2 +- src/me/ramswaroop/misc/Outer.java | 32 +++++++++++++++++++ .../InorderWithoutStackAndRecursion.java | 4 +-- 5 files changed, 73 insertions(+), 12 deletions(-) create mode 100644 src/me/ramswaroop/arrays/LargestProductContiguousSubArray.java create mode 100644 src/me/ramswaroop/misc/Outer.java diff --git a/src/me/ramswaroop/arrays/LargestProductContiguousSubArray.java b/src/me/ramswaroop/arrays/LargestProductContiguousSubArray.java new file mode 100644 index 00000000..367c5541 --- /dev/null +++ b/src/me/ramswaroop/arrays/LargestProductContiguousSubArray.java @@ -0,0 +1,25 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 5/28/15 + * @time: 12:44 PM + */ +public class LargestProductContiguousSubArray { + + /** + * + * @param a + * @return + */ + public static int getLargestProductContiguousSubArray(int[] a) { + return 0; + } + + public static void main(String a[]) { + System.out.println(getLargestProductContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4})); + System.out.println(getLargestProductContiguousSubArray(new int[]{6, -3, -10, 0, 2})); + } +} diff --git a/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java b/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java index 266b6350..e0e767c5 100644 --- a/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java +++ b/src/me/ramswaroop/arrays/Segregate0s1sAnd2s.java @@ -50,16 +50,20 @@ public static void main(String a[]) { segregate0s1sAnd2s(ar); System.out.println(Arrays.toString(ar)); - int[] ar1 = new int[]{0, 2, 1, 1, 2, 0}; - segregate0s1sAnd2s(ar1); - System.out.println(Arrays.toString(ar1)); + ar = new int[]{0, 2, 1, 1, 2, 0}; + segregate0s1sAnd2s(ar); + System.out.println(Arrays.toString(ar)); - int[] ar2 = new int[]{0, 1, 2}; - segregate0s1sAnd2s(ar2); - System.out.println(Arrays.toString(ar2)); + ar = new int[]{0, 1, 2}; + segregate0s1sAnd2s(ar); + System.out.println(Arrays.toString(ar)); - int[] ar3 = new int[]{2, 1, 0, 2, 1, 0}; - segregate0s1sAnd2s(ar3); - System.out.println(Arrays.toString(ar3)); + ar = new int[]{2, 1, 0, 2, 1, 0}; + segregate0s1sAnd2s(ar); + System.out.println(Arrays.toString(ar)); + + ar = new int[]{1, 2, 1, 0, 2, 1, 0}; + segregate0s1sAnd2s(ar); + System.out.println(Arrays.toString(ar)); } } diff --git a/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java b/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java index 61ccb58b..acccfb46 100644 --- a/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java +++ b/src/me/ramswaroop/linkedlists/SegregateEvenOddNumbers.java @@ -21,7 +21,7 @@ public class SegregateEvenOddNumbers { * 1) Make a pointer point the last node of the list. *

* 2) Traverse the linked list from start and append all odd values - * nodes to the end the above pointer. + * nodes to the end of the above pointer. *

* 3) If the pointer in step 1 points to a odd valued node then move it * to the end so that the relative order of nodes remains unchanged. diff --git a/src/me/ramswaroop/misc/Outer.java b/src/me/ramswaroop/misc/Outer.java new file mode 100644 index 00000000..96ad1124 --- /dev/null +++ b/src/me/ramswaroop/misc/Outer.java @@ -0,0 +1,32 @@ +package me.ramswaroop.misc; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 9/30/15 + * @time: 9:37 AM + */ +class BigOuter { + static class Nest { + void go() { + System.out.println("hi"); + } + } +} + +public class Outer { + static class B2 { + void goB2() { + System.out.println("hi 2"); + } + } + + public static void main(String[] args) { + BigOuter.Nest n = new BigOuter.Nest(); + n.go(); + B2 b2 = new B2(); + b2.goB2(); + //B2.goB2(); not possible + } +} diff --git a/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java b/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java index 4e34dcff..2664cc8b 100644 --- a/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java +++ b/src/me/ramswaroop/trees/InorderWithoutStackAndRecursion.java @@ -32,10 +32,10 @@ public void inOrder() { * 2. While current is not NULL * If current does not have left child * a) Print current’s data - * b) Go to the right, i.e., current = current->right + * b) Go to right child, i.e., current = current->right * Else * a) Make current as right child of the rightmost node in current's left subtree - * b) Go to this left child, i.e., current = current->left + * b) Go to left child, i.e., current = current->left * * @param node */ From 99ac232e9eb73d3123d2685c32f946397f036f1c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 11 Oct 2015 20:46:59 +0530 Subject: [PATCH 359/417] anagrams lexicographically done --- ...amsTogether.java => AnagramsTogether.java} | 2 +- .../AnagramsTogetherLexicographically.java | 55 +++++++++++++++++++ src/me/ramswaroop/misc/ArraySum.java | 46 ++++++++++++++++ 3 files changed, 102 insertions(+), 1 deletion(-) rename src/me/ramswaroop/arrays/{PrintAnagramsTogether.java => AnagramsTogether.java} (96%) create mode 100644 src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java create mode 100644 src/me/ramswaroop/misc/ArraySum.java diff --git a/src/me/ramswaroop/arrays/PrintAnagramsTogether.java b/src/me/ramswaroop/arrays/AnagramsTogether.java similarity index 96% rename from src/me/ramswaroop/arrays/PrintAnagramsTogether.java rename to src/me/ramswaroop/arrays/AnagramsTogether.java index 050bedce..b90dfa9a 100644 --- a/src/me/ramswaroop/arrays/PrintAnagramsTogether.java +++ b/src/me/ramswaroop/arrays/AnagramsTogether.java @@ -9,7 +9,7 @@ * @date: 9/23/15 * @time: 8:11 PM */ -public class PrintAnagramsTogether { +public class AnagramsTogether { public static void printAnagramsTogether(String[] s) { diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java new file mode 100644 index 00000000..d321bc28 --- /dev/null +++ b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java @@ -0,0 +1,55 @@ +package me.ramswaroop.arrays; + +import java.util.*; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/11/15 + * @time: 7:56 PM + */ +public class AnagramsTogetherLexicographically { + + public static void printAnagramsTogether(String[] s) { + + TreeMap> treeMap = new TreeMap<>(); + + for (int i = 0; i < s.length; i++) { + String removeSpaces = s[i].replaceAll("\\s+", ""); + char[] chars = removeSpaces.toCharArray(); + Arrays.sort(chars); + + List indexes = treeMap.get(String.valueOf(chars)); + if (indexes == null) { + indexes = new ArrayList<>(); + } + indexes.add(i); + treeMap.put(String.valueOf(chars), indexes); + } + + for (Map.Entry> entry : treeMap.entrySet()) { + List anagrams = new ArrayList<>(); + for (int i = 0; i < entry.getValue().size(); i++) { + anagrams.add(s[entry.getValue().get(i)]); + } + + // print list + Collections.sort(anagrams); + for (int i = 0; i < anagrams.size(); i++) { + System.out.print(anagrams.get(i)); + if (anagrams.size() - i > 1) System.out.print(","); + } + System.out.println(); + } + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + List strings = new ArrayList<>(); + while (in.hasNextLine()) { + strings.add(in.nextLine()); + } + printAnagramsTogether(strings.toArray(new String[0])); + } +} diff --git a/src/me/ramswaroop/misc/ArraySum.java b/src/me/ramswaroop/misc/ArraySum.java new file mode 100644 index 00000000..1c608908 --- /dev/null +++ b/src/me/ramswaroop/misc/ArraySum.java @@ -0,0 +1,46 @@ +package me.ramswaroop.misc; + +import java.util.Arrays; +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/11/15 + * @time: 7:26 PM + */ +public class ArraySum { + + public static int doesPairExistsWithSum(int[] a, int sum) { + Arrays.sort(a); + + int len = a.length; + + for (int i = 0, j = len - 1; i < j; ) { + if (a[i] + a[j] == sum) { + return 1; + } else if (a[i] + a[j] < sum) { // approach towards larger elements + i++; + } else { // approach towards smaller elements + j--; + } + } + return 0; + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + int sum = Integer.parseInt(in.nextLine()); + int length = Integer.parseInt(in.nextLine()); + + int[] in_ar = new int[length]; + + for (int i = 0; i < length; i++) { + in_ar[i] = Integer.parseInt(in.nextLine()); + } + + System.out.println(doesPairExistsWithSum(in_ar, sum)); + } +} From 953c818e21d9859be6e777642234372eadd7ff1a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 11 Oct 2015 20:48:51 +0530 Subject: [PATCH 360/417] added todo --- .../ramswaroop/arrays/AnagramsTogetherLexicographically.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java index d321bc28..658c73d4 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java +++ b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java @@ -11,6 +11,7 @@ */ public class AnagramsTogetherLexicographically { + // todo lexicographic for the entire output public static void printAnagramsTogether(String[] s) { TreeMap> treeMap = new TreeMap<>(); @@ -34,8 +35,9 @@ public static void printAnagramsTogether(String[] s) { anagrams.add(s[entry.getValue().get(i)]); } - // print list + // print anagrams lexicographically within a single line Collections.sort(anagrams); + for (int i = 0; i < anagrams.size(); i++) { System.out.print(anagrams.get(i)); if (anagrams.size() - i > 1) System.out.print(","); From ca58b6d2aae0fc6b5500cdefb7cf817b0fbe25ee Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 11 Oct 2015 22:27:06 +0530 Subject: [PATCH 361/417] anagrams todo done --- .../AnagramsTogetherLexicographically.java | 36 ++++++++++----- src/me/ramswaroop/misc/ArraySum.java | 46 ------------------- 2 files changed, 24 insertions(+), 58 deletions(-) delete mode 100644 src/me/ramswaroop/misc/ArraySum.java diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java index 658c73d4..190c16fd 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java +++ b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java @@ -11,38 +11,50 @@ */ public class AnagramsTogetherLexicographically { - // todo lexicographic for the entire output + /** + * + * @param s + */ public static void printAnagramsTogether(String[] s) { - TreeMap> treeMap = new TreeMap<>(); - + HashMap> hashMap = new HashMap<>(); + List> output = new ArrayList<>(); + for (int i = 0; i < s.length; i++) { String removeSpaces = s[i].replaceAll("\\s+", ""); char[] chars = removeSpaces.toCharArray(); Arrays.sort(chars); - List indexes = treeMap.get(String.valueOf(chars)); + List indexes = hashMap.get(String.valueOf(chars)); if (indexes == null) { indexes = new ArrayList<>(); } indexes.add(i); - treeMap.put(String.valueOf(chars), indexes); + hashMap.put(String.valueOf(chars), indexes); } - for (Map.Entry> entry : treeMap.entrySet()) { + for (Map.Entry> entry : hashMap.entrySet()) { + List anagrams = new ArrayList<>(); + for (int i = 0; i < entry.getValue().size(); i++) { anagrams.add(s[entry.getValue().get(i)]); } - // print anagrams lexicographically within a single line + // arrange anagrams lexicographically within a single line Collections.sort(anagrams); - - for (int i = 0; i < anagrams.size(); i++) { - System.out.print(anagrams.get(i)); - if (anagrams.size() - i > 1) System.out.print(","); + output.add(anagrams); + } + + Collections.sort(output, new Comparator>() { + @Override + public int compare(List o1, List o2) { + return o1.get(0).compareTo(o2.get(0)); } - System.out.println(); + }); + + for (int i = 0; i < output.size(); i++) { + System.out.println(output.get(i)); } } diff --git a/src/me/ramswaroop/misc/ArraySum.java b/src/me/ramswaroop/misc/ArraySum.java deleted file mode 100644 index 1c608908..00000000 --- a/src/me/ramswaroop/misc/ArraySum.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.ramswaroop.misc; - -import java.util.Arrays; -import java.util.Scanner; - -/** - * Created by IntelliJ IDEA. - * - * @author: ramswaroop - * @date: 10/11/15 - * @time: 7:26 PM - */ -public class ArraySum { - - public static int doesPairExistsWithSum(int[] a, int sum) { - Arrays.sort(a); - - int len = a.length; - - for (int i = 0, j = len - 1; i < j; ) { - if (a[i] + a[j] == sum) { - return 1; - } else if (a[i] + a[j] < sum) { // approach towards larger elements - i++; - } else { // approach towards smaller elements - j--; - } - } - return 0; - } - - public static void main(String a[]) { - Scanner in = new Scanner(System.in); - - int sum = Integer.parseInt(in.nextLine()); - int length = Integer.parseInt(in.nextLine()); - - int[] in_ar = new int[length]; - - for (int i = 0; i < length; i++) { - in_ar[i] = Integer.parseInt(in.nextLine()); - } - - System.out.println(doesPairExistsWithSum(in_ar, sum)); - } -} From 3307380ab8446c5be98d9dc00b8627e2e54a5252 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 11 Oct 2015 22:33:36 +0530 Subject: [PATCH 362/417] made changes to make it runnable in intellij idea ide --- .../AnagramsTogetherLexicographically.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java index 190c16fd..cb7a1ca9 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java +++ b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java @@ -12,14 +12,16 @@ public class AnagramsTogetherLexicographically { /** - * + * Prints anagrams in groups where the groups are arranged lexicographically + * and the strings within each group is also arranged lexicographically. + * * @param s */ public static void printAnagramsTogether(String[] s) { HashMap> hashMap = new HashMap<>(); List> output = new ArrayList<>(); - + for (int i = 0; i < s.length; i++) { String removeSpaces = s[i].replaceAll("\\s+", ""); char[] chars = removeSpaces.toCharArray(); @@ -34,9 +36,9 @@ public static void printAnagramsTogether(String[] s) { } for (Map.Entry> entry : hashMap.entrySet()) { - + List anagrams = new ArrayList<>(); - + for (int i = 0; i < entry.getValue().size(); i++) { anagrams.add(s[entry.getValue().get(i)]); } @@ -52,17 +54,19 @@ public int compare(List o1, List o2) { return o1.get(0).compareTo(o2.get(0)); } }); - + for (int i = 0; i < output.size(); i++) { - System.out.println(output.get(i)); + System.out.println(output.get(i)); } } public static void main(String a[]) { Scanner in = new Scanner(System.in); List strings = new ArrayList<>(); - while (in.hasNextLine()) { - strings.add(in.nextLine()); + String s; + // you should use in.hasNextLine() + while (!(s = in.nextLine()).trim().equals("")) { + strings.add(s); } printAnagramsTogether(strings.toArray(new String[0])); } From 1d045f0d3fe756350d5721995116740d41958b70 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 11 Oct 2015 22:47:23 +0530 Subject: [PATCH 363/417] added comments --- .../arrays/AnagramsTogetherLexicographically.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java index cb7a1ca9..b05ba279 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java +++ b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java @@ -12,8 +12,9 @@ public class AnagramsTogetherLexicographically { /** - * Prints anagrams in groups where the groups are arranged lexicographically - * and the strings within each group is also arranged lexicographically. + * Takes an array of String {@param s} and prints anagrams in groups where the groups + * are arranged lexicographically and the strings within each group are also arranged + * lexicographically. * * @param s */ @@ -48,6 +49,7 @@ public static void printAnagramsTogether(String[] s) { output.add(anagrams); } + // the entire output should also be in lexicographic order Collections.sort(output, new Comparator>() { @Override public int compare(List o1, List o2) { @@ -60,6 +62,11 @@ public int compare(List o1, List o2) { } } + /** + * Take list of strings from console and print anagrams in groups. + * + * @param a + */ public static void main(String a[]) { Scanner in = new Scanner(System.in); List strings = new ArrayList<>(); From 90330bae0bd3eab3c7ca57ce2e1510787c82f0dc Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 12 Oct 2015 09:30:32 +0530 Subject: [PATCH 364/417] code improvements --- .../AnagramsTogetherLexicographically.java | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java index b05ba279..9e4d00f4 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java +++ b/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java @@ -21,7 +21,16 @@ public class AnagramsTogetherLexicographically { public static void printAnagramsTogether(String[] s) { HashMap> hashMap = new HashMap<>(); - List> output = new ArrayList<>(); + TreeSet> treeSet = new TreeSet<>(new Comparator() { + @Override + public int compare(Object o1, Object o2) { + if (o1 instanceof List && o2 instanceof List) { + return ((List) o1).get(0).compareTo(((List) o2).get(0)); + } else { + return 0; + } + } + }); for (int i = 0; i < s.length; i++) { String removeSpaces = s[i].replaceAll("\\s+", ""); @@ -44,21 +53,13 @@ public static void printAnagramsTogether(String[] s) { anagrams.add(s[entry.getValue().get(i)]); } - // arrange anagrams lexicographically within a single line - Collections.sort(anagrams); - output.add(anagrams); + Collections.sort(anagrams); // arrange anagrams lexicographically within a single line + treeSet.add(anagrams); // sort the entire output lexicographically } - // the entire output should also be in lexicographic order - Collections.sort(output, new Comparator>() { - @Override - public int compare(List o1, List o2) { - return o1.get(0).compareTo(o2.get(0)); - } - }); - - for (int i = 0; i < output.size(); i++) { - System.out.println(output.get(i)); + Iterator iterator = treeSet.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); } } From 59ac3dce0fa209874894425ff227d5086a146046 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 12 Oct 2015 23:03:38 +0530 Subject: [PATCH 365/417] coded + unit tested --- .../arrays/MinimumDistanceBetweenTwoNos.java | 2 +- .../ramswaroop/arrays/SortedSubSequence.java | 58 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/arrays/SortedSubSequence.java diff --git a/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java b/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java index 034ccfcc..560ab591 100644 --- a/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java +++ b/src/me/ramswaroop/arrays/MinimumDistanceBetweenTwoNos.java @@ -36,7 +36,7 @@ public static int getMinimumDistanceBetweenTwoNos(int[] a, int x, int y) { endIndex = i; } } - // if distance is less then update + // if distance is less, then update if (Math.abs(endIndex - startIndex) < minDiff) { minDiff = Math.abs(endIndex - startIndex); } diff --git a/src/me/ramswaroop/arrays/SortedSubSequence.java b/src/me/ramswaroop/arrays/SortedSubSequence.java new file mode 100644 index 00000000..040672a5 --- /dev/null +++ b/src/me/ramswaroop/arrays/SortedSubSequence.java @@ -0,0 +1,58 @@ +package me.ramswaroop.arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/12/15 + * @time: 8:32 PM + */ +public class SortedSubSequence { + + /** + * Finds 3 elements such that a[i] < a[j] < a[k] and i < j < k in O(n) time + * in an array of n integers. If there are multiple such triplets, then prints any + * one of them. + * + * @param a + */ + public static void printSortedSubSequenceOfSize3(int[] a) { + int len = a.length, min = a[0], max = a[len - 1]; + + int[] smaller = new int[len], larger = new int[len]; + + smaller[0] = -1; + for (int i = 1; i < len; i++) { + if (a[i] < min) { + smaller[i] = -1; + min = a[i]; + } else { + smaller[i] = min; + } + } + + larger[len - 1] = -1; + for (int i = len - 2; i >= 0; i--) { + if (a[i] > max) { + larger[i] = -1; + max = a[i]; + } else { + larger[i] = max; + } + } + + for (int i = 0; i < len; i++) { + if (smaller[i] != -1 && larger[i] != -1) { + System.out.println(smaller[i] + "," + a[i] + "," + larger[i]); + break; + } + } + + } + + public static void main(String a[]) { + printSortedSubSequenceOfSize3(new int[]{12, 11, 10, 5, 6, 2, 30}); + printSortedSubSequenceOfSize3(new int[]{1, 2, 3, 4}); + printSortedSubSequenceOfSize3(new int[]{4, 3, 2, 1}); + } +} From 4f175f42de5ea267c6c43743a51a99645f3e2e57 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 13 Oct 2015 10:35:13 +0530 Subject: [PATCH 366/417] added comments --- .../arrays/MaximumSumNonAdjacentSubsequence.java | 8 ++++---- src/me/ramswaroop/arrays/SortedSubSequence.java | 5 +++++ src/me/ramswaroop/misc/Parenthesis.java | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java b/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java index 3a348306..d5b68b1b 100644 --- a/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java +++ b/src/me/ramswaroop/arrays/MaximumSumNonAdjacentSubsequence.java @@ -7,7 +7,7 @@ * @date: 7/29/15 * @time: 9:18 AM */ -public class MaximumSumNonAdjacentSubsequence { +public class MaximumSumNonAdjacentSubSequence { /** * Given an array of positive numbers, finds the maximum sum of a sub-sequence @@ -24,7 +24,7 @@ public class MaximumSumNonAdjacentSubsequence { * @param a * @return */ - public static int maximumSumNonAdjacentSubsequence(int[] a) { + public static int maximumSumNonAdjacentSubSequence(int[] a) { int incl = a[0], excl = 0, prevIncl = incl; // incl is max sum including the current element // and excl is max sum excluding the current element for (int i = 1; i < a.length; i++) { @@ -36,7 +36,7 @@ public static int maximumSumNonAdjacentSubsequence(int[] a) { } public static void main(String a[]) { - System.out.println(maximumSumNonAdjacentSubsequence(new int[]{3, 2, 7, 10})); - System.out.println(maximumSumNonAdjacentSubsequence(new int[]{3, 2, 5, 10, 7})); + System.out.println(maximumSumNonAdjacentSubSequence(new int[]{3, 2, 7, 10})); + System.out.println(maximumSumNonAdjacentSubSequence(new int[]{3, 2, 5, 10, 7})); } } diff --git a/src/me/ramswaroop/arrays/SortedSubSequence.java b/src/me/ramswaroop/arrays/SortedSubSequence.java index 040672a5..42893683 100644 --- a/src/me/ramswaroop/arrays/SortedSubSequence.java +++ b/src/me/ramswaroop/arrays/SortedSubSequence.java @@ -13,6 +13,11 @@ public class SortedSubSequence { * Finds 3 elements such that a[i] < a[j] < a[k] and i < j < k in O(n) time * in an array of n integers. If there are multiple such triplets, then prints any * one of them. + * + * Algorithm: + * 1) Create an auxiliary array smaller[0..n-1]. smaller[i] should store the index of a number which is smaller than arr[i] and is on left side of arr[i]. smaller[i] should contain -1 if there is no such element. + * 2) Create another auxiliary array greater[0..n-1]. greater[i] should store the index of a number which is greater than arr[i] and is on right side of arr[i]. greater[i] should contain -1 if there is no such element. + * 3) Finally traverse both smaller[] and greater[] and find the index i for which both smaller[i] and greater[i] are not -1. * * @param a */ diff --git a/src/me/ramswaroop/misc/Parenthesis.java b/src/me/ramswaroop/misc/Parenthesis.java index 6945d347..8c7ab982 100644 --- a/src/me/ramswaroop/misc/Parenthesis.java +++ b/src/me/ramswaroop/misc/Parenthesis.java @@ -37,7 +37,7 @@ public static boolean isWellFormed(String input) { int len = input.length(); Stack stack = new Stack<>(); - // base case + // obvious check as the i/p only consists of parenthesis if (len % 2 != 0) return false; for (int i = 0; i < len; i++) { From 12e08afc6cd5536d87c92b1eb31f454bc1825475 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 15 Oct 2015 10:44:05 +0530 Subject: [PATCH 367/417] coded + unit tested --- .../strings/StringPermutationCount.java | 31 +++++++++++++++++++ .../StringPermutations.java | 2 +- .../UppercaseLowercasePermutations.java | 2 +- 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/me/ramswaroop/strings/StringPermutationCount.java rename src/me/ramswaroop/{arrays => strings}/StringPermutations.java (97%) rename src/me/ramswaroop/{arrays => strings}/UppercaseLowercasePermutations.java (98%) diff --git a/src/me/ramswaroop/strings/StringPermutationCount.java b/src/me/ramswaroop/strings/StringPermutationCount.java new file mode 100644 index 00000000..1f2a3272 --- /dev/null +++ b/src/me/ramswaroop/strings/StringPermutationCount.java @@ -0,0 +1,31 @@ +package me.ramswaroop.strings; + +/** + * Created by IntelliJ IDEA. + *

+ * You have 2 string, one smaller, one larger. Write an algorithm to figure out how many permutations of the + * smaller string exist in the bigger string. + * + * @author: ramswaroop + * @date: 10/15/15 + * @time: 10:32 AM + */ +public class StringPermutationCount { + + public static int getStringPermutationCount(String prefix, String s1, String s2, int count) { + if (s1.isEmpty()) { + if (s2.indexOf(prefix) != -1) count++; + } + + for (int i = 0; i < s1.length(); i++) { + count = getStringPermutationCount(prefix + s1.substring(i, i + 1), s1.substring(0, i) + s1.substring(i + 1), s2, count); + } + + return count; + } + + public static void main(String a[]) { + System.out.println(getStringPermutationCount("", "abc", "abcba", 0)); + System.out.println(getStringPermutationCount("", "abc", "abcba", 0)); + } +} diff --git a/src/me/ramswaroop/arrays/StringPermutations.java b/src/me/ramswaroop/strings/StringPermutations.java similarity index 97% rename from src/me/ramswaroop/arrays/StringPermutations.java rename to src/me/ramswaroop/strings/StringPermutations.java index 38da054b..b2d81e04 100644 --- a/src/me/ramswaroop/arrays/StringPermutations.java +++ b/src/me/ramswaroop/strings/StringPermutations.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.strings; /** * Created by IntelliJ IDEA. diff --git a/src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java b/src/me/ramswaroop/strings/UppercaseLowercasePermutations.java similarity index 98% rename from src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java rename to src/me/ramswaroop/strings/UppercaseLowercasePermutations.java index 326d3a74..fd229bf1 100644 --- a/src/me/ramswaroop/arrays/UppercaseLowercasePermutations.java +++ b/src/me/ramswaroop/strings/UppercaseLowercasePermutations.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.strings; /** * Created by IntelliJ IDEA. From f1868d9a59db5fb7ff61800f9ce66848e3c28a41 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 15 Oct 2015 10:51:04 +0530 Subject: [PATCH 368/417] added comments --- .../ramswaroop/strings/StringPermutationCount.java | 12 +++++++++++- src/me/ramswaroop/strings/StringPermutations.java | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/strings/StringPermutationCount.java b/src/me/ramswaroop/strings/StringPermutationCount.java index 1f2a3272..980c7b41 100644 --- a/src/me/ramswaroop/strings/StringPermutationCount.java +++ b/src/me/ramswaroop/strings/StringPermutationCount.java @@ -9,9 +9,19 @@ * @author: ramswaroop * @date: 10/15/15 * @time: 10:32 AM + * @see: me.ramswaroop.strings.StringPermutations for a simpler version */ public class StringPermutationCount { + /** + * Finds the number of permutations of string {@param s1} that exists in string {@param s2}. + * + * @param prefix + * @param s1 + * @param s2 + * @param count + * @return + */ public static int getStringPermutationCount(String prefix, String s1, String s2, int count) { if (s1.isEmpty()) { if (s2.indexOf(prefix) != -1) count++; @@ -26,6 +36,6 @@ public static int getStringPermutationCount(String prefix, String s1, String s2, public static void main(String a[]) { System.out.println(getStringPermutationCount("", "abc", "abcba", 0)); - System.out.println(getStringPermutationCount("", "abc", "abcba", 0)); + System.out.println(getStringPermutationCount("", "abc", "abcbacb", 0)); } } diff --git a/src/me/ramswaroop/strings/StringPermutations.java b/src/me/ramswaroop/strings/StringPermutations.java index b2d81e04..ea3a5688 100644 --- a/src/me/ramswaroop/strings/StringPermutations.java +++ b/src/me/ramswaroop/strings/StringPermutations.java @@ -8,6 +8,7 @@ * @time: 2:27 PM * @see: http://www.ericleschinski.com/c/java_permutations_recursion/ * @see: http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html + * @see: me.ramswaroop.strings.StringPermutationCount for a modification of this problem */ public class StringPermutations { From 1fb41d882ed6619ee3176055d692eae8692fda73 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 15 Oct 2015 10:55:51 +0530 Subject: [PATCH 369/417] code refactoring --- ...mutationCount.java => StringPermutationsCount.java} | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) rename src/me/ramswaroop/strings/{StringPermutationCount.java => StringPermutationsCount.java} (65%) diff --git a/src/me/ramswaroop/strings/StringPermutationCount.java b/src/me/ramswaroop/strings/StringPermutationsCount.java similarity index 65% rename from src/me/ramswaroop/strings/StringPermutationCount.java rename to src/me/ramswaroop/strings/StringPermutationsCount.java index 980c7b41..6ddc020c 100644 --- a/src/me/ramswaroop/strings/StringPermutationCount.java +++ b/src/me/ramswaroop/strings/StringPermutationsCount.java @@ -11,7 +11,7 @@ * @time: 10:32 AM * @see: me.ramswaroop.strings.StringPermutations for a simpler version */ -public class StringPermutationCount { +public class StringPermutationsCount { /** * Finds the number of permutations of string {@param s1} that exists in string {@param s2}. @@ -22,20 +22,20 @@ public class StringPermutationCount { * @param count * @return */ - public static int getStringPermutationCount(String prefix, String s1, String s2, int count) { + public static int getStringPermutationsCount(String prefix, String s1, String s2, int count) { if (s1.isEmpty()) { if (s2.indexOf(prefix) != -1) count++; } for (int i = 0; i < s1.length(); i++) { - count = getStringPermutationCount(prefix + s1.substring(i, i + 1), s1.substring(0, i) + s1.substring(i + 1), s2, count); + count = getStringPermutationsCount(prefix + s1.substring(i, i + 1), s1.substring(0, i) + s1.substring(i + 1), s2, count); } return count; } public static void main(String a[]) { - System.out.println(getStringPermutationCount("", "abc", "abcba", 0)); - System.out.println(getStringPermutationCount("", "abc", "abcbacb", 0)); + System.out.println(getStringPermutationsCount("", "abc", "abcba", 0)); + System.out.println(getStringPermutationsCount("", "abc", "abcbacb", 0)); } } From 7a1fb557ef18e84a64cc9411566afc4b1d9428ca Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 16 Oct 2015 09:23:20 +0530 Subject: [PATCH 370/417] coded + unit tested --- src/me/ramswaroop/misc/HitCount.java | 49 +++++++++++++++++++ .../{arrays => strings}/AnagramsTogether.java | 2 +- .../AnagramsTogetherLexicographically.java | 2 +- 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/me/ramswaroop/misc/HitCount.java rename src/me/ramswaroop/{arrays => strings}/AnagramsTogether.java (97%) rename src/me/ramswaroop/{arrays => strings}/AnagramsTogetherLexicographically.java (98%) diff --git a/src/me/ramswaroop/misc/HitCount.java b/src/me/ramswaroop/misc/HitCount.java new file mode 100644 index 00000000..7d0afe04 --- /dev/null +++ b/src/me/ramswaroop/misc/HitCount.java @@ -0,0 +1,49 @@ +package me.ramswaroop.misc; + +import java.util.*; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/16/15 + * @time: 8:40 AM + */ +public class HitCount { + + public static String getIPWithMaxHitCount(List inputList) { + HashMap hashMap = new HashMap<>(); + + for (int i = 0; i < inputList.size(); i++) { + String input = inputList.get(i); + String ip = input.substring(0, input.indexOf(" ")); + if (hashMap.get(ip) == null) { + hashMap.put(ip, 1); + } else { + hashMap.put(ip, hashMap.get(ip) + 1); + } + } + + List> list = new ArrayList<>(hashMap.entrySet()); + Collections.sort(list, new Comparator>() { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o2.getValue().compareTo(o1.getValue()); // desc order + } + }); + + return list.get(0).getKey(); + } + + public static void main(String a[]) { + List inputList = new ArrayList<>(); + inputList.add("10.1.2.23 http://we.sdfdsf.sdf"); + inputList.add("10.1.2.24 http://we.sdfdsf.sdf"); + inputList.add("10.1.2.24 http://we.sdfdsf.sdf"); + inputList.add("10.1.2.24 http://we.sdfdsf.sdf"); + inputList.add("10.1.2.24 http://we.sdfdsf.sdf"); + inputList.add("10.1.2.23 http://we.sdfdsf.sdf"); + inputList.add("10.1.2.23 http://we.sdfdsf.sdf"); + System.out.println(getIPWithMaxHitCount(inputList)); + } +} diff --git a/src/me/ramswaroop/arrays/AnagramsTogether.java b/src/me/ramswaroop/strings/AnagramsTogether.java similarity index 97% rename from src/me/ramswaroop/arrays/AnagramsTogether.java rename to src/me/ramswaroop/strings/AnagramsTogether.java index b90dfa9a..e98b3a06 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogether.java +++ b/src/me/ramswaroop/strings/AnagramsTogether.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.strings; import java.util.*; diff --git a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java b/src/me/ramswaroop/strings/AnagramsTogetherLexicographically.java similarity index 98% rename from src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java rename to src/me/ramswaroop/strings/AnagramsTogetherLexicographically.java index 9e4d00f4..160f0a35 100644 --- a/src/me/ramswaroop/arrays/AnagramsTogetherLexicographically.java +++ b/src/me/ramswaroop/strings/AnagramsTogetherLexicographically.java @@ -1,4 +1,4 @@ -package me.ramswaroop.arrays; +package me.ramswaroop.strings; import java.util.*; From c246d773689157c3bcee38f310ae3a2a342d4d5a Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 17 Oct 2015 12:07:08 +0530 Subject: [PATCH 371/417] collection iteration basics --- .../ramswaroop/misc/CollectionIteration.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/me/ramswaroop/misc/CollectionIteration.java diff --git a/src/me/ramswaroop/misc/CollectionIteration.java b/src/me/ramswaroop/misc/CollectionIteration.java new file mode 100644 index 00000000..dadf5e06 --- /dev/null +++ b/src/me/ramswaroop/misc/CollectionIteration.java @@ -0,0 +1,50 @@ +package me.ramswaroop.misc; + +import java.util.*; + +import static java.lang.System.out; + +/** + * Created by IntelliJ IDEA. + *

+ * All possible ways of iterating different collections in Java. + * + * @author: ramswaroop + * @date: 10/16/15 + * @time: 9:24 AM + */ +public class CollectionIteration { + + public static void main(String a[]) { + List list = new ArrayList<>(); + list.add(1); + list.add(2); + list.add(3); + // 1st way + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + out.println("List: " + iterator.next()); + } + // 2nd way + for (int i = 0; i < list.size(); i++) { + out.println("List: " + list.get(i)); + } + + Map hashMap = new HashMap<>(); + hashMap.put("one", 1); + hashMap.put("two", 2); + hashMap.put("three", 3); + // 1st way + Iterator> iterator1 = hashMap.entrySet().iterator(); // iterator only iterates on + // lists or set and not on maps + while (iterator1.hasNext()) { + Map.Entry entry = iterator1.next(); + out.println("HashMap: " + entry.getKey() + "->" + entry.getValue()); + } + // 2nd way + for (Map.Entry entry : hashMap.entrySet()) { // entrySet() returns a Set of Entry objects + // stored in HashMap + out.println("HashMap: " + entry.getKey() + "->" + entry.getValue()); + } + } +} From dc9d3bbd69d3a5f094c41389a5de19151dc4a25e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 17 Oct 2015 13:20:36 +0530 Subject: [PATCH 372/417] initial commit --- .../ramswaroop/backtracking/KnightTour.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/me/ramswaroop/backtracking/KnightTour.java diff --git a/src/me/ramswaroop/backtracking/KnightTour.java b/src/me/ramswaroop/backtracking/KnightTour.java new file mode 100644 index 00000000..83a1221c --- /dev/null +++ b/src/me/ramswaroop/backtracking/KnightTour.java @@ -0,0 +1,76 @@ +package me.ramswaroop.backtracking; + +/** + * Created by IntelliJ IDEA. + *

+ * A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only + * once. If the knight ends on a square that is one knight's move from the beginning square (so that it could tour the + * board again immediately, following the same path), the tour is closed, otherwise it is open. + * + * @author: ramswaroop + * @date: 10/15/15 + * @time: 11:56 PM + * @see: https://en.wikipedia.org/wiki/Knight%27s_tour + */ +public class KnightTour { + + public static boolean isValidMove(int i, int j, int[][] tour) { + if (i >= 0 && j >= 0 && i < tour.length && j < tour[0].length && tour[i][j] == 0) { + return true; + } else { + return false; + } + } + + public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves, int step, int[][] tour) { + + if (step == tour.length * tour[0].length) return true; + + for (int k = 0; k < xMoves.length; k++) { + i += xMoves[k]; + j += yMoves[k]; + + if (isValidMove(i, j, tour)) { + step++; + tour[i][j] = step; + if (isValidKnightTour(i, j, xMoves, yMoves, step, tour)) { + return true; + } else { + tour[i][j] = 0; + } + } + } + + return false; + } + + public static void printKnightTour(int[] boardSize) { + if (boardSize.length < 2) return; + + int[][] tour = new int[boardSize[0]][boardSize[1]]; + int[] xMoves = new int[]{1, 1, 2, 2, -1, -1, -2, -2}; + int[] yMoves = new int[]{-2, 2, -1, 1, -2, 2, -1, 1}; + + tour[0][0] = 1; + + if (isValidKnightTour(0, 0, xMoves, yMoves, 1, tour)) { + print2DMatrix(tour); + } else { + System.out.println("Knight's tour doesn't exist for board size [" + boardSize[0] + "x" + boardSize[1] + "]"); + } + + } + + public static void print2DMatrix(int[][] array) { + for (int i = 0; i < array.length; i++) { + for (int j = 0; j < array[0].length; j++) { + System.out.print("[" + array[i][j] + "]"); + } + System.out.println(); + } + } + + public static void main(String a[]) { + printKnightTour(new int[]{8, 8}); + } +} From be459ef8a3871ac61fd41943f8ae7fc1ed905fdb Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 17 Oct 2015 15:28:48 +0530 Subject: [PATCH 373/417] coded + unit tested --- .../ramswaroop/backtracking/KnightTour.java | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/src/me/ramswaroop/backtracking/KnightTour.java b/src/me/ramswaroop/backtracking/KnightTour.java index 83a1221c..2e7cb82d 100644 --- a/src/me/ramswaroop/backtracking/KnightTour.java +++ b/src/me/ramswaroop/backtracking/KnightTour.java @@ -14,6 +14,13 @@ */ public class KnightTour { + /** + * + * @param i + * @param j + * @param tour + * @return + */ public static boolean isValidMove(int i, int j, int[][] tour) { if (i >= 0 && j >= 0 && i < tour.length && j < tour[0].length && tour[i][j] == 0) { return true; @@ -22,21 +29,30 @@ public static boolean isValidMove(int i, int j, int[][] tour) { } } + /** + * + * @param i + * @param j + * @param xMoves + * @param yMoves + * @param step + * @param tour + * @return + */ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves, int step, int[][] tour) { - if (step == tour.length * tour[0].length) return true; + if (step > tour.length * tour[0].length) return true; for (int k = 0; k < xMoves.length; k++) { - i += xMoves[k]; - j += yMoves[k]; + int nextI = i + xMoves[k]; + int nextJ = j + yMoves[k]; - if (isValidMove(i, j, tour)) { - step++; - tour[i][j] = step; - if (isValidKnightTour(i, j, xMoves, yMoves, step, tour)) { + if (isValidMove(nextI, nextJ, tour)) { + tour[nextI][nextJ] = step; + if (isValidKnightTour(nextI, nextJ, xMoves, yMoves, step + 1, tour)) { return true; } else { - tour[i][j] = 0; + tour[nextI][nextJ] = 0; } } } @@ -44,6 +60,10 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves return false; } + /** + * + * @param boardSize + */ public static void printKnightTour(int[] boardSize) { if (boardSize.length < 2) return; @@ -53,7 +73,7 @@ public static void printKnightTour(int[] boardSize) { tour[0][0] = 1; - if (isValidKnightTour(0, 0, xMoves, yMoves, 1, tour)) { + if (isValidKnightTour(0, 0, xMoves, yMoves, 2, tour)) { print2DMatrix(tour); } else { System.out.println("Knight's tour doesn't exist for board size [" + boardSize[0] + "x" + boardSize[1] + "]"); From dbb626d4dd6b58b18586a30620e41fcecfa07b18 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 18 Oct 2015 11:26:08 +0530 Subject: [PATCH 374/417] coded + unit tested --- .../ramswaroop/backtracking/KnightTour.java | 11 ++- .../ramswaroop/backtracking/RatInAMaze.java | 72 +++++++++++++++++++ 2 files changed, 77 insertions(+), 6 deletions(-) create mode 100644 src/me/ramswaroop/backtracking/RatInAMaze.java diff --git a/src/me/ramswaroop/backtracking/KnightTour.java b/src/me/ramswaroop/backtracking/KnightTour.java index 2e7cb82d..f47f83c8 100644 --- a/src/me/ramswaroop/backtracking/KnightTour.java +++ b/src/me/ramswaroop/backtracking/KnightTour.java @@ -15,14 +15,13 @@ public class KnightTour { /** - * * @param i * @param j * @param tour * @return */ public static boolean isValidMove(int i, int j, int[][] tour) { - if (i >= 0 && j >= 0 && i < tour.length && j < tour[0].length && tour[i][j] == 0) { + if (i >= 0 && i < tour.length && j >= 0 && j < tour[0].length && tour[i][j] == 0) { return true; } else { return false; @@ -30,7 +29,6 @@ public static boolean isValidMove(int i, int j, int[][] tour) { } /** - * * @param i * @param j * @param xMoves @@ -43,9 +41,11 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves if (step > tour.length * tour[0].length) return true; + int nextI, nextJ; + for (int k = 0; k < xMoves.length; k++) { - int nextI = i + xMoves[k]; - int nextJ = j + yMoves[k]; + nextI = i + xMoves[k]; + nextJ = j + yMoves[k]; if (isValidMove(nextI, nextJ, tour)) { tour[nextI][nextJ] = step; @@ -61,7 +61,6 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves } /** - * * @param boardSize */ public static void printKnightTour(int[] boardSize) { diff --git a/src/me/ramswaroop/backtracking/RatInAMaze.java b/src/me/ramswaroop/backtracking/RatInAMaze.java new file mode 100644 index 00000000..ffaff5ec --- /dev/null +++ b/src/me/ramswaroop/backtracking/RatInAMaze.java @@ -0,0 +1,72 @@ +package me.ramswaroop.backtracking; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/18/15 + * @time: 10:39 AM + */ +public class RatInAMaze { + + public static boolean isValidMove(int i, int j, int[][] maze) { + if (i >= 0 && i < maze.length && j >= 0 && j < maze[0].length && maze[i][j] == 1) { + return true; + } else { + return false; + } + } + + public static boolean isValidPath(int i, int j, int[] xMoves, int[] yMoves, int[][] maze, int[][] path) { + + if (i == maze.length - 1 && j == maze[0].length - 1) return true; + + int nextI, nextJ; + + for (int k = 0; k < xMoves.length; k++) { + nextI = i + xMoves[k]; + nextJ = j + yMoves[k]; + if (isValidMove(nextI, nextJ, maze)) { + path[nextI][nextJ] = 1; + if (isValidPath(nextI, nextJ, xMoves, yMoves, maze, path)) { + return true; + } else { + path[nextI][nextJ] = 0; + } + } + } + return false; + } + + public static void printMazePath(int i, int j, int[][] maze) { + + int[] xMoves = {0, 1}; + int[] yMoves = {1, 0}; + + int[][] path = new int[maze.length][maze[0].length]; + + System.out.println("Maze"); + System.out.println("---------------"); + print2DMatrix(maze); + System.out.println("---------------"); + + if (isValidPath(i, j, xMoves, yMoves, maze, path)) { + print2DMatrix(path); + } else { + System.out.println("No escape path found!"); + } + } + + public static void print2DMatrix(int[][] array) { + for (int i = 0; i < array.length; i++) { + for (int j = 0; j < array[0].length; j++) { + System.out.print("[" + array[i][j] + "]"); + } + System.out.println(); + } + } + + public static void main(String a[]) { + printMazePath(0, 0, new int[][]{{1, 1, 1, 1}, {0, 0, 1, 1}}); + } +} From 215f95652ee6b37450cfb9cf7a3f16306bd6cbea Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 18 Oct 2015 17:48:16 +0530 Subject: [PATCH 375/417] added comments --- .../ramswaroop/backtracking/KnightTour.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/backtracking/KnightTour.java b/src/me/ramswaroop/backtracking/KnightTour.java index f47f83c8..0d82b0b7 100644 --- a/src/me/ramswaroop/backtracking/KnightTour.java +++ b/src/me/ramswaroop/backtracking/KnightTour.java @@ -11,12 +11,15 @@ * @date: 10/15/15 * @time: 11:56 PM * @see: https://en.wikipedia.org/wiki/Knight%27s_tour + * @see: me.ramswaroop.backtracking.RatInAMaze for a simpler version of this problem */ public class KnightTour { /** - * @param i - * @param j + * Determines if a move is a valid move in the given chess board. + * + * @param i is the row of the new move + * @param j is the column of the new move * @param tour * @return */ @@ -29,6 +32,9 @@ public static boolean isValidMove(int i, int j, int[][] tour) { } /** + * Finds a valid knight's tour for a given chess board size if any + * with the use of backtracking. + * * @param i * @param j * @param xMoves @@ -44,15 +50,18 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves int nextI, nextJ; for (int k = 0; k < xMoves.length; k++) { + // next move is calculated from all possible moves nextI = i + xMoves[k]; nextJ = j + yMoves[k]; + // if the next move is valid then we proceed otherwise we + // try next set of moves if (isValidMove(nextI, nextJ, tour)) { tour[nextI][nextJ] = step; if (isValidKnightTour(nextI, nextJ, xMoves, yMoves, step + 1, tour)) { return true; } else { - tour[nextI][nextJ] = 0; + tour[nextI][nextJ] = 0; // backtrack } } } @@ -60,19 +69,26 @@ public static boolean isValidKnightTour(int i, int j, int[] xMoves, int[] yMoves return false; } + /** - * @param boardSize + * Prints the knight's tour if any. + * + * @param i is the start row + * @param j is the start column + * @param boardSize is the size of the chess board */ - public static void printKnightTour(int[] boardSize) { + public static void printKnightTour(int i, int j, int[] boardSize) { if (boardSize.length < 2) return; + // a 2D array for the knight's tour int[][] tour = new int[boardSize[0]][boardSize[1]]; + // all possible relative moves that a knight can make int[] xMoves = new int[]{1, 1, 2, 2, -1, -1, -2, -2}; int[] yMoves = new int[]{-2, 2, -1, 1, -2, 2, -1, 1}; tour[0][0] = 1; - if (isValidKnightTour(0, 0, xMoves, yMoves, 2, tour)) { + if (isValidKnightTour(i, j, xMoves, yMoves, 2, tour)) { print2DMatrix(tour); } else { System.out.println("Knight's tour doesn't exist for board size [" + boardSize[0] + "x" + boardSize[1] + "]"); @@ -90,6 +106,6 @@ public static void print2DMatrix(int[][] array) { } public static void main(String a[]) { - printKnightTour(new int[]{8, 8}); + printKnightTour(0, 0, new int[]{8, 8}); } } From 2a224f46811fc656ff440b0ed849dae60c28b2b9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 19 Oct 2015 22:28:53 +0530 Subject: [PATCH 376/417] coded + unit tested --- .../DuplicatesInArrayWithinKDistance.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/me/ramswaroop/arrays/DuplicatesInArrayWithinKDistance.java diff --git a/src/me/ramswaroop/arrays/DuplicatesInArrayWithinKDistance.java b/src/me/ramswaroop/arrays/DuplicatesInArrayWithinKDistance.java new file mode 100644 index 00000000..05575bf3 --- /dev/null +++ b/src/me/ramswaroop/arrays/DuplicatesInArrayWithinKDistance.java @@ -0,0 +1,47 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; +import java.util.HashSet; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/18/15 + * @time: 8:40 PM + */ +public class DuplicatesInArrayWithinKDistance { + + /** + * Finds duplicates in an unsorted array {@param a} which are + * only k distance apart from each other. + * + * @param a + * @param k + * @return + */ + public static int[] findDuplicatesInArrayWithinKDistance(int[] a, int k) { + int index = 0; + int[] duplicates = new int[a.length]; + + HashSet hashSet = new HashSet<>(); + + for (int i = 0; i < a.length; i++) { + if (hashSet.contains(a[i])) { + duplicates[index++] = a[i]; + } else { + hashSet.add(a[i]); + } + + if (i >= k) { + hashSet.remove(a[i - k]); + } + } + + return Arrays.copyOf(duplicates, index); + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(findDuplicatesInArrayWithinKDistance(new int[]{1, 2, 8, 1, 3, 4, 5, 6, 6, 7}, 3))); + } +} From e7a610c0209be718e99f3ac1708d0d89ea311ab9 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 20 Oct 2015 22:53:32 +0530 Subject: [PATCH 377/417] coded + unit tested --- src/me/ramswaroop/strings/SubString.java | 44 ++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/me/ramswaroop/strings/SubString.java diff --git a/src/me/ramswaroop/strings/SubString.java b/src/me/ramswaroop/strings/SubString.java new file mode 100644 index 00000000..5ef8b8cd --- /dev/null +++ b/src/me/ramswaroop/strings/SubString.java @@ -0,0 +1,44 @@ +package me.ramswaroop.strings; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/20/15 + * @time: 1:15 PM + */ +public class SubString { + + /** + * Naive approach to determine whether string {@param s2} is a + * substring of string {@param s1}. + * + * @param s1 + * @param s2 + * @return + */ + public static boolean isSubString(String s1, String s2) { + char[] c1 = s1.toCharArray(), + c2 = s2.toCharArray(); + int l1 = c1.length, + l2 = c2.length, + i, j; + + for (i = 0; i <= l1 - l2; i++) { + for (j = 0; j < l2 && i + j < l1; j++) { + if (c1[i + j] != c2[j]) break; + } + if (j == l2) { + return true; + } + } + return false; + } + + public static void main(String a[]) { + System.out.println(isSubString("ramswaroop", "ram")); + System.out.println(isSubString("ramswaroop", "rams")); + System.out.println(isSubString("ramswaroop", "ramss")); + System.out.println(isSubString("ramswaroop", "ar")); + } +} From 839501a2b86d386606b0d7af0c2a1bdc2bc7e3d8 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 20 Oct 2015 23:50:16 +0530 Subject: [PATCH 378/417] coded + unit tested --- .../arrays/SymmetricDifference.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/me/ramswaroop/arrays/SymmetricDifference.java diff --git a/src/me/ramswaroop/arrays/SymmetricDifference.java b/src/me/ramswaroop/arrays/SymmetricDifference.java new file mode 100644 index 00000000..dcd7fa98 --- /dev/null +++ b/src/me/ramswaroop/arrays/SymmetricDifference.java @@ -0,0 +1,60 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/20/15 + * @time: 11:34 PM + */ +public class SymmetricDifference { + + /** + * Returns the symmetric difference between array {@param a1} + * and array {@param a2}. + *

+ * SYMMETRIC DIFFERENCE refers to the numbers which are present in + * only one of the arrays and not both. + * + * @param a1 + * @param a2 + * @return + */ + public static int[] getSymmetricDifference(int[] a1, int[] a2) { + int index = 0; + int[] res = new int[a1.length + a2.length]; + + Arrays.sort(a1); + Arrays.sort(a2); + + for (int i = 0, j = 0; i < a1.length || j < a2.length; ) { + if (j >= a2.length) { + res[index++] = a1[i]; + i++; + } else if (i >= a1.length) { + res[index++] = a2[j]; + j++; + } else if (a1[i] < a2[j]) { + res[index++] = a1[i]; + i++; + } else if (a2[j] < a1[i]) { + res[index++] = a2[j]; + j++; + } else { + i++; + j++; + } + } + + return Arrays.copyOf(res, index); + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{2, 4, 5}))); + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{5, 6, 7}))); + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{5, 6, 7, 8}))); + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{1, 2, 3, 4}))); + } +} From 23e0bbdceebd05eac93889953485c80793d2c060 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 21 Oct 2015 10:57:03 +0530 Subject: [PATCH 379/417] coded + unit tested --- src/me/ramswaroop/strings/StringRotation.java | 53 +++++++++++++++++++ src/me/ramswaroop/strings/SubString.java | 3 ++ 2 files changed, 56 insertions(+) create mode 100644 src/me/ramswaroop/strings/StringRotation.java diff --git a/src/me/ramswaroop/strings/StringRotation.java b/src/me/ramswaroop/strings/StringRotation.java new file mode 100644 index 00000000..e46306d3 --- /dev/null +++ b/src/me/ramswaroop/strings/StringRotation.java @@ -0,0 +1,53 @@ +package me.ramswaroop.strings; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/21/15 + * @time: 10:06 AM + * @see: me.ramswaroop.strings.SubString for a similar problem. + */ +public class StringRotation { + + /** + * Determines if string {@param s2} is a rotation of string {@param s1}. + * + * @param s1 + * @param s2 + * @return + */ + public static boolean isStringRotation(String s1, String s2) { + char[] c1 = s1.toCharArray(); + char[] c2 = s2.toCharArray(); + + int l1 = c1.length, + l2 = c2.length, + i, j, k; + + for (i = 0; i < l1; i++) { + for (j = 0; j < l2 && i + j < l1; j++) { + if (c1[i + j] != c2[j]) break; + } + k = 0; + while (k < l1 && j < l2) { + if (c1[k++] != c2[j]) break; + j++; + } + if (j == l2) { + return true; + } + } + return false; + } + + public static void main(String a[]) { + System.out.println(isStringRotation("ramswaroop", "swaroopram")); + System.out.println(isStringRotation("ramswaroop", "swaroopramramram")); + System.out.println(isStringRotation("ramswaroop", "mswaroopra")); + System.out.println(isStringRotation("ramswaroop", "swarooppram")); + System.out.println(isStringRotation("ramswaroop", "")); + System.out.println(isStringRotation("mswaroopra", "ramswaroop")); + System.out.println(isStringRotation("amam", "mama")); + } +} diff --git a/src/me/ramswaroop/strings/SubString.java b/src/me/ramswaroop/strings/SubString.java index 5ef8b8cd..09978f11 100644 --- a/src/me/ramswaroop/strings/SubString.java +++ b/src/me/ramswaroop/strings/SubString.java @@ -6,6 +6,7 @@ * @author: ramswaroop * @date: 10/20/15 * @time: 1:15 PM + * @see: me.ramswaroop.strings.StringRotation for a similar problem. */ public class SubString { @@ -36,6 +37,8 @@ public static boolean isSubString(String s1, String s2) { } public static void main(String a[]) { + System.out.println(isSubString("ramswaroop", "ramswaroop")); + System.out.println(isSubString("ramswaroop", "")); System.out.println(isSubString("ramswaroop", "ram")); System.out.println(isSubString("ramswaroop", "rams")); System.out.println(isSubString("ramswaroop", "ramss")); From 8302d6b34b7512ffb0a93b7c266fb54a9f5385f5 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 22 Oct 2015 10:06:18 +0530 Subject: [PATCH 380/417] hackerrank solutions added --- .../arraysandsorting/InsertionSort1.java | 48 +++++++++++++++ .../arraysandsorting/InsertionSort2.java | 46 +++++++++++++++ .../arraysandsorting/IntroTutorial.java | 35 +++++++++++ .../arraysandsorting/LoopInvariant.java | 44 ++++++++++++++ .../arraysandsorting/QuickSort1.java | 43 ++++++++++++++ .../arraysandsorting/QuickSort2.java | 48 +++++++++++++++ .../arraysandsorting/RunningTime.java | 43 ++++++++++++++ .../strings/AlternatingCharacters.java | 37 ++++++++++++ .../algorithms/strings/PalindromeIndex.java | 54 +++++++++++++++++ .../algorithms/strings/Pangram.java | 42 +++++++++++++ .../algorithms/warmup/FlippingBits.java | 32 ++++++++++ .../algorithms/warmup/LonelyInteger.java | 50 ++++++++++++++++ .../algorithms/warmup/LoveLetterMystery.java | 37 ++++++++++++ .../algorithms/warmup/MaximizingXor.java | 38 ++++++++++++ .../algorithms/warmup/UtopianTree.java | 40 +++++++++++++ .../bitmanipulation/CounterGame.java | 54 +++++++++++++++++ .../hackerrank/bitmanipulation/Solution.java | 59 +++++++++++++++++++ .../bitmanipulation/TwosCompliment.java | 36 +++++++++++ .../hackerrank/java/oops/JavaInheritance.java | 30 ++++++++++ src/com/hackerrank/practice/RandomTest.java | 53 +++++++++++++++++ src/com/hackerrank/practice/SPOJ1.java | 31 ++++++++++ 21 files changed, 900 insertions(+) create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java create mode 100644 src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java create mode 100644 src/com/hackerrank/algorithms/strings/AlternatingCharacters.java create mode 100644 src/com/hackerrank/algorithms/strings/PalindromeIndex.java create mode 100644 src/com/hackerrank/algorithms/strings/Pangram.java create mode 100644 src/com/hackerrank/algorithms/warmup/FlippingBits.java create mode 100644 src/com/hackerrank/algorithms/warmup/LonelyInteger.java create mode 100644 src/com/hackerrank/algorithms/warmup/LoveLetterMystery.java create mode 100644 src/com/hackerrank/algorithms/warmup/MaximizingXor.java create mode 100644 src/com/hackerrank/algorithms/warmup/UtopianTree.java create mode 100644 src/com/hackerrank/bitmanipulation/CounterGame.java create mode 100644 src/com/hackerrank/bitmanipulation/Solution.java create mode 100644 src/com/hackerrank/bitmanipulation/TwosCompliment.java create mode 100644 src/com/hackerrank/java/oops/JavaInheritance.java create mode 100644 src/com/hackerrank/practice/RandomTest.java create mode 100644 src/com/hackerrank/practice/SPOJ1.java diff --git a/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java new file mode 100644 index 00000000..ba62e57e --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java @@ -0,0 +1,48 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/1/15 + * Time: 8:58 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class InsertionSort1 { + + static void insertIntoSorted(int[] ar) { + int V = ar[ar.length - 1], i = ar.length - 2; + + for (; i >= 0; i--) { + if (V < ar[i]) { + ar[i + 1] = ar[i]; + } else { + break; + } + printArray(ar); + } + + ar[i + 1] = V; + printArray(ar); + } + + /* Tail starts here */ + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int s = in.nextInt(); + int[] ar = new int[s]; + for (int i = 0; i < s; i++) { + ar[i] = in.nextInt(); + } + insertIntoSorted(ar); + } + + private static void printArray(int[] ar) { + for (int n : ar) { + System.out.print(n + " "); + } + System.out.println(""); + } + +} diff --git a/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java new file mode 100644 index 00000000..dfbf153a --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java @@ -0,0 +1,46 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/1/15 + * Time: 9:42 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class InsertionSort2 { + + static void insertionSortPart2(int[] ar) { + for (int i = 1; i < ar.length; i++) { + int V = ar[i], j; + /** + * keep shifting no.s to right until + * right place for insertion(of V) is found + */ + for (j = i - 1; j >= 0 && ar[j] > V; j--) { + ar[j + 1] = ar[j]; + } + ar[j + 1] = V; + printArray(ar); + } + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int s = in.nextInt(); + int[] ar = new int[s]; + for (int i = 0; i < s; i++) { + ar[i] = in.nextInt(); + } + insertionSortPart2(ar); + + } + + private static void printArray(int[] ar) { + for (int n : ar) { + System.out.print(n + " "); + } + System.out.println(""); + } +} diff --git a/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java b/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java new file mode 100644 index 00000000..6a1c904a --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java @@ -0,0 +1,35 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.Arrays; +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/1/15 + * Time: 3:38 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class IntroTutorial { + static int search(int searchVal, int[] arr) { + return Arrays.binarySearch(arr, searchVal); + } + + public static void main(String[] a) { + Scanner in = new Scanner(System.in); + + int searchVal = in.nextInt(); + int arrSize = in.nextInt(); + int[] arr = new int[arrSize]; + // as nextInt() doesn't read new line character + in.nextLine(); + String next = in.nextLine(); + String[] next_split = next.split(" "); + + for (int _a_i = 0; _a_i < arrSize; _a_i++) { + arr[_a_i] = Integer.parseInt(next_split[_a_i]); + } + + System.out.print(search(searchVal, arr)); + } +} diff --git a/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java b/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java new file mode 100644 index 00000000..01e88383 --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java @@ -0,0 +1,44 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/2/15 + * Time: 3:26 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class LoopInvariant { + + public static void insertionSort(int[] A) { + for (int i = 1; i < A.length; i++) { + int value = A[i]; + int j = i - 1; + while (j >= 0 && A[j] > value) { + A[j + 1] = A[j]; + j = j - 1; + } + A[j + 1] = value; + } + + printArray(A); + } + + + static void printArray(int[] ar) { + for (int n : ar) { + System.out.print(n + " "); + } + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int[] ar = new int[n]; + for (int i = 0; i < n; i++) { + ar[i] = in.nextInt(); + } + insertionSort(ar); + } +} diff --git a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java new file mode 100644 index 00000000..c95fa8e3 --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java @@ -0,0 +1,43 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/2/15 + * Time: 5:13 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class QuickSort1 { + + static void partition(int[] ar) { + int pivot = ar[0], j = 0; + int[] arCopy = ar.clone(); + + for (int i = 0; i < arCopy.length; i++) { + if (arCopy[i] < pivot) ar[j++] = arCopy[i]; + } + for (int i = 0; i < arCopy.length; i++) { + if (arCopy[i] >= pivot) ar[j++] = arCopy[i]; + } + printArray(ar); + } + + static void printArray(int[] ar) { + for (int n : ar) { + System.out.print(n + " "); + } + System.out.println(""); + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int[] ar = new int[n]; + for (int i = 0; i < n; i++) { + ar[i] = in.nextInt(); + } + partition(ar); + } +} diff --git a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java new file mode 100644 index 00000000..ef35849a --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java @@ -0,0 +1,48 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/3/15 + * Time: 1:05 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class QuickSort2 { + + static void quickSort(int[] ar, int start, int end) { + int pivot = ar[0]; + List ar1 = new ArrayList<>(); + List ar2 = new ArrayList<>(); + + for (int i = start; i < end; i++) { + if (ar[i] < pivot) { + ar1.add(ar[i]); + } else if (ar[i] > pivot) { + ar2.add(ar[i]); + } + } + + //TODO + } + + static void printArray(int[] ar) { + for (int n : ar) { + System.out.print(n + " "); + } + System.out.println(""); + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int[] ar = new int[n]; + for (int i = 0; i < n; i++) { + ar[i] = in.nextInt(); + } + quickSort(ar, 0, ar.length); + } +} diff --git a/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java b/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java new file mode 100644 index 00000000..2c435043 --- /dev/null +++ b/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java @@ -0,0 +1,43 @@ +package me.ramswaroop.algorithms.arraysandsorting; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/2/15 + * Time: 5:02 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class RunningTime { + static void insertionSortPart2(int[] ar) { + int c = 0; + for (int i = 1; i < ar.length; i++) { + int V = ar[i], j; + for (j = i - 1; j >= 0 && ar[j] > V; j--, c++) { + ar[j + 1] = ar[j]; + } + ar[j + 1] = V; + //printArray(ar); + } + System.out.print(c); + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int s = in.nextInt(); + int[] ar = new int[s]; + for (int i = 0; i < s; i++) { + ar[i] = in.nextInt(); + } + insertionSortPart2(ar); + + } + + private static void printArray(int[] ar) { + for (int n : ar) { + System.out.print(n + " "); + } + System.out.println(""); + } +} diff --git a/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java b/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java new file mode 100644 index 00000000..3ce7ab06 --- /dev/null +++ b/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java @@ -0,0 +1,37 @@ +package me.ramswaroop.algorithms.strings; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/22/15 + * @time: 9:24 AM + */ +public class AlternatingCharacters { + + public static int countDeletions(String s) { + int count = 0, index = 0; + for (int i = 1; i < s.length(); i++) { + if (s.charAt(i) == s.charAt(index)) { + count++; + } else { + index = i; + } + } + return count; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int t = Integer.parseInt(in.nextLine()); + String[] input = new String[t]; + for (int i = 0; i < t; i++) { + input[i] = in.nextLine(); + } + for (int i = 0; i < t; i++) { + System.out.println(countDeletions(input[i])); + } + } +} diff --git a/src/com/hackerrank/algorithms/strings/PalindromeIndex.java b/src/com/hackerrank/algorithms/strings/PalindromeIndex.java new file mode 100644 index 00000000..5b780ddd --- /dev/null +++ b/src/com/hackerrank/algorithms/strings/PalindromeIndex.java @@ -0,0 +1,54 @@ +package me.ramswaroop.algorithms.strings; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/18/15 + * Time: 12:27 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class PalindromeIndex { + + static int makePalindrome(String s) { + int index = -1, l = s.length(); + if (isPalindrome(s)) { + return -1; + } + for (int i = 0; i < l; i++) { + StringBuilder sb = new StringBuilder(s); + sb.deleteCharAt(i); + String str = sb.toString(); + if (isPalindrome(str)) { + return i; + } + } + return index; + } + + static boolean isPalindrome(String s) { + int l = s.length(), i, j; + for (i = 0, j = l - 1; i < l / 2; i++, j--) { + if ((int) s.charAt(i) != (int) s.charAt(j)) { + return false; + } + } + return true; + } + + public static void main(String[] a) { + Scanner in = new Scanner(System.in); + + int t = in.nextInt(); + String s[] = new String[t]; + + for (int i = 0; i < t; i++) { + s[i] = in.next(); + } + + for (int i = 0; i < t; i++) { + System.out.println(makePalindrome(s[i])); + } + } +} diff --git a/src/com/hackerrank/algorithms/strings/Pangram.java b/src/com/hackerrank/algorithms/strings/Pangram.java new file mode 100644 index 00000000..282b6d29 --- /dev/null +++ b/src/com/hackerrank/algorithms/strings/Pangram.java @@ -0,0 +1,42 @@ +package me.ramswaroop.algorithms.strings; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/22/15 + * @time: 8:47 AM + */ +public class Pangram { + + public static String isPangram(String s) { + + char c; + s = s.replaceAll("\\s+", ""); + s = s.toUpperCase(); + int[] alphabets = new int[26]; + + // check if all alphabets are present only once + for (int i = 0; i < s.length(); i++) { + c = s.charAt(i); + if (alphabets[c - 65] == 0) { + alphabets[c - 65] = 1; + } + } + + // check if all alphabets are present in string at least once + for (int i = 0; i < alphabets.length; i++) { + if (alphabets[i] == 0) return "not pangram"; + } + + return "pangram"; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String s = in.nextLine(); + System.out.println(isPangram(s)); + } +} diff --git a/src/com/hackerrank/algorithms/warmup/FlippingBits.java b/src/com/hackerrank/algorithms/warmup/FlippingBits.java new file mode 100644 index 00000000..9db5f21c --- /dev/null +++ b/src/com/hackerrank/algorithms/warmup/FlippingBits.java @@ -0,0 +1,32 @@ +package me.ramswaroop.algorithms.warmup; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 2/28/15 + * Time: 12:41 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class FlippingBits { + + static long flipBits(long i) { + return i ^ 4294967295l; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + + int t = Integer.parseInt(in.nextLine()); + long[] in_ar = new long[t]; + + for (int i = 0; i < t; i++) { + in_ar[i] = in.nextLong(); + } + + for (long i : in_ar) { + System.out.println(flipBits(i)); + } + } +} diff --git a/src/com/hackerrank/algorithms/warmup/LonelyInteger.java b/src/com/hackerrank/algorithms/warmup/LonelyInteger.java new file mode 100644 index 00000000..b60b695c --- /dev/null +++ b/src/com/hackerrank/algorithms/warmup/LonelyInteger.java @@ -0,0 +1,50 @@ +package me.ramswaroop.algorithms.warmup; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 2/28/15 + * Time: 12:16 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class LonelyInteger { + + static int lonelyInteger(int[] a) { + + Map map = new HashMap<>(); + for (int i : a) { + map.put(i, map.get(i) == null ? 1 : map.get(i) + 1); + } + + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 1) { + return entry.getKey(); + } + } + + return 1; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int res; + + int _a_size = Integer.parseInt(in.nextLine()); + int[] _a = new int[_a_size]; + int _a_item; + String next = in.nextLine(); + String[] next_split = next.split(" "); + + for (int _a_i = 0; _a_i < _a_size; _a_i++) { + _a_item = Integer.parseInt(next_split[_a_i]); + _a[_a_i] = _a_item; + } + + res = lonelyInteger(_a); + System.out.println(res); + } +} diff --git a/src/com/hackerrank/algorithms/warmup/LoveLetterMystery.java b/src/com/hackerrank/algorithms/warmup/LoveLetterMystery.java new file mode 100644 index 00000000..b0588dfd --- /dev/null +++ b/src/com/hackerrank/algorithms/warmup/LoveLetterMystery.java @@ -0,0 +1,37 @@ +package me.ramswaroop.algorithms.warmup; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/17/15 + * Time: 3:22 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class LoveLetterMystery { + static int calcPalindromeSteps(String s) { + int steps = 0, length = s.length(), a, b; + for (int i = 0, j = length - 1; i < length / 2; i++, j--) { + if ((a = (int) s.charAt(i)) != (b = (int) s.charAt(j))) { + steps += Math.abs(a - b); + } + } + return steps; + } + + public static void main(String[] a) { + Scanner in = new Scanner(System.in); + + int t = in.nextInt(); + String s[] = new String[t]; + + for (int i = 0; i < t; i++) { + s[i] = in.next(); + } + + for (int i = 0; i < t; i++) { + System.out.println(calcPalindromeSteps(s[i])); + } + } +} diff --git a/src/com/hackerrank/algorithms/warmup/MaximizingXor.java b/src/com/hackerrank/algorithms/warmup/MaximizingXor.java new file mode 100644 index 00000000..78865aa2 --- /dev/null +++ b/src/com/hackerrank/algorithms/warmup/MaximizingXor.java @@ -0,0 +1,38 @@ +package me.ramswaroop.algorithms.warmup; + +import java.util.Scanner; +import java.util.TreeSet; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/7/15 + * Time: 11:07 AM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class MaximizingXor { + + static int maxXor(int l, int r) { + TreeSet res = new TreeSet(); + for (int i = l; i <= r; i++) { + for (int j = i; j <= r; j++) { + res.add(i ^ j); + } + } + return (int) res.last(); + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int res; + int _l; + _l = Integer.parseInt(in.nextLine()); + + int _r; + _r = Integer.parseInt(in.nextLine()); + + res = maxXor(_l, _r); + System.out.println(res); + + } +} diff --git a/src/com/hackerrank/algorithms/warmup/UtopianTree.java b/src/com/hackerrank/algorithms/warmup/UtopianTree.java new file mode 100644 index 00000000..ca0d5556 --- /dev/null +++ b/src/com/hackerrank/algorithms/warmup/UtopianTree.java @@ -0,0 +1,40 @@ +package me.ramswaroop.algorithms.warmup; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 3/1/15 + * Time: 3:07 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class UtopianTree { + static int calcHeight(int growthCycles) { + int h = 1; + + for (int i = 1; i <= growthCycles; i++) { + if (i % 2 != 0) + h *= 2; + else + h += 1; + } + + return h; + } + + public static void main(String[] a) { + Scanner in = new Scanner(System.in); + + int t = in.nextInt(); + int n[] = new int[t]; + + for (int i = 0; i < t; i++) { + n[i] = in.nextInt(); + } + + for (int i = 0; i < t; i++) { + System.out.println(calcHeight(n[i])); + } + } +} diff --git a/src/com/hackerrank/bitmanipulation/CounterGame.java b/src/com/hackerrank/bitmanipulation/CounterGame.java new file mode 100644 index 00000000..e5ede2a2 --- /dev/null +++ b/src/com/hackerrank/bitmanipulation/CounterGame.java @@ -0,0 +1,54 @@ +package me.ramswaroop.bitmanipulation; + +import java.math.BigInteger; +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/24/15 + * @time: 12:03 PM + */ +public class CounterGame { + + public static boolean isPowerOf2(BigInteger n) { + return !n.equals(BigInteger.ZERO) && (n.and(n.subtract(BigInteger.ONE))).equals(BigInteger.ZERO); + } + + public static BigInteger nextLowerPowerOf2(BigInteger n) { + BigInteger p = BigInteger.ONE; + while (p.compareTo(n) == -1) { + p = p.shiftLeft(1); + } + return (n.compareTo(BigInteger.ONE) == 1) ? p.shiftRight(1) : n; // check for n = 0 or 1; + } + + public static String computeWinner(BigInteger n) { + boolean louiseTurn = true; + while (!n.equals(BigInteger.ONE)) { + if (isPowerOf2(n)) { + n = n.shiftRight(1); + } else { + n = n.subtract(nextLowerPowerOf2(n)); + } + louiseTurn = !louiseTurn; + } + return (louiseTurn) ? "Richard" : "Louise"; + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + int t = Integer.parseInt(in.nextLine()); + BigInteger[] in_ar = new BigInteger[t]; + + for (int i = 0; i < t; i++) { + in_ar[i] = in.nextBigInteger(); + } + + for (BigInteger i : in_ar) { + System.out.println(computeWinner(i)); + } + } +} diff --git a/src/com/hackerrank/bitmanipulation/Solution.java b/src/com/hackerrank/bitmanipulation/Solution.java new file mode 100644 index 00000000..84bbebd9 --- /dev/null +++ b/src/com/hackerrank/bitmanipulation/Solution.java @@ -0,0 +1,59 @@ +package me.ramswaroop.bitmanipulation; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/24/15 + * @time: 10:25 PM + */ +public class Solution { + private final static byte BITS; + private final static long[] BIT_COUNT_TO_BIT; + static { + BITS = 32; + BIT_COUNT_TO_BIT = new long[BITS+1]; + BIT_COUNT_TO_BIT[0] = 1; + for(byte i = 1; i <= BITS; i++){ + BIT_COUNT_TO_BIT[i] = ((BIT_COUNT_TO_BIT[i-1] - 1L) << 1) + (1L << (i-1)) + 1L; + } + } + public static void main(String[] args) throws IOException { + StringBuffer sb = new StringBuffer(); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + for(short T = Short.parseShort(br.readLine()); T > 0; T--){ + String[] temp = br.readLine().split(" "); + int A = Integer.parseInt(temp[0]); + int B = Integer.parseInt(temp[1]); + long bits = bitCountToNum(B) - bitCountToNum(A) + getHammingWeight(A); + bits += (A < 0 && B >= 0) ? BIT_COUNT_TO_BIT[BITS] - 1L: 0; + sb.append(bits + "\n"); + } + System.out.print(sb); + } + //Bit count in number + private static int getHammingWeight(int n){ + byte count = 0; + while(n != 0){ + count++; + n &= n-1; + } + return count; + } + //Bit count to number, inclusive + private static long bitCountToNum(int n){ + long count = 0; + for(byte b = BITS; n != 0;){ + int x = 1 << --b; + if((n & x) != 0){ + n &= ~x; + count += BIT_COUNT_TO_BIT[b] + n; + } + } + return count; + } +} diff --git a/src/com/hackerrank/bitmanipulation/TwosCompliment.java b/src/com/hackerrank/bitmanipulation/TwosCompliment.java new file mode 100644 index 00000000..1f379cd2 --- /dev/null +++ b/src/com/hackerrank/bitmanipulation/TwosCompliment.java @@ -0,0 +1,36 @@ +package me.ramswaroop.bitmanipulation; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 6/24/15 + * @time: 10:25 PM + */ +public class TwosCompliment { + + public static long countSetBitsInRange(int start, int end) { + int count = 0; + for (int i = start; i <= end; i++) { + count += Integer.bitCount(i); + } + return count; + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + int t = Integer.parseInt(in.nextLine()); + String[][] in_ar = new String[t][2]; + + for (int i = 0; i < t; i++) { + in_ar[i] = in.nextLine().split(" "); + } + + for (String[] i : in_ar) { + System.out.println(countSetBitsInRange(Integer.parseInt(i[0]), Integer.parseInt(i[1]))); + } + } +} diff --git a/src/com/hackerrank/java/oops/JavaInheritance.java b/src/com/hackerrank/java/oops/JavaInheritance.java new file mode 100644 index 00000000..d12db5c0 --- /dev/null +++ b/src/com/hackerrank/java/oops/JavaInheritance.java @@ -0,0 +1,30 @@ +package me.ramswaroop.java.oops; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 7/19/15 + * @time: 3:36 PM + */ +public class JavaInheritance { + + public void JavaInheritance() { + + } + + public static void main(String a[]) { + + } +} + + +class Arithmetic { + +} + +class Adder extends Arithmetic { + int add(int a, int b) { + return a + b; + } +} diff --git a/src/com/hackerrank/practice/RandomTest.java b/src/com/hackerrank/practice/RandomTest.java new file mode 100644 index 00000000..4d29fd8c --- /dev/null +++ b/src/com/hackerrank/practice/RandomTest.java @@ -0,0 +1,53 @@ +package me.ramswaroop.practice; + +import java.util.Random; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 2/23/15 + * Time: 12:48 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +public class RandomTest { + public static void main(String[] args) { + Random r = new Random(); + System.out.println(r.nextInt(1)); + System.out.println(randInt(0, 1, false)); + //System.out.print(randInts(1, 0)); + } + + public static int randInt(int start, int end, boolean startInclusive) { + int diff = end - start; + if (start < 0 || end < 0 || diff <= 0) return -1; + + Random random = new Random(); + if (startInclusive) { + return random.nextInt(diff + 1) + start; + } else { + return random.nextInt(diff) + start + 1; + } + } + + public static int randInt(int max, int exclude) { + // some validation + if (max <= 0) return -1; + Random random = new Random(); + int randInt = random.nextInt(max); + if (randInt == exclude) { + return (randInt == max) ? randInt - 1 : randInt + 1; + } else { + return randInt; + } + } + + public static int[] randInts(int max, int exclude) { + int[] randInts = new int[2]; + randInts[0] = randInt(max, exclude); + do { + randInts[1] = randInt(max, exclude); + } while ((randInts[0] != -1 & randInts[1] != -1) && (randInts[0] == randInts[1])); + + return randInts; + } +} diff --git a/src/com/hackerrank/practice/SPOJ1.java b/src/com/hackerrank/practice/SPOJ1.java new file mode 100644 index 00000000..1fd0e4d6 --- /dev/null +++ b/src/com/hackerrank/practice/SPOJ1.java @@ -0,0 +1,31 @@ +package me.ramswaroop.practice; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * User: ramswaroop + * Date: 4/22/15 + * Time: 7:40 PM + * To change this template go to Preferences | IDE Settings | File and Code Templates + */ +class SPOJ1 { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + + List inputList = new ArrayList<>(); + int input; + for (; ;) { + input = Integer.parseInt(in.nextLine()); + if (input == 42) break; + inputList.add(input); + } + + for (long i : inputList) { + System.out.println(i); + } + } +} From 66574c631b10b3763f77a115ae65d298f7d81dcf Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Thu, 22 Oct 2015 13:33:48 +0530 Subject: [PATCH 381/417] coded + unit tested + code refactoring --- .../arraysandsorting/InsertionSort1.java | 2 +- .../arraysandsorting/InsertionSort2.java | 2 +- .../arraysandsorting/IntroTutorial.java | 2 +- .../arraysandsorting/LoopInvariant.java | 2 +- .../arraysandsorting/QuickSort1.java | 2 +- .../arraysandsorting/QuickSort2.java | 2 +- .../arraysandsorting/RunningTime.java | 2 +- .../strings/AlternatingCharacters.java | 2 +- .../algorithms/strings/PalindromeIndex.java | 2 +- .../algorithms/strings/Pangram.java | 2 +- .../algorithms/strings/TwoStrings.java | 40 +++++++++++++++ .../ramswaroop/backtracking/RatInAMaze.java | 24 ++++++++- .../{SubString.java => SubStringCheck.java} | 2 +- src/me/ramswaroop/strings/SubStrings.java | 49 +++++++++++++++++++ 14 files changed, 122 insertions(+), 13 deletions(-) create mode 100644 src/com/hackerrank/algorithms/strings/TwoStrings.java rename src/me/ramswaroop/strings/{SubString.java => SubStringCheck.java} (97%) create mode 100644 src/me/ramswaroop/strings/SubStrings.java diff --git a/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java index ba62e57e..7dadb554 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java index dfbf153a..93ee48a3 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java b/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java index 6a1c904a..aac8e479 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.Arrays; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java b/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java index 01e88383..2b8613e9 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java index c95fa8e3..7e14ca9b 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java index ef35849a..e58420bd 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.ArrayList; import java.util.List; diff --git a/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java b/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java index 2c435043..36a55877 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/RunningTime.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.arraysandsorting; +package com.hackerrank.algorithms.arraysandsorting; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java b/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java index 3ce7ab06..823f1e61 100644 --- a/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java +++ b/src/com/hackerrank/algorithms/strings/AlternatingCharacters.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.strings; +package com.hackerrank.algorithms.strings; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/strings/PalindromeIndex.java b/src/com/hackerrank/algorithms/strings/PalindromeIndex.java index 5b780ddd..b9d76784 100644 --- a/src/com/hackerrank/algorithms/strings/PalindromeIndex.java +++ b/src/com/hackerrank/algorithms/strings/PalindromeIndex.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.strings; +package com.hackerrank.algorithms.strings; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/strings/Pangram.java b/src/com/hackerrank/algorithms/strings/Pangram.java index 282b6d29..27fffa88 100644 --- a/src/com/hackerrank/algorithms/strings/Pangram.java +++ b/src/com/hackerrank/algorithms/strings/Pangram.java @@ -1,4 +1,4 @@ -package me.ramswaroop.algorithms.strings; +package com.hackerrank.algorithms.strings; import java.util.Scanner; diff --git a/src/com/hackerrank/algorithms/strings/TwoStrings.java b/src/com/hackerrank/algorithms/strings/TwoStrings.java new file mode 100644 index 00000000..f2b0ea1f --- /dev/null +++ b/src/com/hackerrank/algorithms/strings/TwoStrings.java @@ -0,0 +1,40 @@ +package com.hackerrank.algorithms.strings; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/22/15 + * @time: 10:08 AM + */ +public class TwoStrings { + + public static String isSubstringInBoth(String[] a) { + char[] alphabets = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', + 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z'}; + + for (int i = 0; i < alphabets.length; i++) { + if (a[0].indexOf(alphabets[i]) != -1 && a[1].indexOf(alphabets[i]) != -1) return "YES"; + } + + return "NO"; + } + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + int t = Integer.parseInt(in.nextLine()); + String[][] input = new String[t][2]; + + for (int i = 0; i < t; i++) { + input[i][0] = in.nextLine(); + input[i][1] = in.nextLine(); + } + + for (int i = 0; i < t; i++) { + System.out.println(isSubstringInBoth(input[i])); + } + } +} diff --git a/src/me/ramswaroop/backtracking/RatInAMaze.java b/src/me/ramswaroop/backtracking/RatInAMaze.java index ffaff5ec..09aaf096 100644 --- a/src/me/ramswaroop/backtracking/RatInAMaze.java +++ b/src/me/ramswaroop/backtracking/RatInAMaze.java @@ -9,6 +9,12 @@ */ public class RatInAMaze { + /** + * @param i + * @param j + * @param maze + * @return + */ public static boolean isValidMove(int i, int j, int[][] maze) { if (i >= 0 && i < maze.length && j >= 0 && j < maze[0].length && maze[i][j] == 1) { return true; @@ -17,6 +23,15 @@ public static boolean isValidMove(int i, int j, int[][] maze) { } } + /** + * @param i + * @param j + * @param xMoves + * @param yMoves + * @param maze + * @param path + * @return + */ public static boolean isValidPath(int i, int j, int[] xMoves, int[] yMoves, int[][] maze, int[][] path) { if (i == maze.length - 1 && j == maze[0].length - 1) return true; @@ -38,13 +53,18 @@ public static boolean isValidPath(int i, int j, int[] xMoves, int[] yMoves, int[ return false; } + /** + * @param i is the start row + * @param j is the start column + * @param maze is the maze in which a path has to be found (1 denotes rat can traverse and 0 denotes it cannot) + */ public static void printMazePath(int i, int j, int[][] maze) { int[] xMoves = {0, 1}; int[] yMoves = {1, 0}; - + int[][] path = new int[maze.length][maze[0].length]; - + System.out.println("Maze"); System.out.println("---------------"); print2DMatrix(maze); diff --git a/src/me/ramswaroop/strings/SubString.java b/src/me/ramswaroop/strings/SubStringCheck.java similarity index 97% rename from src/me/ramswaroop/strings/SubString.java rename to src/me/ramswaroop/strings/SubStringCheck.java index 09978f11..77f79a83 100644 --- a/src/me/ramswaroop/strings/SubString.java +++ b/src/me/ramswaroop/strings/SubStringCheck.java @@ -8,7 +8,7 @@ * @time: 1:15 PM * @see: me.ramswaroop.strings.StringRotation for a similar problem. */ -public class SubString { +public class SubStringCheck { /** * Naive approach to determine whether string {@param s2} is a diff --git a/src/me/ramswaroop/strings/SubStrings.java b/src/me/ramswaroop/strings/SubStrings.java new file mode 100644 index 00000000..d5e085d2 --- /dev/null +++ b/src/me/ramswaroop/strings/SubStrings.java @@ -0,0 +1,49 @@ +package me.ramswaroop.strings; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/22/15 + * @time: 11:16 AM + */ +public class SubStrings { + + /** + * Prints all sub-strings of string {@param s} iteratively. + * + * @param s + */ + public static void printAllSubStrings(String s) { + for (int i = 0; i < s.length(); i++) { + for (int j = i; j < s.length(); j++) { + System.out.println(s.substring(i, j + 1)); + } + } + } + + /** + * Prints all sub-strings of string {@param s} recursively. + * + * @param s + */ + public static void printAllSubStringsRecursive(String s) { + if (s.length() == 0) return; + + for (int i = 1; i <= s.length(); i++) { + System.out.println(s.substring(0, i)); + } + printAllSubStrings(s.substring(1)); + } + + public static void main(String a[]) { + System.out.println("----Iterative----"); + printAllSubStrings("ram"); + System.out.println("--------"); + printAllSubStrings(""); + System.out.println("----Recursive----"); + printAllSubStringsRecursive("ram"); + System.out.println("--------"); + printAllSubStringsRecursive(""); + } +} From 87c12ddfa5d0a82b051db8f87148e223c69eed23 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 23 Oct 2015 08:46:18 +0530 Subject: [PATCH 382/417] coded + unit tested --- .../arrays/sorting/CheckSorted.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/me/ramswaroop/arrays/sorting/CheckSorted.java diff --git a/src/me/ramswaroop/arrays/sorting/CheckSorted.java b/src/me/ramswaroop/arrays/sorting/CheckSorted.java new file mode 100644 index 00000000..b7464176 --- /dev/null +++ b/src/me/ramswaroop/arrays/sorting/CheckSorted.java @@ -0,0 +1,66 @@ +package me.ramswaroop.arrays.sorting; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/23/15 + * @time: 8:30 AM + */ +public class CheckSorted { + + /** + * Determines whether array {@param a} is sorted or not. + * Sort order can be either ascending or descending. + * + * @param a + * @return + */ + public static boolean isSorted(int[] a) { + + if (a.length == 0) return true; + + int i; + boolean isAscending; + + // go to index where you find a number different from + // previous number (req. to determine sort order) + for (i = 1; i < a.length; i++) { + if (a[i] != a[i - 1]) break; + } + + // all elements equal or only a single element + if (i == a.length) { + return true; + } + + // determine sort order of array + if (a[i] > a[i - 1]) { + isAscending = true; + } else { + isAscending = false; + } + + // check if appropriate sort property is hold for rest of array + if (isAscending) { + for (; i < a.length; i++) { + if (a[i] < a[i - 1]) return false; + } + } else { + for (; i < a.length; i++) { + if (a[i] > a[i - 1]) return false; + } + } + + return true; + } + + public static void main(String a[]) { + System.out.println(isSorted(new int[]{1, 2, 3, 4, 5})); + System.out.println(isSorted(new int[]{5, 4, 3, 2, 1})); + System.out.println(isSorted(new int[]{})); + System.out.println(isSorted(new int[]{0})); + System.out.println(isSorted(new int[]{0, 0, 0, 0, 0, 0})); + System.out.println(isSorted(new int[]{4, 7, 9, 1, 0})); + } +} From b768583944501dc7b163dbe3eb3d7ef92a12337e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 23 Oct 2015 08:58:00 +0530 Subject: [PATCH 383/417] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 201d756b..bfcba90a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Algorithms and Data Structures in Java -The repo consists of solutions to numerous problems using different data structures and algorithms, where all solutions are coded purely in Java. You can also refer my [Java Notes](http://java.ramswaroop.me) for a quick refresh on the Java concepts. +The repo consists of solutions to numerous problems using different data structures and algorithms, where all solutions are coded purely in Java. It also contains solutions to HackerRank problems which I have solved so far. + +You can also refer my [Java Notes](http://java.ramswaroop.me) for a quick refresh on the Java concepts. ## Environment From 9977bda5cae99c936fed36cb9d5a62c6080c8369 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 24 Oct 2015 15:44:49 +0530 Subject: [PATCH 384/417] code improvements --- .../ramswaroop/arrays/sorting/QuickSort.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/me/ramswaroop/arrays/sorting/QuickSort.java b/src/me/ramswaroop/arrays/sorting/QuickSort.java index 946265db..14320208 100644 --- a/src/me/ramswaroop/arrays/sorting/QuickSort.java +++ b/src/me/ramswaroop/arrays/sorting/QuickSort.java @@ -19,53 +19,53 @@ public class QuickSort { * at its correct position. * * @param ar - * @param low - * @param high + * @param startIndex + * @param endIndex * @return position of the pivot element */ - public static int partition(int[] ar, int low, int high) { - int pivot = high, temp; + public static int partition(int[] ar, int startIndex, int endIndex) { + int pivot = endIndex, temp; - for (int i = low; i < high; i++) { + for (int i = startIndex; i < endIndex; i++) { /** * if ith element is smaller than pivot element then * swap it with the last larger element known */ if (ar[i] < ar[pivot]) { - // swap a[low] with a[i] - temp = ar[low]; - ar[low] = ar[i]; + // swap a[startIndex] with a[i] + temp = ar[startIndex]; + ar[startIndex] = ar[i]; ar[i] = temp; - low++; + startIndex++; } } // place the pivot element in its correct position - temp = ar[low]; - ar[low] = ar[pivot]; + temp = ar[startIndex]; + ar[startIndex] = ar[pivot]; ar[pivot] = temp; - return low; + return startIndex; } /** * Recursive Quick sort. - * NOTE: This function is tail-recursive (doesn't use - * extra stack space per recursive call). + * NOTE: This function is tail-recursive (doesn't use extra stack space per recursive call in many + * programming languages but not in Java as it doesn't support tail-recursive optimization). *

* Time complexity: * Best Case: O(nlogn) * Worst Case: O(n*n) * * @param ar - * @param low - * @param high + * @param startIndex + * @param endIndex */ - public static void quickSort(int[] ar, int low, int high) { - if (low < high) { - int partition = partition(ar, low, high); - quickSort(ar, low, partition - 1); - quickSort(ar, partition + 1, high); + public static void quickSort(int[] ar, int startIndex, int endIndex) { + if (startIndex < endIndex) { + int partition = partition(ar, startIndex, endIndex); + quickSort(ar, startIndex, partition - 1); + quickSort(ar, partition + 1, endIndex); } } From f8118655dc862eb8840a95ef83ddf73fc56c553b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sat, 24 Oct 2015 16:24:39 +0530 Subject: [PATCH 385/417] coded + unit tested --- .../arraysandsorting/QuickSort2.java | 50 ++++++++++++------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java index e58420bd..a366da37 100644 --- a/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java +++ b/src/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java @@ -1,7 +1,5 @@ package com.hackerrank.algorithms.arraysandsorting; -import java.util.ArrayList; -import java.util.List; import java.util.Scanner; /** @@ -13,27 +11,43 @@ */ public class QuickSort2 { - static void quickSort(int[] ar, int start, int end) { - int pivot = ar[0]; - List ar1 = new ArrayList<>(); - List ar2 = new ArrayList<>(); - - for (int i = start; i < end; i++) { - if (ar[i] < pivot) { - ar1.add(ar[i]); - } else if (ar[i] > pivot) { - ar2.add(ar[i]); + static int partition(int[] a, int start, int end) { + + int pivot = start, temp; + + for (int i = start + 1; i <= end; i++) { + // maintains the relative positioning of elements in each partition + if (a[i] < a[pivot]) { + start++; + temp = a[i]; + int j; + for (j = i; j > start; j--) { + a[j] = a[j - 1]; + } + a[j] = temp; } } - //TODO + temp = a[pivot]; + while (pivot < start) { + a[pivot] = a[pivot + 1]; + pivot++; + } + a[pivot] = temp; + + return pivot; } - static void printArray(int[] ar) { - for (int n : ar) { - System.out.print(n + " "); + static void quickSort(int[] ar, int start, int end) { + if (start < end) { + int p = partition(ar, start, end); + quickSort(ar, start, p - 1); + quickSort(ar, p + 1, end); + for (int i = start; i <= end; i++) { + System.out.print(ar[i] + " "); + } + System.out.println(); } - System.out.println(""); } public static void main(String[] args) { @@ -43,6 +57,6 @@ public static void main(String[] args) { for (int i = 0; i < n; i++) { ar[i] = in.nextInt(); } - quickSort(ar, 0, ar.length); + quickSort(ar, 0, n - 1); } } From 51533247a1ea198223a23692fb14626e7ddfa5aa Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 25 Oct 2015 22:41:03 +0530 Subject: [PATCH 386/417] coded + unit tested --- .../ramswaroop/strings/RemoveExtraSpaces.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/me/ramswaroop/strings/RemoveExtraSpaces.java diff --git a/src/me/ramswaroop/strings/RemoveExtraSpaces.java b/src/me/ramswaroop/strings/RemoveExtraSpaces.java new file mode 100644 index 00000000..1e2cb81e --- /dev/null +++ b/src/me/ramswaroop/strings/RemoveExtraSpaces.java @@ -0,0 +1,59 @@ +package me.ramswaroop.strings; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/25/15 + * @time: 9:44 PM + */ +public class RemoveExtraSpaces { + + /** + * Removes extra spaces in string {@param s} without creating a + * extra variable to hold the result, in O(n) time complexity. + * + * @param s + * @return + */ + public static String removeExtraSpaces(String s) { + char[] c = s.toCharArray(); + + int j = c.length; + for (int i = 1; i < c.length; i++) { + // check for two or more consecutive spaces + if (c[i] == ' ' && c[i - 1] == ' ') { + // if extra spaces encountered for the 1st time + if (j == c.length) j = i; + + // skip all extra spaces + while (i < c.length && c[i] == ' ') { + i++; + } + + // if reached end of string then stop + if (i == c.length) break; + } + + // copy characters occurring after extra spaces to their appropriate positions + while (i < c.length && j < c.length) { + if (c[i] == ' ' && c[i - 1] == ' ') break; + + c[j] = c[i]; + i++; + j++; + } + } + + return String.valueOf(Arrays.copyOf(c, j)); + } + + public static void main(String a[]) { + System.out.println(removeExtraSpaces("ram swaroop is a good boy.")); + System.out.println(removeExtraSpaces("ram swaroop is a good boy.")); + System.out.println(removeExtraSpaces("ram swaroop is a good boy .")); + System.out.println(removeExtraSpaces(" ram swaroop is a good boy .")); + } +} From 80abc1872e5c4aeb62036a26ba17155dfb8bc262 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 26 Oct 2015 09:49:32 +0530 Subject: [PATCH 387/417] added comments --- src/me/ramswaroop/strings/RemoveExtraSpaces.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/strings/RemoveExtraSpaces.java b/src/me/ramswaroop/strings/RemoveExtraSpaces.java index 1e2cb81e..9b2967d4 100644 --- a/src/me/ramswaroop/strings/RemoveExtraSpaces.java +++ b/src/me/ramswaroop/strings/RemoveExtraSpaces.java @@ -19,9 +19,10 @@ public class RemoveExtraSpaces { * @return */ public static String removeExtraSpaces(String s) { + char[] c = s.toCharArray(); - int j = c.length; + for (int i = 1; i < c.length; i++) { // check for two or more consecutive spaces if (c[i] == ' ' && c[i - 1] == ' ') { @@ -39,6 +40,7 @@ public static String removeExtraSpaces(String s) { // copy characters occurring after extra spaces to their appropriate positions while (i < c.length && j < c.length) { + // stop when you encounter extra spaces again if (c[i] == ' ' && c[i - 1] == ' ') break; c[j] = c[i]; @@ -53,6 +55,7 @@ public static String removeExtraSpaces(String s) { public static void main(String a[]) { System.out.println(removeExtraSpaces("ram swaroop is a good boy.")); System.out.println(removeExtraSpaces("ram swaroop is a good boy.")); + System.out.println(removeExtraSpaces(" ram swaroop is a good boy.")); System.out.println(removeExtraSpaces("ram swaroop is a good boy .")); System.out.println(removeExtraSpaces(" ram swaroop is a good boy .")); } From 8288e23ee219b965bdf31061eb14c38209fb23ef Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 26 Oct 2015 09:50:48 +0530 Subject: [PATCH 388/417] added use cases --- src/me/ramswaroop/strings/RemoveExtraSpaces.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/me/ramswaroop/strings/RemoveExtraSpaces.java b/src/me/ramswaroop/strings/RemoveExtraSpaces.java index 9b2967d4..1ea76b42 100644 --- a/src/me/ramswaroop/strings/RemoveExtraSpaces.java +++ b/src/me/ramswaroop/strings/RemoveExtraSpaces.java @@ -58,5 +58,8 @@ public static void main(String a[]) { System.out.println(removeExtraSpaces(" ram swaroop is a good boy.")); System.out.println(removeExtraSpaces("ram swaroop is a good boy .")); System.out.println(removeExtraSpaces(" ram swaroop is a good boy .")); + System.out.println(removeExtraSpaces(" ")); + System.out.println(removeExtraSpaces("")); + System.out.println(removeExtraSpaces(" ")); } } From 5e02c250d9995a793c3b5e45672ad3435f66cf9f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 26 Oct 2015 22:17:54 +0530 Subject: [PATCH 389/417] coded + unit tested --- .../arrays/sorting/PancakeSort.java | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/me/ramswaroop/arrays/sorting/PancakeSort.java diff --git a/src/me/ramswaroop/arrays/sorting/PancakeSort.java b/src/me/ramswaroop/arrays/sorting/PancakeSort.java new file mode 100644 index 00000000..3364f999 --- /dev/null +++ b/src/me/ramswaroop/arrays/sorting/PancakeSort.java @@ -0,0 +1,80 @@ +package me.ramswaroop.arrays.sorting; + +import java.util.Arrays; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/26/15 + * @time: 9:20 PM + */ +public class PancakeSort { + + /** + * Sorts the array {@param a} in-place in O(n^2) time complexity. + *

+ * This can also be seen as: Sort the array {@param a} using a method + * {@code reverse(int[] a, int end)} which reverses array {@code int[] a} + * from {@code 0} index till {@code end} index (both inclusive). + * + * @param a + */ + public static void sort(int[] a) { + + int maxIndex; // max element's index + int unsortedIndex = a.length - 1; // index till which elements are unsorted + + while (unsortedIndex > 0) { + maxIndex = 0; + // find max element's index + for (int j = 1; j <= unsortedIndex; j++) { + if (a[j] > a[maxIndex]) { + maxIndex = j; + } + } + reverse(a, maxIndex); // bring the max element to the front + reverse(a, unsortedIndex); // move the max element to its appropriate index + unsortedIndex--; + } + } + + /** + * Reverses array {@param a} from {@code 0} index + * till {@code end} index. + * + * @param a + * @param end + */ + public static void reverse(int[] a, int end) { + int temp; + for (int i = 0; i <= end / 2; i++) { + temp = a[i]; + a[i] = a[end - i]; + a[end - i] = temp; + } + } + + public static void main(String a[]) { + int[] ar = {1, 2, 3, 4, 5, 6}; + System.out.println(Arrays.toString(ar)); + sort(ar); + System.out.println(Arrays.toString(ar)); + ar = new int[]{3, 4, 7, 1, 9, 0}; + System.out.println(Arrays.toString(ar)); + sort(ar); + System.out.println(Arrays.toString(ar)); + ar = new int[]{6, 5, 4, 3, 2, 1}; + System.out.println(Arrays.toString(ar)); + sort(ar); + System.out.println(Arrays.toString(ar)); + ar = new int[]{}; + System.out.println(Arrays.toString(ar)); + sort(ar); + System.out.println(Arrays.toString(ar)); + ar = new int[]{1}; + System.out.println(Arrays.toString(ar)); + sort(ar); + System.out.println(Arrays.toString(ar)); + } +} From df14445aa03df3ab2038d194a7466cb575b53e7e Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 26 Oct 2015 22:21:03 +0530 Subject: [PATCH 390/417] code improvements --- src/me/ramswaroop/arrays/sorting/PancakeSort.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/me/ramswaroop/arrays/sorting/PancakeSort.java b/src/me/ramswaroop/arrays/sorting/PancakeSort.java index 3364f999..6d229cdb 100644 --- a/src/me/ramswaroop/arrays/sorting/PancakeSort.java +++ b/src/me/ramswaroop/arrays/sorting/PancakeSort.java @@ -33,8 +33,11 @@ public static void sort(int[] a) { maxIndex = j; } } - reverse(a, maxIndex); // bring the max element to the front - reverse(a, unsortedIndex); // move the max element to its appropriate index + // move the max element to its appropriate index if its not already in its correct index + if (maxIndex != unsortedIndex) { + reverse(a, maxIndex); // bring the max element to the front + reverse(a, unsortedIndex); // move the max element to its appropriate index + } unsortedIndex--; } } From ca08f5965389bfcac038cf229fa126186fad696f Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Tue, 27 Oct 2015 23:45:27 +0530 Subject: [PATCH 391/417] added another method --- src/me/ramswaroop/trees/CheckForBST.java | 29 +++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/me/ramswaroop/trees/CheckForBST.java b/src/me/ramswaroop/trees/CheckForBST.java index 2f8aaeb2..55fa2ca2 100644 --- a/src/me/ramswaroop/trees/CheckForBST.java +++ b/src/me/ramswaroop/trees/CheckForBST.java @@ -14,15 +14,15 @@ * @author: ramswaroop * @date: 6/26/15 * @time: 7:14 PM - * - * Concept: Perform in-order traversal of the tree and if - * the result isn't in ascending order then returns false. */ public class CheckForBST { /** * Traverse the tree in in-order fashion and insert all nodes * in a list and check for sort order of list. + *

+ * Concept: Perform in-order traversal of the tree and if + * the result isn't in ascending order then returns false. * * @param node * @param list @@ -47,6 +47,8 @@ public static > boolean isBST(BinaryNode node, List + * Concept: Perform in-order traversal of the tree and if + * the result isn't in ascending order then returns false. * * @param node * @param prev @@ -68,6 +70,23 @@ public static > boolean isBST(BinaryNode node, Binary return left && right; } + /** + * @param node + * @param minValue + * @param maxValue + * @param + * @return + */ + public static > boolean isBST(BinaryNode node, E minValue, E maxValue) { + if (node == null) return true; + + if (node.value.compareTo(minValue) < 0 || node.value.compareTo(maxValue) > 0) { + return false; + } + + return isBST(node.left, minValue, node.value) && isBST(node.right, node.value, maxValue); + } + public static void main(String a[]) { BinarySearchTree binarySearchTree = new BinarySearchTree<>(); binarySearchTree.put(6); @@ -87,5 +106,9 @@ public static void main(String a[]) { binaryTree.put(9); out.println("Is BST: "); out.println(isBST(binaryTree.root, new BinaryNode(null))); + out.println("Is BST: "); + out.println(isBST(binarySearchTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); + out.println("Is BST: "); + out.println(isBST(binaryTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); } } From 72c9c3b17e2eb3afe4358447ecd1b487a062f045 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 28 Oct 2015 00:03:16 +0530 Subject: [PATCH 392/417] added comments --- src/me/ramswaroop/trees/CheckForBST.java | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/me/ramswaroop/trees/CheckForBST.java b/src/me/ramswaroop/trees/CheckForBST.java index 55fa2ca2..4ff0a6ab 100644 --- a/src/me/ramswaroop/trees/CheckForBST.java +++ b/src/me/ramswaroop/trees/CheckForBST.java @@ -21,8 +21,8 @@ public class CheckForBST { * Traverse the tree in in-order fashion and insert all nodes * in a list and check for sort order of list. *

- * Concept: Perform in-order traversal of the tree and if - * the result isn't in ascending order then returns false. + * Concept: In-order traversal of a BST is always sorted in ascending + * manner. * * @param node * @param list @@ -45,10 +45,12 @@ public static > boolean isBST(BinaryNode node, List - * Concept: Perform in-order traversal of the tree and if - * the result isn't in ascending order then returns false. + * Concept: In-order traversal of a BST is always sorted in ascending + * manner. * * @param node * @param prev @@ -71,6 +73,12 @@ public static > boolean isBST(BinaryNode node, Binary } /** + * Simplest way to test whether a binary tree is a BST or not. + *

+ * CONCEPT: A node's left sub-tree cannot have a value more than + * the node's value and similarly the node's right sub-tree cannot + * have a value less than the node's value. + * * @param node * @param minValue * @param maxValue @@ -88,6 +96,7 @@ public static > boolean isBST(BinaryNode node, E minV } public static void main(String a[]) { + // in-order approach BinarySearchTree binarySearchTree = new BinarySearchTree<>(); binarySearchTree.put(6); binarySearchTree.put(3); @@ -106,6 +115,7 @@ public static void main(String a[]) { binaryTree.put(9); out.println("Is BST: "); out.println(isBST(binaryTree.root, new BinaryNode(null))); + // min max approach out.println("Is BST: "); out.println(isBST(binarySearchTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); out.println("Is BST: "); From 8e458a601b5519a52e3120ad0cea33601067d39c Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 28 Oct 2015 00:07:26 +0530 Subject: [PATCH 393/417] added comments --- src/me/ramswaroop/strings/AnagramsTogether.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/strings/AnagramsTogether.java b/src/me/ramswaroop/strings/AnagramsTogether.java index e98b3a06..9fd15ad3 100644 --- a/src/me/ramswaroop/strings/AnagramsTogether.java +++ b/src/me/ramswaroop/strings/AnagramsTogether.java @@ -11,14 +11,21 @@ */ public class AnagramsTogether { + /** + * Prints all the anagrams together from the string + * array {@param s}. + * + * @param s + */ public static void printAnagramsTogether(String[] s) { + // each key holds all the indexes of a anagram HashMap> hashMap = new HashMap<>(); for (int i = 0; i < s.length; i++) { char[] chars = s[i].toCharArray(); Arrays.sort(chars); - + List indexes = hashMap.get(String.valueOf(chars)); if (indexes == null) { indexes = new ArrayList<>(); From 6a390c5795d472530bd3dae99f60fad19d27e426 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 30 Oct 2015 21:35:30 +0530 Subject: [PATCH 394/417] coded + unit tested --- .../ramswaroop/arrays/NextLargerNumber.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/me/ramswaroop/arrays/NextLargerNumber.java diff --git a/src/me/ramswaroop/arrays/NextLargerNumber.java b/src/me/ramswaroop/arrays/NextLargerNumber.java new file mode 100644 index 00000000..699bcc1a --- /dev/null +++ b/src/me/ramswaroop/arrays/NextLargerNumber.java @@ -0,0 +1,84 @@ +package me.ramswaroop.arrays; + +import me.ramswaroop.arrays.sorting.QuickSort; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 10/30/15 + * @time: 11:01 AM + */ +public class NextLargerNumber { + + /** + * Finds the closest number which is larger + * than {@param n} by using only those digits + * present in {@param n} and using any digit + * only once. + * + * @param n + * @return + */ + public static int findNextLargerNumber(Integer n) { + + String str = n.toString(); + int len = str.length(); + int[] a = new int[len]; + int minIndex; + + // construct int array containing all + // digits in number {@param n} + for (int i = 0; i < len; i++) { + a[i] = Integer.parseInt(str.charAt(i) + ""); + } + + int i = len - 1; + while (i > 0) { + if (a[i] > a[i - 1]) break; + i--; + } + + if (i <= 0) return -1; + + minIndex = i; + int j = len - 1; + while (j >= i) { + if (a[j] < a[minIndex] && a[j] > a[i - 1]) { + minIndex = j; + } + j--; + } + + swap(a, i - 1, minIndex); + + QuickSort.quickSort(a, i, len - 1); + + StringBuilder builder = new StringBuilder(); + for (int k = 0; k < len; k++) { + builder.append(a[k]); + } + + return Integer.parseInt(builder.toString()); + } + + /** + * Swaps variables in {@param a} at {@param index1} with {@param index2}. + * + * @param a + * @param index1 + * @param index2 + */ + private static void swap(int[] a, int index1, int index2) { + int temp = a[index1]; + a[index1] = a[index2]; + a[index2] = temp; + } + + public static void main(String a[]) { + System.out.println(findNextLargerNumber(56)); + System.out.println(findNextLargerNumber(65)); + System.out.println(findNextLargerNumber(3451)); + System.out.println(findNextLargerNumber(534976)); + } +} From debc964d16a9a10369dcb7b8064f9be414f7c793 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 30 Oct 2015 21:43:13 +0530 Subject: [PATCH 395/417] added comments --- src/me/ramswaroop/arrays/NextLargerNumber.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/me/ramswaroop/arrays/NextLargerNumber.java b/src/me/ramswaroop/arrays/NextLargerNumber.java index 699bcc1a..e937577a 100644 --- a/src/me/ramswaroop/arrays/NextLargerNumber.java +++ b/src/me/ramswaroop/arrays/NextLargerNumber.java @@ -8,6 +8,7 @@ * @author: ramswaroop * @date: 10/30/15 * @time: 11:01 AM + * @see: http://www.geeksforgeeks.org/find-next-greater-number-set-digits/ */ public class NextLargerNumber { @@ -30,17 +31,21 @@ public static int findNextLargerNumber(Integer n) { // construct int array containing all // digits in number {@param n} for (int i = 0; i < len; i++) { - a[i] = Integer.parseInt(str.charAt(i) + ""); + a[i] = Integer.parseInt(String.valueOf(str.charAt(i))); } + // find the index where a digit is greater than its previous + // digit (from left) int i = len - 1; while (i > 0) { if (a[i] > a[i - 1]) break; i--; } + // digits are already in descending order, so return if (i <= 0) return -1; + // find index of smallest no. greater than a[i-1] minIndex = i; int j = len - 1; while (j >= i) { @@ -50,10 +55,14 @@ public static int findNextLargerNumber(Integer n) { j--; } + // swap a[i-1] with the smallest no. on the right + // of i-1 index which is larger than a[i-1] swap(a, i - 1, minIndex); + // sort all digits to the right of i-1 index QuickSort.quickSort(a, i, len - 1); + // construct the no. from the int array StringBuilder builder = new StringBuilder(); for (int k = 0; k < len; k++) { builder.append(a[k]); From 80a4649d32bdd270c8eb01b4cc60e7a807567a32 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Sun, 1 Nov 2015 21:26:15 +0530 Subject: [PATCH 396/417] coded + unit tested --- .../arrays/ArrangeNosToFormBiggestNo.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/me/ramswaroop/arrays/ArrangeNosToFormBiggestNo.java diff --git a/src/me/ramswaroop/arrays/ArrangeNosToFormBiggestNo.java b/src/me/ramswaroop/arrays/ArrangeNosToFormBiggestNo.java new file mode 100644 index 00000000..889a0254 --- /dev/null +++ b/src/me/ramswaroop/arrays/ArrangeNosToFormBiggestNo.java @@ -0,0 +1,47 @@ +package me.ramswaroop.arrays; + +import java.util.Arrays; +import java.util.Comparator; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 11/1/15 + * @time: 8:53 PM + */ +public class ArrangeNosToFormBiggestNo { + + /** + * Sorts no.s in array {@param a} such that if you form a number {@code n} + * by concatenating digits in order a[0]....a[size], it results being the + * largest number possible. + *

+ * For example, + * I/P: {54, 546, 548, 60} + * O/P: {60, 548, 546, 54} i.e, 6054854654 + *

+ * I/P: {1, 34, 3, 98, 9, 76, 45, 4} + * O/P: {9, 98, 76, 45, 4, 34, 3, 1} i.e, 998764543431 + * + * @param a + * @return + */ + public static Integer[] arrangeArrayOfNosToFormBiggestNo(Integer[] a) { + + Arrays.sort(a, new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return Integer.parseInt(o1 + "" + o2) > Integer.parseInt(o2 + "" + o1) ? -1 : 1; + } + }); + + return a; + } + + public static void main(String a[]) { + System.out.println(Arrays.toString(arrangeArrayOfNosToFormBiggestNo(new Integer[]{45, 567, 12, 1}))); + System.out.println(Arrays.toString(arrangeArrayOfNosToFormBiggestNo(new Integer[]{54, 546, 548, 60}))); + System.out.println(Arrays.toString(arrangeArrayOfNosToFormBiggestNo(new Integer[]{1, 34, 3, 98, 9, 76, 45, 4}))); + } +} From f20198680495723a408899a8400b0f5b5eaca2dd Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Wed, 11 Nov 2015 15:57:49 +0530 Subject: [PATCH 397/417] code refactoring --- .../ramswaroop/misc/MethodLocalVSInner.java | 2 +- src/me/ramswaroop/misc/ReplaceAll.java | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/me/ramswaroop/misc/ReplaceAll.java diff --git a/src/me/ramswaroop/misc/MethodLocalVSInner.java b/src/me/ramswaroop/misc/MethodLocalVSInner.java index 7c4a5954..359e9cf1 100644 --- a/src/me/ramswaroop/misc/MethodLocalVSInner.java +++ b/src/me/ramswaroop/misc/MethodLocalVSInner.java @@ -20,12 +20,12 @@ public static void main(String[] args) { } void go() { + new A().m(); class A { void m() { System.out.println("inner"); } } - new A().m(); } class A { diff --git a/src/me/ramswaroop/misc/ReplaceAll.java b/src/me/ramswaroop/misc/ReplaceAll.java new file mode 100644 index 00000000..7db7a4f1 --- /dev/null +++ b/src/me/ramswaroop/misc/ReplaceAll.java @@ -0,0 +1,21 @@ +package me.ramswaroop.misc; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 11/3/15 + * @time: 2:21 PM + */ +public class ReplaceAll { + + public static String replaceAll(String str, String regex, String replacement) { + return str.replaceAll(regex, replacement); + } + + public static void main(String a[]) { + System.out.println(replaceAll("ram s", "\\s+", "")); + } +} + + From f69abf254e0233a7374e337770fd9448910fb01b Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Fri, 13 Nov 2015 11:43:42 +0530 Subject: [PATCH 398/417] added java concept --- src/me/ramswaroop/misc/OuterClassAccess.java | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/me/ramswaroop/misc/OuterClassAccess.java diff --git a/src/me/ramswaroop/misc/OuterClassAccess.java b/src/me/ramswaroop/misc/OuterClassAccess.java new file mode 100644 index 00000000..9c299823 --- /dev/null +++ b/src/me/ramswaroop/misc/OuterClassAccess.java @@ -0,0 +1,28 @@ +package me.ramswaroop.misc; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 11/13/15 + * @time: 11:39 AM + */ +public class OuterClassAccess { + private int size = 7; + private static int length = 3; + + public static void main(String[] args) { + new OuterClassAccess().go(); + } + + void go() { + int size = 5; + System.out.println(new Inner().adder()); + } + + class Inner { + int adder() { + return size * length; // inner class can access static members of outer class + } + } +} From cdbe9a16835018e009737fdd9a72d05b809989d0 Mon Sep 17 00:00:00 2001 From: Ram swaroop Date: Mon, 8 Feb 2016 11:50:01 +0530 Subject: [PATCH 399/417] half done --- .../projecteuler/MultiplesOf3and5.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/com/hackerrank/projecteuler/MultiplesOf3and5.java diff --git a/src/com/hackerrank/projecteuler/MultiplesOf3and5.java b/src/com/hackerrank/projecteuler/MultiplesOf3and5.java new file mode 100644 index 00000000..fcbc341b --- /dev/null +++ b/src/com/hackerrank/projecteuler/MultiplesOf3and5.java @@ -0,0 +1,20 @@ +package com.hackerrank.projecteuler; + +import java.util.Scanner; + +/** + * Created by IntelliJ IDEA. + * + * @author: ramswaroop + * @date: 1/1/16 + * @time: 8:48 AM + */ +public class MultiplesOf3and5 { + + public static void main(String a[]) { + Scanner in = new Scanner(System.in); + + int t = Integer.parseInt(in.nextLine()); + + } +} From 56d1a2a6dd8118806bc52cfcbd345b0091e3b512 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Mon, 2 May 2016 19:50:59 +0100 Subject: [PATCH 400/417] camel casing fix --- .../algorithms/implementation/GridSearch.java | 53 +++++++++++++++++++ .../ConstructTreeFromInorderAndPreorder.java | 2 +- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/com/hackerrank/algorithms/implementation/GridSearch.java diff --git a/src/com/hackerrank/algorithms/implementation/GridSearch.java b/src/com/hackerrank/algorithms/implementation/GridSearch.java new file mode 100644 index 00000000..ccfcc8ab --- /dev/null +++ b/src/com/hackerrank/algorithms/implementation/GridSearch.java @@ -0,0 +1,53 @@ +package com.hackerrank.algorithms.implementation; + +import java.util.Scanner; + +/** + * Created by ramswaroop on 02/05/2016. + */ +public class GridSearch { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int t = in.nextInt(); + for (int a0 = 0; a0 < t; a0++) { + int R = in.nextInt(); + int C = in.nextInt(); + String G[] = new String[R]; + for (int G_i = 0; G_i < R; G_i++) { + G[G_i] = in.next(); + } + int r = in.nextInt(); + int c = in.nextInt(); + String P[] = new String[r]; + for (int P_i = 0; P_i < r; P_i++) { + P[P_i] = in.next(); + } + int count = 0; + int start = 0; + + loop1: + for (int G_i = 0; G_i < R; G_i++) { + if ((start = G[G_i].indexOf(P[0], start)) > -1) { + count = 1; + for (int P_i = 1; P_i < r && G_i + P_i < R; P_i++) { + if (G[G_i + P_i].indexOf(P[P_i]) != start) { + break; + } + count++; + } + if (count == r) { + System.out.println("YES"); + break; + } else { + continue loop1; + } + } + } + if (count != r) { + System.out.println("NO"); + } + } + } +} + diff --git a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java index 408eb573..4ad7cc38 100644 --- a/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java +++ b/src/me/ramswaroop/trees/ConstructTreeFromInorderAndPreorder.java @@ -11,7 +11,7 @@ * @date: 6/26/15 * @time: 5:34 PM */ -public class ConstructTreeFromInOrderAndPreorder { +public class ConstructTreeFromInOrderAndPreOrder { public > void constructTreeWithInOrderAndPreOrder(List> inOrder, List> preOrder) { From f6b047a90d5ba71627864d461972fb7ecedf9fe5 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Thu, 5 May 2016 17:52:31 -0400 Subject: [PATCH 401/417] solution works if no. of rows and columns are equal --- .../hackerrank/algorithms/implementation/GridSearch.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/com/hackerrank/algorithms/implementation/GridSearch.java b/src/com/hackerrank/algorithms/implementation/GridSearch.java index ccfcc8ab..3f8f7463 100644 --- a/src/com/hackerrank/algorithms/implementation/GridSearch.java +++ b/src/com/hackerrank/algorithms/implementation/GridSearch.java @@ -24,11 +24,10 @@ public static void main(String[] args) { P[P_i] = in.next(); } int count = 0; - int start = 0; + int start = -1; - loop1: for (int G_i = 0; G_i < R; G_i++) { - if ((start = G[G_i].indexOf(P[0], start)) > -1) { + if ((start = G[G_i].indexOf(P[0], start + 1)) > -1) { count = 1; for (int P_i = 1; P_i < r && G_i + P_i < R; P_i++) { if (G[G_i + P_i].indexOf(P[P_i]) != start) { @@ -40,7 +39,7 @@ public static void main(String[] args) { System.out.println("YES"); break; } else { - continue loop1; + G_i = 0; } } } From caeee7c391d49cfefef96aa8d5b164ffe0941318 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sun, 8 May 2016 18:27:39 -0400 Subject: [PATCH 402/417] grid search done --- .../algorithms/implementation/GridSearch.java | 48 ++++++++++++------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/src/com/hackerrank/algorithms/implementation/GridSearch.java b/src/com/hackerrank/algorithms/implementation/GridSearch.java index 3f8f7463..6fb2251d 100644 --- a/src/com/hackerrank/algorithms/implementation/GridSearch.java +++ b/src/com/hackerrank/algorithms/implementation/GridSearch.java @@ -23,29 +23,45 @@ public static void main(String[] args) { for (int P_i = 0; P_i < r; P_i++) { P[P_i] = in.next(); } - int count = 0; - int start = -1; + // create 2D array for grid + int grid[][] = new int[R][C]; + for (int i = 0; i < R; i++) { + for (int j = 0; j < C; j++) { + grid[i][j] = Character.getNumericValue(G[i].charAt(j)); + } + } + + // create 2D array for pattern to be searched in grid + int pattern[][] = new int[r][c]; + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + pattern[i][j] = Character.getNumericValue(P[i].charAt(j)); + } + } + + // search logic + outerLoop: for (int G_i = 0; G_i < R; G_i++) { - if ((start = G[G_i].indexOf(P[0], start + 1)) > -1) { - count = 1; - for (int P_i = 1; P_i < r && G_i + P_i < R; P_i++) { - if (G[G_i + P_i].indexOf(P[P_i]) != start) { - break; + for (int G_j = 0; G_j < C; G_j++) { + innerLoop: + for (int P_i = 0; P_i < r && G_i + P_i < R; P_i++) { + for (int P_j = 0; P_j < c && G_j + P_j < C; P_j++) { + if (grid[G_i + P_i][G_j + P_j] != pattern[P_i][P_j]) { + break innerLoop; + } else if (P_i == r - 1 && P_j == c - 1) { + System.out.println("YES"); + break outerLoop; + } } - count++; + } - if (count == r) { - System.out.println("YES"); - break; - } else { - G_i = 0; + if (R - G_i < r) { // no. of rows left in grid less than no. of rows in pattern + System.out.println("NO"); + break outerLoop; } } } - if (count != r) { - System.out.println("NO"); - } } } } From fb6c74b108d339ff2076f8a99656140bd9e442aa Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 28 May 2016 20:05:38 -0400 Subject: [PATCH 403/417] cavity map done --- .../algorithms/implementation/CavityMap.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/com/hackerrank/algorithms/implementation/CavityMap.java diff --git a/src/com/hackerrank/algorithms/implementation/CavityMap.java b/src/com/hackerrank/algorithms/implementation/CavityMap.java new file mode 100644 index 00000000..8ead43c8 --- /dev/null +++ b/src/com/hackerrank/algorithms/implementation/CavityMap.java @@ -0,0 +1,30 @@ +package com.hackerrank.algorithms.implementation; + +import java.util.Scanner; + +/** + * Created by ramswaroop on 08/05/2016. + */ +public class CavityMap { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + String grid[] = new String[n]; + for (int grid_i = 0; grid_i < n; grid_i++) { + grid[grid_i] = in.next(); + } + for (int i = 1; i < n - 1; i++) { + for (int j = 1; j < n - 1; j++) { + if (Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i].charAt(j - 1)) + && Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i].charAt(j + 1)) + && Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i - 1].charAt(j)) + && Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i + 1].charAt(j))) { + grid[i] = grid[i].substring(0, j) + "X" + grid[i].substring(j + 1); + } + } + } + for (int grid_i = 0; grid_i < n; grid_i++) { + System.out.println(grid[grid_i]); + } + } +} From 2e6b7bc7db7d71c580622a8ce5931e9b206888de Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sun, 29 May 2016 18:27:39 -0400 Subject: [PATCH 404/417] biginteger problem done --- .../implementation/ExtraLongFactorials.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/com/hackerrank/algorithms/implementation/ExtraLongFactorials.java diff --git a/src/com/hackerrank/algorithms/implementation/ExtraLongFactorials.java b/src/com/hackerrank/algorithms/implementation/ExtraLongFactorials.java new file mode 100644 index 00000000..d4e340b7 --- /dev/null +++ b/src/com/hackerrank/algorithms/implementation/ExtraLongFactorials.java @@ -0,0 +1,19 @@ +package com.hackerrank.algorithms.implementation; + +import java.math.BigInteger; +import java.util.Scanner; + +/** + * Created by ramswaroop on 29/05/2016. + */ +public class ExtraLongFactorials { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + BigInteger res = BigInteger.ONE; + for (int i = n; i > 0; i--) { + res = res.multiply(BigInteger.valueOf(i)); + } + System.out.println(res); + } +} From 1d2750750d5f0bbe1165103433141d7af2187703 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Mon, 30 May 2016 18:28:04 -0400 Subject: [PATCH 405/417] time in words done --- .../implementation/TheTimeInWords.java | 38 +++++++++++++++++++ .../ramswaroop/misc}/RandomTest.java | 2 +- .../ramswaroop/misc}/SPOJ1.java | 2 +- 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 src/com/hackerrank/algorithms/implementation/TheTimeInWords.java rename src/{com/hackerrank/practice => me/ramswaroop/misc}/RandomTest.java (97%) rename src/{com/hackerrank/practice => me/ramswaroop/misc}/SPOJ1.java (95%) diff --git a/src/com/hackerrank/algorithms/implementation/TheTimeInWords.java b/src/com/hackerrank/algorithms/implementation/TheTimeInWords.java new file mode 100644 index 00000000..0b747ce5 --- /dev/null +++ b/src/com/hackerrank/algorithms/implementation/TheTimeInWords.java @@ -0,0 +1,38 @@ +package com.hackerrank.algorithms.implementation; + +import java.util.Scanner; + +/** + * Created by ramswaroop on 29/05/2016. + */ +public class TheTimeInWords { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int h = in.nextInt(); + int m = in.nextInt(); + String timeInWords; + String[] words = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", + "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", + "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", + "twenty seven", "twenty eight", "twenty nine"}; + + if (m == 0) { + timeInWords = words[h] + " o' clock"; + } else if (m == 1) { + timeInWords = words[m] + " minute past " + words[h]; + } else if (m == 15) { + timeInWords = "quarter past " + words[h]; + } else if (m < 30) { + timeInWords = words[m] + " minutes past " + words[h]; + } else if (m == 30) { + timeInWords = "half past " + words[h]; + } else if (m == 45) { + timeInWords = "quarter to " + words[(h == 12) ? h - 11 : h + 1]; + } else if (60 - m == 1) { + timeInWords = words[60 - m] + " minute to " + words[(h == 12) ? h - 11 : h + 1]; + } else { + timeInWords = words[60 - m] + " minutes to " + words[(h == 12) ? h - 11 : h + 1]; + } + System.out.println(timeInWords); + } +} diff --git a/src/com/hackerrank/practice/RandomTest.java b/src/me/ramswaroop/misc/RandomTest.java similarity index 97% rename from src/com/hackerrank/practice/RandomTest.java rename to src/me/ramswaroop/misc/RandomTest.java index 4d29fd8c..820477f4 100644 --- a/src/com/hackerrank/practice/RandomTest.java +++ b/src/me/ramswaroop/misc/RandomTest.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; import java.util.Random; diff --git a/src/com/hackerrank/practice/SPOJ1.java b/src/me/ramswaroop/misc/SPOJ1.java similarity index 95% rename from src/com/hackerrank/practice/SPOJ1.java rename to src/me/ramswaroop/misc/SPOJ1.java index 1fd0e4d6..6c80f409 100644 --- a/src/com/hackerrank/practice/SPOJ1.java +++ b/src/me/ramswaroop/misc/SPOJ1.java @@ -1,4 +1,4 @@ -package me.ramswaroop.practice; +package me.ramswaroop.misc; import java.util.ArrayList; import java.util.List; From 2a141af40adb99a21bfd88239424fe2f4dd08e02 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Tue, 31 May 2016 18:02:42 -0400 Subject: [PATCH 406/417] binary gap done --- src/me/ramswaroop/bits/BinaryGap.java | 49 +++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/me/ramswaroop/bits/BinaryGap.java diff --git a/src/me/ramswaroop/bits/BinaryGap.java b/src/me/ramswaroop/bits/BinaryGap.java new file mode 100644 index 00000000..7d1f492e --- /dev/null +++ b/src/me/ramswaroop/bits/BinaryGap.java @@ -0,0 +1,49 @@ +package me.ramswaroop.bits; + +/** + * Created by ramswaroop on 30/05/2016. + */ +public class BinaryGap { + + /** + * A binary gap of a positive integer N is any maximal + * sequence of consecutive zeros that is surrounded by ones + * at both ends in the binary representation of N. + * + * @param n + * @return + */ + public static int findBinaryGap(long n) { + int gap = 0; + int maxGap = 0; + while (n > 0) { + if ((n & 1) == 1) { + n = n >>> 1; + while (n > 0 && (n & 1) == 0) { + gap++; + n = n >>> 1; + } + if (gap > maxGap) { + maxGap = gap; + gap = 0; + } + } + n = n >>> 1; + } + + return maxGap; + } + + public static int findMaxNoOf0sBetweenTwo1s(long n) { + return findBinaryGap(n); + } + + public static void main(String[] args) { + System.out.println(findBinaryGap(2)); + System.out.println(findBinaryGap(8)); + System.out.println(findBinaryGap(9)); + System.out.println(findBinaryGap(16)); + System.out.println(findBinaryGap(17)); + System.out.println(findMaxNoOf0sBetweenTwo1s(121)); + } +} From c7292200abca6ffbed9d25b33182dd56b1c882f4 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Tue, 31 May 2016 19:00:46 -0400 Subject: [PATCH 407/417] fixed bug + count div done --- src/me/ramswaroop/arrays/CountDivisors.java | 30 +++++++++++++++++++++ src/me/ramswaroop/bits/BinaryGap.java | 7 ++--- 2 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 src/me/ramswaroop/arrays/CountDivisors.java diff --git a/src/me/ramswaroop/arrays/CountDivisors.java b/src/me/ramswaroop/arrays/CountDivisors.java new file mode 100644 index 00000000..6a20dbd9 --- /dev/null +++ b/src/me/ramswaroop/arrays/CountDivisors.java @@ -0,0 +1,30 @@ +package me.ramswaroop.arrays; + +/** + * Created by ramswaroop on 31/05/2016. + */ +public class CountDivisors { + + /** + * Counts the number of integers in the range {@param begin} and + * {@param end} that are divisible by {@param n}. + * + * @param begin + * @param end + * @param n + * @return + */ + public static int countDivisorsInRange(int begin, int end, int n) { + int b = end / n + 1; // From 0 to end the integers divisible by n + int a = begin / n + 1; // From 0 to begin the integers divisible by n + + if (begin % n == 0) { // "begin" is inclusive; if divisible by n then + --a; // remove 1 from "a" + } + return b - a; // return integers in range + } + + public static void main(String[] a) { + countDivisorsInRange(0, 2000000000, 5); + } +} diff --git a/src/me/ramswaroop/bits/BinaryGap.java b/src/me/ramswaroop/bits/BinaryGap.java index 7d1f492e..3694a31f 100644 --- a/src/me/ramswaroop/bits/BinaryGap.java +++ b/src/me/ramswaroop/bits/BinaryGap.java @@ -18,15 +18,14 @@ public static int findBinaryGap(long n) { int maxGap = 0; while (n > 0) { if ((n & 1) == 1) { - n = n >>> 1; - while (n > 0 && (n & 1) == 0) { + while (n >>> 1 > 0 && (n >>> 1 & 1) == 0) { gap++; n = n >>> 1; } if (gap > maxGap) { maxGap = gap; - gap = 0; } + gap = 0; } n = n >>> 1; } @@ -45,5 +44,7 @@ public static void main(String[] args) { System.out.println(findBinaryGap(16)); System.out.println(findBinaryGap(17)); System.out.println(findMaxNoOf0sBetweenTwo1s(121)); + System.out.println(findMaxNoOf0sBetweenTwo1s(1041)); + System.out.println(findMaxNoOf0sBetweenTwo1s(2_147_483_64889L)); } } From a8ff8a89ff82768fa8bbdd8a755eaa1daa040241 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 30 Jul 2016 05:19:06 -0400 Subject: [PATCH 408/417] package modified --- .../bitmanipulation/CounterGame.java | 2 +- .../hackerrank/bitmanipulation/Solution.java | 28 +++++++++++-------- .../bitmanipulation/TwosCompliment.java | 2 +- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/com/hackerrank/bitmanipulation/CounterGame.java b/src/com/hackerrank/bitmanipulation/CounterGame.java index e5ede2a2..c319fc38 100644 --- a/src/com/hackerrank/bitmanipulation/CounterGame.java +++ b/src/com/hackerrank/bitmanipulation/CounterGame.java @@ -1,4 +1,4 @@ -package me.ramswaroop.bitmanipulation; +package com.hackerrank.bitmanipulation; import java.math.BigInteger; import java.util.Scanner; diff --git a/src/com/hackerrank/bitmanipulation/Solution.java b/src/com/hackerrank/bitmanipulation/Solution.java index 84bbebd9..618b9120 100644 --- a/src/com/hackerrank/bitmanipulation/Solution.java +++ b/src/com/hackerrank/bitmanipulation/Solution.java @@ -1,4 +1,4 @@ -package me.ramswaroop.bitmanipulation; +package com.hackerrank.bitmanipulation; import java.io.BufferedReader; import java.io.IOException; @@ -14,42 +14,46 @@ public class Solution { private final static byte BITS; private final static long[] BIT_COUNT_TO_BIT; + static { BITS = 32; - BIT_COUNT_TO_BIT = new long[BITS+1]; + BIT_COUNT_TO_BIT = new long[BITS + 1]; BIT_COUNT_TO_BIT[0] = 1; - for(byte i = 1; i <= BITS; i++){ - BIT_COUNT_TO_BIT[i] = ((BIT_COUNT_TO_BIT[i-1] - 1L) << 1) + (1L << (i-1)) + 1L; + for (byte i = 1; i <= BITS; i++) { + BIT_COUNT_TO_BIT[i] = ((BIT_COUNT_TO_BIT[i - 1] - 1L) << 1) + (1L << (i - 1)) + 1L; } } + public static void main(String[] args) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - for(short T = Short.parseShort(br.readLine()); T > 0; T--){ + for (short T = Short.parseShort(br.readLine()); T > 0; T--) { String[] temp = br.readLine().split(" "); int A = Integer.parseInt(temp[0]); int B = Integer.parseInt(temp[1]); long bits = bitCountToNum(B) - bitCountToNum(A) + getHammingWeight(A); - bits += (A < 0 && B >= 0) ? BIT_COUNT_TO_BIT[BITS] - 1L: 0; + bits += (A < 0 && B >= 0) ? BIT_COUNT_TO_BIT[BITS] - 1L : 0; sb.append(bits + "\n"); } System.out.print(sb); } + //Bit count in number - private static int getHammingWeight(int n){ + private static int getHammingWeight(int n) { byte count = 0; - while(n != 0){ + while (n != 0) { count++; - n &= n-1; + n &= n - 1; } return count; } + //Bit count to number, inclusive - private static long bitCountToNum(int n){ + private static long bitCountToNum(int n) { long count = 0; - for(byte b = BITS; n != 0;){ + for (byte b = BITS; n != 0; ) { int x = 1 << --b; - if((n & x) != 0){ + if ((n & x) != 0) { n &= ~x; count += BIT_COUNT_TO_BIT[b] + n; } diff --git a/src/com/hackerrank/bitmanipulation/TwosCompliment.java b/src/com/hackerrank/bitmanipulation/TwosCompliment.java index 1f379cd2..37fb21ae 100644 --- a/src/com/hackerrank/bitmanipulation/TwosCompliment.java +++ b/src/com/hackerrank/bitmanipulation/TwosCompliment.java @@ -1,4 +1,4 @@ -package me.ramswaroop.bitmanipulation; +package com.hackerrank.bitmanipulation; import java.util.Scanner; From 053ee05f560df16f53f5af41ad785195646a67f2 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sun, 31 Jul 2016 19:31:00 -0400 Subject: [PATCH 409/417] code refactoring and added a better test case --- src/me/ramswaroop/trees/CheckForBST.java | 27 +++++++++++++----------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/me/ramswaroop/trees/CheckForBST.java b/src/me/ramswaroop/trees/CheckForBST.java index 4ff0a6ab..07f16c46 100644 --- a/src/me/ramswaroop/trees/CheckForBST.java +++ b/src/me/ramswaroop/trees/CheckForBST.java @@ -104,21 +104,24 @@ public static void main(String a[]) { binarySearchTree.put(7); binarySearchTree.put(8); binarySearchTree.put(9); - out.println("Is BST: "); - out.println(isBST(binarySearchTree.root, new BinaryNode(null))); + out.println("1) Is BST: "); + out.println(isBST(binarySearchTree.root, new BinaryNode<>(null))); // should be true + BinaryTree binaryTree = new BinaryTree<>(); binaryTree.put(6); - binaryTree.put(3); - binaryTree.put(5); - binaryTree.put(7); - binaryTree.put(8); + binaryTree.put(4); binaryTree.put(9); - out.println("Is BST: "); - out.println(isBST(binaryTree.root, new BinaryNode(null))); + binaryTree.put(2); + binaryTree.put(8); + binaryTree.put(7); + binaryTree.put(10); + out.println("2) Is BST: "); + out.println(isBST(binaryTree.root, new BinaryNode<>(null))); // should be false + // min max approach - out.println("Is BST: "); - out.println(isBST(binarySearchTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); - out.println("Is BST: "); - out.println(isBST(binaryTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); + out.println("3) Is BST: "); + out.println(isBST(binarySearchTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); // should be true + out.println("4) Is BST: "); + out.println(isBST(binaryTree.root, Integer.MIN_VALUE, Integer.MAX_VALUE)); // should be false } } From b58efeaca2d2fe784f17d9f8209b3c7bc71fa165 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Thu, 1 Sep 2016 17:25:51 -0400 Subject: [PATCH 410/417] wiggle sort easy way: done --- .../ramswaroop/arrays/sorting/WiggleSort.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/me/ramswaroop/arrays/sorting/WiggleSort.java diff --git a/src/me/ramswaroop/arrays/sorting/WiggleSort.java b/src/me/ramswaroop/arrays/sorting/WiggleSort.java new file mode 100644 index 00000000..4e9ab2ea --- /dev/null +++ b/src/me/ramswaroop/arrays/sorting/WiggleSort.java @@ -0,0 +1,45 @@ +package me.ramswaroop.arrays.sorting; + +import java.util.Arrays; + +/** + * Wiggle Sort: Arrange the elements in the array such that elements in + * even indices are greater than or equal to its neighbouring elements + * and elements in odd indices are less than or equal to its neighbouring + * elements. In other words, all elements in array {@code a} are arranged + * such that, a[i-1] <= a[i] => a[i+1] + *

+ * Ex: {1, 3, 2, 5, 4, 6} + * + * @author ramswaroop + * @version 01/09/2016 + */ +public class WiggleSort { + + public static int[] wiggleSortEasyWay(int[] a) { + a = MergeSort.mergeSort(a); + for (int i = 1; i < a.length; i += 2) { + swap(a, i, i + 1); + } + return a; + } + + private static void swap(int[] a, int index1, int index2) { + if (index2 >= a.length) return; + + a[index1] = a[index1] + a[index2]; + a[index2] = a[index1] - a[index2]; + a[index1] = a[index1] - a[index2]; + } + + public static void main(String[] a) { + int[] ar = {3, 5, 6, 7, 8, 1, 2}; + System.out.println(Arrays.toString(wiggleSortEasyWay(ar))); + int[] ar1 = {3, 5, 6, 7, 2, 1}; + System.out.println(Arrays.toString(wiggleSortEasyWay(ar1))); + int[] ar2 = {3, 5, 6, 7, 8, 1}; + System.out.println(Arrays.toString(wiggleSortEasyWay(ar2))); + int[] ar3 = {3, 5, 6, 5, 8, 1}; + System.out.println(Arrays.toString(wiggleSortEasyWay(ar3))); + } +} From cc348a9e679207bbc70e7484a1e31b4c438cf991 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Wed, 28 Sep 2016 17:22:52 -0400 Subject: [PATCH 411/417] making anagrams: done, some minor javadoc error fixed --- .../algorithms/strings/MakingAnagrams.java | 53 +++++++++++++++++++ src/me/ramswaroop/arrays/RotateArray.java | 4 +- 2 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 src/com/hackerrank/algorithms/strings/MakingAnagrams.java diff --git a/src/com/hackerrank/algorithms/strings/MakingAnagrams.java b/src/com/hackerrank/algorithms/strings/MakingAnagrams.java new file mode 100644 index 00000000..71290d2f --- /dev/null +++ b/src/com/hackerrank/algorithms/strings/MakingAnagrams.java @@ -0,0 +1,53 @@ +package com.hackerrank.algorithms.strings; + +import java.util.Arrays; + +/** + * @author ramswaroop + * @version 28/09/2016 + */ +public class MakingAnagrams { + + /** + * Find number of characters to be deleted to make {@param a} + * and {@param b} anagrams. + * See: https://www.hackerrank.com/challenges/making-anagrams + * + * @param a + * @param b + * @return + */ + public static int makeAnagrams(String a, String b) { + + int i = 0, j = 0, c = 0; + char[] s1 = a.toCharArray(); + char[] s2 = b.toCharArray(); + Arrays.sort(s1); + Arrays.sort(s2); + + while (i < s1.length || j < s2.length) { + if (i >= s1.length) { + c++; + j++; + } else if (j >= s2.length) { + c++; + i++; + } else if (s1[i] < s2[j]) { + c++; + i++; + } else if (s1[i] > s2[j]) { + c++; + j++; + } else { + i++; + j++; + } + } + + return c; + } + + public static void main(String[] a) { + System.out.println(makeAnagrams("abc", "cde")); + } +} diff --git a/src/me/ramswaroop/arrays/RotateArray.java b/src/me/ramswaroop/arrays/RotateArray.java index 57a168bb..96d06888 100644 --- a/src/me/ramswaroop/arrays/RotateArray.java +++ b/src/me/ramswaroop/arrays/RotateArray.java @@ -46,10 +46,10 @@ public static void rotateNaiveApproach(int[] a, int k) { * Reverse B, we get ArBr = [2, 1, 7, 6, 5, 4, 3] * Reverse all, we get (ArBr)r = [3, 4, 5, 6, 7, 1, 2] * NOTE: Ar = Reverse of A + * See: http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/ * * @param a * @param k - * @see: http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/ */ public static void rotateReversal(int[] a, int k) { ReverseArray.reverseRecursive(a, 0, k - 1); @@ -59,10 +59,10 @@ public static void rotateReversal(int[] a, int k) { /** * Juggling algorithm for array rotation. + * See: http://www.geeksforgeeks.org/array-rotation/ * * @param a * @param k - * @see: http://www.geeksforgeeks.org/array-rotation/ */ public static void rotateGCD(int[] a, int k) { int gcd = gcd(a.length, k), temp, i, j, p; From 3cd5e6a57a3a5db990be944e2d138823b3dd0825 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Fri, 30 Sep 2016 07:22:47 -0400 Subject: [PATCH 412/417] RansomNote: done --- .../hackerrank/tutorials/ctci/RansomNote.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/com/hackerrank/tutorials/ctci/RansomNote.java diff --git a/src/com/hackerrank/tutorials/ctci/RansomNote.java b/src/com/hackerrank/tutorials/ctci/RansomNote.java new file mode 100644 index 00000000..a61e9ef8 --- /dev/null +++ b/src/com/hackerrank/tutorials/ctci/RansomNote.java @@ -0,0 +1,69 @@ +package com.hackerrank.tutorials.ctci; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +/** + * Question: https://www.hackerrank.com/challenges/ctci-ransom-note + * + * @author ramswaroop + * @version 30/09/2016 + */ +public class RansomNote { + + Map magazineMap; + Map noteMap; + + public RansomNote(String magazine, String note) { + + magazineMap = new HashMap<>(); + noteMap = new HashMap<>(); + String[] magazineWords = magazine.split(" "); + String[] noteWords = note.split(" "); + Integer c; + + for (int i = 0; i < magazineWords.length; i++) { + if ((c = magazineMap.get(magazineWords[i])) == null) { + magazineMap.put(magazineWords[i], 1); + } else { + magazineMap.put(magazineWords[i], c + 1); + } + } + + for (int i = 0; i < noteWords.length; i++) { + if ((c = noteMap.get(noteWords[i])) == null) { + noteMap.put(noteWords[i], 1); + } else { + noteMap.put(noteWords[i], c + 1); + } + } + } + + public boolean solve() { + for (Map.Entry entry : noteMap.entrySet()) { + if (magazineMap.get(entry.getKey()) == null || magazineMap.get(entry.getKey()) - entry.getValue() < 0) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int m = scanner.nextInt(); + int n = scanner.nextInt(); + + // Eat whitespace to beginning of next line + scanner.nextLine(); + + RansomNote s = new RansomNote(scanner.nextLine(), scanner.nextLine()); + scanner.close(); + + if (s.solve()) { + System.out.println("Yes"); + } else { + System.out.println("No"); + } + } +} From b1bcef74388a835c5b74c6c034dd34a2685a062c Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 8 Oct 2016 15:07:47 -0400 Subject: [PATCH 413/417] RansomNote: done --- src/com/hackerrank/tutorials/ctci/RansomNote.java | 1 + src/me/ramswaroop/misc/CollectionIteration.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/com/hackerrank/tutorials/ctci/RansomNote.java b/src/com/hackerrank/tutorials/ctci/RansomNote.java index a61e9ef8..eb8414ee 100644 --- a/src/com/hackerrank/tutorials/ctci/RansomNote.java +++ b/src/com/hackerrank/tutorials/ctci/RansomNote.java @@ -6,6 +6,7 @@ /** * Question: https://www.hackerrank.com/challenges/ctci-ransom-note + * Level: Easy * * @author ramswaroop * @version 30/09/2016 diff --git a/src/me/ramswaroop/misc/CollectionIteration.java b/src/me/ramswaroop/misc/CollectionIteration.java index dadf5e06..d7acec42 100644 --- a/src/me/ramswaroop/misc/CollectionIteration.java +++ b/src/me/ramswaroop/misc/CollectionIteration.java @@ -8,6 +8,7 @@ * Created by IntelliJ IDEA. *

* All possible ways of iterating different collections in Java. + * Level: Basics * * @author: ramswaroop * @date: 10/16/15 From c84ae804926efba16c26c4ca5c44d5fd176f649b Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 8 Oct 2016 16:34:17 -0400 Subject: [PATCH 414/417] implement a queue with 2 stacks : done --- .../tutorials/ctci/QueuesWithTwoStacks.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/com/hackerrank/tutorials/ctci/QueuesWithTwoStacks.java diff --git a/src/com/hackerrank/tutorials/ctci/QueuesWithTwoStacks.java b/src/com/hackerrank/tutorials/ctci/QueuesWithTwoStacks.java new file mode 100644 index 00000000..6d4e3ae9 --- /dev/null +++ b/src/com/hackerrank/tutorials/ctci/QueuesWithTwoStacks.java @@ -0,0 +1,56 @@ +package com.hackerrank.tutorials.ctci; + +import java.util.Scanner; +import java.util.Stack; + +/** + * Question: https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks + * Level: Medium + * + * @author ramswaroop + * @version 07/10/2016 + */ +public class QueuesWithTwoStacks { + + public static class MyQueue { + Stack stackNewestOnTop = new Stack(); + Stack stackOldestOnTop = new Stack(); + + public void enqueue(T value) { // Push onto newest stack + stackNewestOnTop.push(value); + } + + public T peek() { + return stackOldestOnTop.isEmpty() ? stackNewestOnTop.firstElement() : stackOldestOnTop.peek(); + } + + public T dequeue() { + if (stackOldestOnTop.isEmpty()) { + while (!stackNewestOnTop.isEmpty()) { + stackOldestOnTop.push(stackNewestOnTop.pop()); + } + } + return stackOldestOnTop.pop(); + } + } + + + public static void main(String[] args) { + MyQueue queue = new MyQueue<>(); + + Scanner scan = new Scanner(System.in); + int n = scan.nextInt(); + + for (int i = 0; i < n; i++) { + int operation = scan.nextInt(); + if (operation == 1) { // enqueue + queue.enqueue(scan.nextInt()); + } else if (operation == 2) { // dequeue + queue.dequeue(); + } else if (operation == 3) { // print/peek + System.out.println(queue.peek()); + } + } + scan.close(); + } +} From aabf64f2ee645e4c6099c378f242b4af4acb3dc7 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Thu, 2 Feb 2017 22:40:20 +0000 Subject: [PATCH 415/417] Added streams api questions --- .../dynamicprogramming/FibonacciNumbers.java | 1 + src/me/ramswaroop/java8/Streams.java | 125 ++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 src/me/ramswaroop/java8/Streams.java diff --git a/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java b/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java index dac48fb4..5bed39c4 100644 --- a/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java +++ b/src/me/ramswaroop/dynamicprogramming/FibonacciNumbers.java @@ -36,6 +36,7 @@ public static int[] getFirstKFibonacciNumbers(int k) { } public static void main(String a[]) { + out.println(Arrays.toString(getFirstKFibonacciNumbers(0))); out.println(Arrays.toString(getFirstKFibonacciNumbers(10))); out.println(Arrays.toString(getFirstKFibonacciNumbers(46))); } diff --git a/src/me/ramswaroop/java8/Streams.java b/src/me/ramswaroop/java8/Streams.java new file mode 100644 index 00000000..7bd58a89 --- /dev/null +++ b/src/me/ramswaroop/java8/Streams.java @@ -0,0 +1,125 @@ +package me.ramswaroop.java8; + +import java.util.Arrays; +import java.util.List; + +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.toList; + +/** + * @author ramswaroop + * @version 02/02/2017 + */ +class Trader { + + private final String name; + private final String city; + + public Trader(String n, String c) { + this.name = n; + this.city = c; + } + + public String getName() { + return this.name; + } + + public String getCity() { + return this.city; + } + + public String toString() { + return "Trader:" + this.name + " in " + this.city; + } +} + +class Transaction { + private final Trader trader; + private final int year; + private final int value; + + public Transaction(Trader trader, int year, int value) { + this.trader = trader; + this.year = year; + this.value = value; + } + + public Trader getTrader() { + return this.trader; + } + + public int getYear() { + return this.year; + } + + public int getValue() { + return this.value; + } + + public String toString() { + return "{" + this.trader + ", " + + "year: " + this.year + ", " + + "value:" + this.value + "}"; + } +} + +public class Streams { + + static final Trader raoul = new Trader("Raoul", "Cambridge"); + static final Trader mario = new Trader("Mario", "Milan"); + static final Trader alan = new Trader("Alan", "Cambridge"); + static final Trader brian = new Trader("Brian", "Cambridge"); + + static final List transactions = Arrays.asList( + new Transaction(brian, 2011, 300), + new Transaction(raoul, 2012, 1000), + new Transaction(raoul, 2011, 400), + new Transaction(mario, 2012, 710), + new Transaction(mario, 2012, 700), + new Transaction(alan, 2012, 950) + ); + + public static List getTransactionsIn2011SortedByValue() { + return transactions.stream() + .filter(t -> t.getYear() == 2011) + .sorted(comparing(Transaction::getValue)) + .collect(toList()); + } + + public static List findUniqueCities() { + return transactions.stream() + .map(t -> t.getTrader().getCity()) + .distinct() + .collect(toList()); + } + + public static List getAllTradersFromCambridgeAndSortByName() { + return transactions.stream() + .map(Transaction::getTrader) + .filter(traders -> traders.getCity().equals("Cambridge")) + .distinct() + .sorted(comparing(Trader::getName)) + .collect(toList()); + } + + public static List getAllTraderNamesAndSortByName() { + return transactions.stream() + .map(t -> t.getTrader().getName()) + .distinct() + .sorted() + .collect(toList()); + } + + public static boolean areAnyTradersFromMilan() { + return transactions.stream() + .anyMatch(t -> t.getTrader().getCity().equals("Milan")); + } + + public static void main(String[] a) { + System.out.println(getTransactionsIn2011SortedByValue()); + System.out.println(findUniqueCities()); + System.out.println(getAllTradersFromCambridgeAndSortByName()); + System.out.println(getAllTraderNamesAndSortByName()); + System.out.println(areAnyTradersFromMilan()); + } +} \ No newline at end of file From c164dff328e1ab0261c55118998d7ff69888e954 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Sat, 4 Feb 2017 16:02:49 +0000 Subject: [PATCH 416/417] More examples added to streams --- src/me/ramswaroop/java8/Streams.java | 37 ++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/src/me/ramswaroop/java8/Streams.java b/src/me/ramswaroop/java8/Streams.java index 7bd58a89..b9d00799 100644 --- a/src/me/ramswaroop/java8/Streams.java +++ b/src/me/ramswaroop/java8/Streams.java @@ -109,17 +109,40 @@ public static List getAllTraderNamesAndSortByName() { .sorted() .collect(toList()); } - + public static boolean areAnyTradersFromMilan() { return transactions.stream() - .anyMatch(t -> t.getTrader().getCity().equals("Milan")); + .anyMatch(t -> "Milan".equals(t.getTrader().getCity())); + } + + public static Integer[] getAllTransValuesFromTradersInCambridge() { + return transactions.stream() + .filter(t -> "Cambridge".equals(t.getTrader().getCity())) + .map(Transaction::getValue) + .toArray(Integer[]::new); + } + + public static int findHighestTransactionValue() { + return transactions.stream() + .map(Transaction::getValue) + .reduce((t1, t2) -> (t1 > t2) ? t1 : t2) // can replace with .reduce(Integer::max) + .get(); + } + + public static Transaction getSmallestTransaction() { + return transactions.stream() + .reduce((t1, t2) -> t1.getValue() < t2.getValue() ? t1 : t2) + .get(); } public static void main(String[] a) { - System.out.println(getTransactionsIn2011SortedByValue()); - System.out.println(findUniqueCities()); - System.out.println(getAllTradersFromCambridgeAndSortByName()); - System.out.println(getAllTraderNamesAndSortByName()); - System.out.println(areAnyTradersFromMilan()); + System.out.println("1: " + getTransactionsIn2011SortedByValue()); + System.out.println("2: " + findUniqueCities()); + System.out.println("3: " + getAllTradersFromCambridgeAndSortByName()); + System.out.println("4: " + getAllTraderNamesAndSortByName()); + System.out.println("5: " + areAnyTradersFromMilan()); + System.out.println("6: " + Arrays.asList(getAllTransValuesFromTradersInCambridge())); + System.out.println("7: " + findHighestTransactionValue()); + System.out.println("8: " + getSmallestTransaction()); } } \ No newline at end of file From 2618693e692e1e97810e9d18c0d10eb7bc2934e3 Mon Sep 17 00:00:00 2001 From: ramswaroop Date: Fri, 17 Feb 2017 15:25:37 +0000 Subject: [PATCH 417/417] flatMap demo --- src/me/ramswaroop/java8/FlatMapInStreams.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/me/ramswaroop/java8/FlatMapInStreams.java diff --git a/src/me/ramswaroop/java8/FlatMapInStreams.java b/src/me/ramswaroop/java8/FlatMapInStreams.java new file mode 100644 index 00000000..f584a675 --- /dev/null +++ b/src/me/ramswaroop/java8/FlatMapInStreams.java @@ -0,0 +1,64 @@ +package me.ramswaroop.java8; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author ramswaroop + * @version 17/02/2017 + */ +public class FlatMapInStreams { + + public static long countTotalIngredientsInAllDishes(List dishes) { + return dishes.stream().map(Dish::getIngredients).flatMap(List::stream).count(); + } + + public static void main(String[] a) { + List ingredients = new ArrayList<>(); + ingredients.add("rice"); + ingredients.add("chicken"); + ingredients.add("haldi"); + List dishes = Arrays.asList( + new Dish("biriyani", 600, ingredients), + new Dish("biriyani", 600, new ArrayList<>())); + // to show whether empty List is counted in flatMap + System.out.println(countTotalIngredientsInAllDishes(dishes)); + } +} + +class Dish { + private String name; + private int calories; + private List ingredients; + + public Dish(String name, int calories, List ingredients) { + this.name = name; + this.calories = calories; + this.ingredients = ingredients; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getCalories() { + return calories; + } + + public void setCalories(int calories) { + this.calories = calories; + } + + public List getIngredients() { + return ingredients; + } + + public void setIngredients(List ingredients) { + this.ingredients = ingredients; + } +}