├── README.md
└── src
└── com
└── hubberspot
└── dsalgo
├── array
├── ArrayUtil.java
├── MergeSortedArrays.java
└── MoveZeros.java
├── dp
└── MaxSubArraySum.java
├── graph
├── AdjListGraph.java
└── AdjMatrixGraph.java
├── hashing
└── HashTable.java
├── heap
└── MaxPQ.java
├── interval
└── MergeInterval.java
├── list
├── CircularLinkedList.java
├── DoublyLinkedList.java
└── SinglyLinkedList.java
├── mathematics
└── RemoveEvenInteger.java
├── matrix
├── SortedMatrix.java
└── SpiralMatrix.java
├── queue
└── Queue.java
├── search
├── BinarySearch.java
└── LinearSearch.java
├── sorting
├── BubbleSort.java
├── InsertionSort.java
├── MergeSort.java
├── SelectionSort.java
└── Sort012.java
├── stack
├── StringReverse.java
└── impl
│ ├── array
│ └── Stack.java
│ └── list
│ └── Stack.java
├── string
└── StringUtil.java
├── tree
├── BinarySearchTree.java
└── BinaryTree.java
└── trie
└── Trie.java
/README.md:
--------------------------------------------------------------------------------
1 | # ds-algos
2 |
3 |
4 |
5 |
Cracking the GAMAM Technical Interviews Ebook
6 |
Buy Now
7 |
8 |

9 |
10 |
Cracking the GAMAM Technical Interviews Ebook
11 |
Buy Now
12 |
13 |
14 |
15 | Get complete free course on Data Structures and Algorithms at - https://www.youtube.com/playlist?list=PL6Zs6LgrJj3tDXv8a_elC6eT_4R5gfX4d.
16 |
17 | Subscribe to the channel for all free courses at - https://www.youtube.com/user/hubberspot?sub_confirmation=1
18 |
19 | 🙏 Thank you for your continuous love and support. I humbly request you to help this channel grow more, for that please Like, Share and Subscribe to my channel. Your support will motivate me to add more valuable content.
20 |
21 | || LIKE || SHARE || SUBSCRIBE ||
22 |
23 | Want to land a software engineering job in the IT industry? This course - 'Visualizing Data Structures and Algorithms' is here to help. The course walks you through multiple Java algorithms, data structures problems, and their solutions with step by step
24 | visualizations, so that you are actually learning instead of blindly memorizing solutions.
25 |
26 | The course covers in and outs of Data Structures and Algorithms in Java. Java is used as the programming language in the course. Students familiar with Javascript, Python, C#, C++, C, etc will also get to learn concepts without any difficulty. The
27 | implementation of various Algorithms and Data Structures have been demonstrated and implemented through animated slides. It covers many interview room questions on Algorithms and Data Structures. The questions and solutions are demonstrated by -
28 |
29 | 1. Animated slide. (To make visualization of algorithms faster)
30 | 2. Coding algorithm on IDE.
31 |
32 | The course covers topics such as -
33 |
34 | 0. Algorithm Analysis
35 | 1. Arrays
36 | 2. Matrix
37 | 3. Singly Linked List
38 | 4. Doubly Linked List
39 | 5. Circular Singly Linked List
40 | 6. Stacks
41 | 7. Queues
42 | 8. Binary Tree
43 | 9. Binary Search Tree
44 | 10. Graphs
45 | 11. Priority Queues and Heaps
46 | 12. Recursion
47 | 13. Searching
48 | 14. Sorting
49 | 15. Strings
50 | 16. Trie Data Structure
51 | 17. Dynamic Programming
52 |
53 | and many more ...
54 |
55 | CLICK TO DOWNLOAD COMPLETE SOURCE CODE -
56 | https://github.com/dinesh-varyani/ds-algos
57 |
58 | Visit my blog for more such free videos -
59 | http://www.hubberspot.com
60 |
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/array/ArrayUtil.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.array;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | public class ArrayUtil {
8 |
9 | public void printArray(int[] arr) {
10 | int n = arr.length;
11 | for (int i = 0; i < n; i++) {
12 | System.out.print(arr[i] + " ");
13 | }
14 | System.out.println();
15 | }
16 |
17 | public int findMinimum(int[] arr) {
18 | // edge case
19 | if (arr == null || arr.length == 0) {
20 | throw new IllegalArgumentException("Invalid input");
21 | }
22 |
23 | int min = arr[0]; // min will hold the minimum of array
24 | for (int i = 1; i < arr.length; i++) {
25 | if (arr[i] < min) {
26 | min = arr[i];
27 | }
28 | }
29 | return min;
30 | }
31 |
32 | public void reverse(int[] numbers, int start, int end) {
33 | while (start < end) {
34 | int temp = numbers[start];
35 | numbers[start] = numbers[end];
36 | numbers[end] = temp;
37 | start++;
38 | end--;
39 | }
40 | }
41 |
42 | public static int[] twoSum(int[] numbers, int target) {
43 | int[] result = new int[2];
44 | Map map = new HashMap<>();
45 |
46 | for (int i = 0; i < numbers.length; i++) {
47 | if (!map.containsKey(target - numbers[i])) {
48 | map.put(numbers[i], i);
49 | } else {
50 | result[1] = i;
51 | result[0] = map.get(target - numbers[i]);
52 | return result;
53 | }
54 | }
55 | throw new IllegalArgumentException("Two numbers not found");
56 | }
57 |
58 | public static int[] twoSumII(int[] arr, int target) {
59 | // Sorting and Two Pointer
60 | Arrays.sort(arr); // 0 2 6 7 10 11
61 | int left = 0;
62 | int right = arr.length - 1;
63 | int[] result = new int[2];
64 | while (left < right) {
65 | int sum = arr[left] + arr[right];
66 | if (sum == target) {
67 | result[0] = arr[left];
68 | result[1] = arr[right];
69 | return result;
70 | } else if (sum < target) {
71 | left++;
72 | } else {
73 | right--;
74 | }
75 | }
76 | return new int[0];
77 | }
78 |
79 | public static int[] sortedSquares(int[] arr) {
80 | // Two pointer technique
81 | int n = arr.length;
82 | int i = 0;
83 | int j = n - 1;
84 | int[] result = new int[n];
85 |
86 | // {-4, -1, 0, 3} -> {0, 1, 9, 16}
87 |
88 | for (int k = n - 1; k >= 0; k--) {
89 | if (Math.abs(arr[i]) > Math.abs(arr[j])) {
90 | result[k] = arr[i] * arr[i];
91 | i++;
92 | } else {
93 | result[k] = arr[j] * arr[j];
94 | j--;
95 | }
96 | }
97 | return result;
98 | }
99 |
100 | public static int findMissingNumber(int[] arr) {
101 | int n = arr.length + 1;
102 | int sum = n * (n + 1) / 2;
103 | for (int num : arr) {
104 | sum = sum - num;
105 | }
106 | return sum;
107 | }
108 |
109 | public void arrayDemo() {
110 | int[] arr = { 1, 3, 6, 8, 2, 4, 7 };
111 | System.out.println(findMissingNumber(arr));
112 | }
113 |
114 | public static void main(String[] args) {
115 | ArrayUtil arrUtil = new ArrayUtil();
116 | arrUtil.arrayDemo();
117 | }
118 |
119 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/array/MergeSortedArrays.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.array;
2 |
3 | public class MergeSortedArrays {
4 |
5 | public int[] merge(int[] arr1, int[] arr2, int n, int m) {
6 | int[] result = new int[n + m];
7 | int i = 0; // traverse arr1
8 | int j = 0; // traverse arr2
9 | int k = 0; // traverse result
10 |
11 | while (i < n && j < m) { // boundary conditions
12 | if (arr1[i] < arr2[j]) { // if arr1 element at i is less than arr2 element at j
13 | result[k] = arr1[i]; // storing arr1 element into result
14 | i++;
15 | } else {
16 | result[k] = arr2[j]; // storing arr2 element into result
17 | j++;
18 | }
19 | k++;
20 | }
21 | // either arr1 got exhausted or arr2 got exhausted
22 | while (i < n) { // arr2 got exhausted
23 | result[k] = arr1[i]; // storing arr1 element into result
24 | i++;
25 | k++;
26 | }
27 |
28 | while (j < m) { // arr1 got exhausted
29 | result[k] = arr2[j]; // storing arr2 element into result
30 | j++;
31 | k++;
32 | }
33 |
34 | return result;
35 |
36 | }
37 |
38 | public void printArray(int[] arr) {
39 | int n = arr.length;
40 | for (int i = 0; i < n; i++) {
41 | System.out.print(arr[i] + " ");
42 | }
43 | System.out.println();
44 | }
45 |
46 | public static void main(String[] args) {
47 | MergeSortedArrays msa = new MergeSortedArrays();
48 | int[] arr1 = { 0, 1, 8, 10 };
49 | int[] arr2 = { 2, 4, 11, 15, 20 };
50 | msa.printArray(arr1);
51 | msa.printArray(arr2);
52 |
53 | int[] result = msa.merge(arr1, arr2, arr1.length, arr2.length);
54 | msa.printArray(result);
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/array/MoveZeros.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.array;
2 |
3 | public class MoveZeros {
4 |
5 | public void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public void arrayDemo() {
14 | int[] arr = { 8, 1, 0, 2, 1, 0, 3 };
15 | printArray(arr);
16 | moveZeros(arr, arr.length);
17 | printArray(arr);
18 | }
19 |
20 | public void moveZeros(int[] arr, int n) {
21 | int j = 0; // focus on zeroth elements
22 | for (int i = 0; i < n; i++) { // i will focus non zero elements
23 | if (arr[i] != 0 && arr[j] == 0) {
24 | int temp = arr[i];
25 | arr[i] = arr[j];
26 | arr[j] = temp;
27 | }
28 | if (arr[j] != 0) {
29 | j++;
30 | }
31 | }
32 | }
33 |
34 | public static void main(String[] args) {
35 | MoveZeros arrUtil = new MoveZeros();
36 | arrUtil.arrayDemo();
37 | }
38 |
39 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/dp/MaxSubArraySum.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.dp;
2 |
3 | public class MaxSubArraySum {
4 |
5 | public static int maxSubArraySum(int[] arr) {
6 | int currentMax = arr[0];
7 | int maxSoFar = arr[0];
8 | for (int i = 1; i < arr.length; i++) {
9 | currentMax = currentMax + arr[i]; // Q1 - element becomes part of current subarray
10 | if (currentMax < arr[i]) {
11 | currentMax = arr[i]; // Q2 - element decides to start its own subarray
12 | }
13 | if (maxSoFar < currentMax) {
14 | maxSoFar = currentMax;
15 | }
16 | }
17 | return maxSoFar;
18 | }
19 |
20 | public static void main(String[] args) {
21 | int[] arr = { 4, 3, -2, 6, -12, 7, -1, 6 };
22 | System.out.println(maxSubArraySum(arr));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/graph/AdjListGraph.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.graph;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 | import java.util.Stack;
6 |
7 | public class AdjListGraph {
8 |
9 | private LinkedList[] adj;
10 | private int V; // number of vertices
11 | private int E; // number of edges
12 |
13 | public AdjListGraph(int nodes) {
14 | this.V = nodes;
15 | this.E = 0;
16 | this.adj = new LinkedList[nodes];
17 | for (int v = 0; v < V; v++) {
18 | adj[v] = new LinkedList<>();
19 | }
20 | }
21 |
22 | public void addEdge(int u, int v) {
23 | adj[u].add(v);
24 | adj[v].add(u);
25 | E++;
26 | }
27 |
28 | public String toString() {
29 | StringBuilder sb = new StringBuilder();
30 | sb.append(V + " vertices, " + E + " edges " + "\n");
31 | for (int v = 0; v < V; v++) {
32 | sb.append(v + ": ");
33 | for (int w : adj[v]) {
34 | sb.append(w + " ");
35 | }
36 | sb.append("\n");
37 | }
38 | return sb.toString();
39 | }
40 |
41 | public void bfs(int s) {
42 | boolean[] visited = new boolean[V];
43 |
44 | Queue q = new LinkedList<>();
45 | visited[s] = true;
46 | q.offer(s);
47 |
48 | while (!q.isEmpty()) {
49 | int u = q.poll();
50 | System.out.print(u + " ");
51 |
52 | for (int v : adj[u]) {
53 | if (!visited[v]) {
54 | visited[v] = true;
55 | q.offer(v);
56 | }
57 | }
58 | }
59 | }
60 |
61 | public void dfs(int s) {
62 | boolean[] visited = new boolean[V];
63 | Stack stack = new Stack<>();
64 | stack.push(s);
65 |
66 | while (!stack.isEmpty()) {
67 | int u = stack.pop();
68 | if (!visited[u]) {
69 | visited[u] = true;
70 | System.out.print(u + " ");
71 |
72 | for (int v : adj[u]) {
73 | if (!visited[v]) {
74 | stack.push(v);
75 | }
76 | }
77 | }
78 | }
79 | }
80 |
81 | public void dfs() {
82 | boolean[] visited = new boolean[V];
83 | for (int v = 0; v < V; v++) {
84 | if (!visited[v]) {
85 | dfs(v, visited);
86 | }
87 | }
88 | }
89 |
90 | private void dfs(int v, boolean[] visited) {
91 | visited[v] = true;
92 | System.out.print(v + " ");
93 | for (int w : adj[v]) {
94 | if (!visited[w]) {
95 | dfs(w, visited);
96 | }
97 | }
98 | }
99 |
100 | public static void main(String[] args) {
101 | AdjListGraph g = new AdjListGraph(5);
102 | g.addEdge(0, 1);
103 | g.addEdge(1, 2);
104 | g.addEdge(2, 3);
105 | g.addEdge(3, 0);
106 | // 4
107 | System.out.println(g);
108 | g.dfs();
109 | }
110 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/graph/AdjMatrixGraph.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.graph;
2 |
3 | public class AdjMatrixGraph {
4 |
5 | private int V; // number of vertices in Graph
6 | private int E; // number of edges in Graph
7 | private int[][] adjMatrix;
8 |
9 | public AdjMatrixGraph(int nodes) {
10 | this.V = nodes;
11 | this.E = 0;
12 | this.adjMatrix = new int[nodes][nodes];
13 | }
14 |
15 | public void addEdge(int u, int v) {
16 | adjMatrix[u][v] = 1;
17 | adjMatrix[v][u] = 1; // because it is an undirected graph
18 | E++;
19 | }
20 |
21 | public String toString() {
22 | StringBuilder sb = new StringBuilder();
23 | sb.append(V + " vertices, " + E + " edges " + "\n");
24 | for (int v = 0; v < V; v++) {
25 | sb.append(v + ": ");
26 | for (int w : adjMatrix[v]) {
27 | sb.append(w + " ");
28 | }
29 | sb.append("\n");
30 | }
31 | return sb.toString();
32 | }
33 |
34 | public static void main(String[] args) {
35 | AdjMatrixGraph g = new AdjMatrixGraph(4);
36 | g.addEdge(0, 1);
37 | g.addEdge(1, 2);
38 | g.addEdge(2, 3);
39 | g.addEdge(3, 0);
40 | System.out.println(g);
41 | }
42 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/hashing/HashTable.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.hashing;
2 |
3 | public class HashTable {
4 |
5 | private HashNode[] buckets;
6 | private int numOfBuckets; // capacity
7 | private int size; // number of key value pairs in hash table or number of hash nodes in a HashTable
8 |
9 | public HashTable() {
10 | this(10); // default capacity
11 | }
12 |
13 | public HashTable(int capacity) {
14 | this.numOfBuckets = capacity;
15 | this.buckets = new HashNode[numOfBuckets];
16 | this.size = 0;
17 | }
18 |
19 | private class HashNode {
20 | private Integer key; // Can be generic type
21 | private String value; // Can be generic type
22 | private HashNode next; // reference to next HashNode
23 |
24 | public HashNode(Integer key, String value) {
25 | this.key = key;
26 | this.value = value;
27 | }
28 | }
29 |
30 | public int size() {
31 | return size;
32 | }
33 |
34 | public boolean isEmpty() {
35 | return size == 0;
36 | }
37 |
38 | public void put(Integer key, String value) {
39 | if (key == null || value == null) {
40 | throw new IllegalArgumentException("Key or Value is null !!!");
41 | }
42 | int bucketIndex = getBucketIndex(key);
43 | HashNode head = buckets[bucketIndex];
44 | while (head != null) {
45 | if (head.key.equals(key)) {
46 | head.value = value;
47 | return;
48 | }
49 | head = head.next;
50 | }
51 | size++;
52 | head = buckets[bucketIndex];
53 | HashNode node = new HashNode(key, value); // (key, value) -> null
54 | node.next = head;
55 | buckets[bucketIndex] = node;
56 | }
57 |
58 | private int getBucketIndex(Integer key) {
59 | return key % numOfBuckets; // buckets.length
60 | }
61 |
62 | public String get(Integer key) {
63 | if (key == null) {
64 | throw new IllegalArgumentException("Key is null !!!");
65 | }
66 | int bucketIndex = getBucketIndex(key);
67 | HashNode head = buckets[bucketIndex];
68 | while (head != null) {
69 | if (head.key.equals(key)) {
70 | return head.value;
71 | }
72 | head = head.next;
73 | }
74 |
75 | return null;
76 | }
77 |
78 | public String remove(Integer key) {
79 | if (key == null) {
80 | throw new IllegalArgumentException("Key is null !!!");
81 | }
82 |
83 | int bucketIndex = getBucketIndex(key);
84 | HashNode head = buckets[bucketIndex]; // (21, "Tom") -> (31, "Harry") -> (41, "Sana") -> null
85 | HashNode previous = null;
86 |
87 | while (head != null) {
88 | if (head.key.equals(key)) {
89 | break;
90 | }
91 | previous = head;
92 | head = head.next;
93 | }
94 | if (head == null) {
95 | return null;
96 | }
97 | size--;
98 | if (previous != null) {
99 | previous.next = head.next;
100 | } else {
101 | buckets[bucketIndex] = head.next;
102 | }
103 |
104 | return head.value;
105 | }
106 |
107 | public static void main(String[] args) {
108 | HashTable table = new HashTable(10);
109 | table.put(105, "Tom");
110 | table.put(21, "Harry");
111 | table.put(31, "Dinesh");
112 | System.out.println(table.size());// (31, "Dinesh") -> (21, "Harry") -> null
113 | System.out.println(table.remove(21));
114 | System.out.println(table.remove(31));
115 | System.out.println(table.size());
116 | }
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/heap/MaxPQ.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.heap;
2 |
3 | public class MaxPQ {
4 | private Integer[] heap;
5 | private int n; // size of max heap
6 |
7 | public MaxPQ(int capacity) {
8 | heap = new Integer[capacity + 1]; // index 0 is kept as empty
9 | n = 0;
10 | }
11 |
12 | public boolean isEmpty() {
13 | return n == 0;
14 | }
15 |
16 | public int size() {
17 | return n;
18 | }
19 |
20 | public void insert(int x) {
21 | if (n == heap.length - 1) {
22 | resize(2 * heap.length);
23 | }
24 | n++;
25 | heap[n] = x;
26 | swim(n);
27 | }
28 |
29 | private void swim(int k) {
30 | while (k > 1 && heap[k / 2] < heap[k]) {
31 | int temp = heap[k];
32 | heap[k] = heap[k / 2];
33 | heap[k / 2] = temp;
34 | k = k / 2; // bcoz we need to continue shifting up till
35 | // new value inserted is at correct position
36 | }
37 | }
38 |
39 | private void resize(int capacity) {
40 | Integer[] temp = new Integer[capacity];
41 | for (int i = 0; i < heap.length; i++) {
42 | temp[i] = heap[i];
43 | }
44 | heap = temp;
45 | }
46 |
47 | public void printMaxHeap() {
48 | for (int i = 1; i <= n; i++) {
49 | System.out.print(heap[i] + " ");
50 | }
51 | }
52 |
53 | public static void main(String[] args) {
54 | MaxPQ pq = new MaxPQ(3);
55 | pq.insert(4);
56 | pq.insert(5);
57 | pq.insert(2);
58 | pq.insert(6);
59 | pq.insert(1);
60 | pq.insert(3);
61 | System.out.println(pq.size());
62 | pq.printMaxHeap();
63 | }
64 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/interval/MergeInterval.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.interval;
2 |
3 | import static java.util.Comparator.comparingInt;
4 |
5 | import java.util.LinkedList;
6 | import java.util.List;
7 |
8 | public class MergeInterval {
9 |
10 | public static class Interval {
11 | int start;
12 | int end;
13 |
14 | public Interval(int start, int end) {
15 | this.start = start;
16 | this.end = end;
17 | }
18 | }
19 |
20 | List insert(List intervals, Interval newInterval) {
21 | if (intervals == null || intervals.isEmpty())
22 | return intervals;
23 | List result = new LinkedList<>();
24 | int i = 0;
25 | while (i < intervals.size() && intervals.get(i).end < newInterval.start) {
26 | result.add(intervals.get(i));
27 | i++;
28 | }
29 | while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
30 | Interval current = intervals.get(i);
31 | newInterval.start = Math.min(current.start, newInterval.start);
32 | newInterval.end = Math.max(current.end, newInterval.end);
33 | i++;
34 | }
35 | result.add(newInterval);
36 | while (i < intervals.size()) {
37 | result.add(intervals.get(i));
38 | i++;
39 | }
40 | return result;
41 | }
42 |
43 | public List merge(List intervals) {
44 | if (intervals.size() < 2) {
45 | return intervals;
46 | }
47 | intervals.sort(comparingInt(interval -> interval.start));
48 | List mergedIntervals = new LinkedList<>();
49 | Interval interval = intervals.get(0);
50 | int start = interval.start;
51 | int end = interval.end;
52 | for (Interval curr : intervals) {
53 | if (curr.start <= end) {
54 | end = Math.max(curr.end, end);
55 | } else {
56 | mergedIntervals.add(new Interval(start, end));
57 | start = curr.start;
58 | end = curr.end;
59 | }
60 | }
61 | mergedIntervals.add(new Interval(start, end));
62 | return mergedIntervals;
63 | }
64 |
65 | List mergeInterval(List intervals) {
66 | if (intervals.size() < 2)
67 | return intervals;
68 | intervals.sort(comparingInt(a -> a.start));
69 | List result = new LinkedList<>();
70 | Interval first = intervals.get(0);
71 | int start = first.start;
72 | int end = first.end;
73 | for (int i = 1; i < intervals.size(); i++) {
74 | Interval current = intervals.get(i);
75 | if (current.start <= end) {
76 | end = Math.max(current.end, end);
77 | } else {
78 | result.add(new Interval(start, end));
79 | start = current.start;
80 | end = current.end;
81 | }
82 | }
83 | result.add(new Interval(start, end));
84 | return result;
85 | }
86 |
87 | public static void main(String[] args) {
88 | MergeInterval mergeInterval = new MergeInterval();
89 | List intervals = new LinkedList<>();
90 | intervals.add(new Interval(0, 1));
91 | intervals.add(new Interval(3, 5));
92 | intervals.add(new Interval(7, 8));
93 | intervals.add(new Interval(9, 10));
94 | List merge = mergeInterval.insert(intervals, new Interval(2, 6));
95 | for (Interval a : merge) {
96 | System.out.println(a.start + "," + a.end);
97 | }
98 |
99 | // List intervals1 = new LinkedList<>();
100 | // intervals1.add(new Interval(6, 7));
101 | // intervals1.add(new Interval(2, 4));
102 | // intervals1.add(new Interval(5, 9));
103 | // List merge1 = mergeInterval.mergeInterval(intervals1);
104 | // for (Interval a : merge1) {
105 | // System.out.println(a.start + "," + a.end);
106 | // }
107 | //
108 | // List intervals2 = new LinkedList<>();
109 | // intervals2.add(new Interval(1, 4));
110 | // intervals2.add(new Interval(2, 6));
111 | // intervals2.add(new Interval(3, 5));
112 | // List merge2 = mergeInterval.mergeInterval(intervals2);
113 | // for (Interval a : merge2) {
114 | // System.out.println(a.start + "," + a.end);
115 | // }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/list/CircularLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.list;
2 |
3 | import java.util.NoSuchElementException;
4 |
5 | public class CircularLinkedList {
6 | private ListNode last;
7 | private int length;
8 |
9 | private class ListNode {
10 | private ListNode next;
11 | private int data;
12 |
13 | public ListNode(int data) {
14 | this.data = data;
15 | }
16 | }
17 |
18 | public CircularLinkedList() {
19 | last = null;
20 | length = 0;
21 | }
22 |
23 | public int length() {
24 | return length;
25 | }
26 |
27 | public boolean isEmpty() {
28 | return length == 0;
29 | }
30 |
31 | public void createCircularLinkedList() {
32 | ListNode first = new ListNode(1);
33 | ListNode second = new ListNode(5);
34 | ListNode third = new ListNode(10);
35 | ListNode fourth = new ListNode(15);
36 |
37 | first.next = second;
38 | second.next = third;
39 | third.next = fourth;
40 | fourth.next = first;
41 |
42 | last = fourth;
43 | }
44 |
45 | public void display() {
46 | if (last == null) {
47 | return;
48 | }
49 |
50 | ListNode first = last.next;
51 | while (first != last) {
52 | System.out.print(first.data + " --> ");
53 | first = first.next;
54 | }
55 | System.out.println(first.data);
56 | }
57 |
58 | public void insertFirst(int data) {
59 | ListNode temp = new ListNode(data);
60 | if (last == null) {
61 | last = temp;
62 | } else {
63 | temp.next = last.next;
64 | }
65 | last.next = temp;
66 | length++;
67 | }
68 |
69 | public void insertLast(int data) {
70 | ListNode temp = new ListNode(data);
71 | if (last == null) {
72 | last = temp;
73 | last.next = last;
74 | } else {
75 | temp.next = last.next;
76 | last.next = temp;
77 | last = temp;
78 | }
79 | length++;
80 | }
81 |
82 | public ListNode removeFirst() {
83 | if (isEmpty()) {
84 | throw new NoSuchElementException("Circular Singly Linked List is already empty");
85 | }
86 |
87 | ListNode temp = last.next;
88 | if (last.next == last) {
89 | last = null;
90 | } else {
91 | last.next = temp.next;
92 | }
93 | temp.next = null;
94 | length--;
95 | return temp;
96 | }
97 |
98 | public static void main(String[] args) {
99 | CircularLinkedList cll = new CircularLinkedList();
100 | cll.createCircularLinkedList();
101 | cll.display();
102 | }
103 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/list/DoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.list;
2 |
3 | import java.util.NoSuchElementException;
4 |
5 | public class DoublyLinkedList {
6 |
7 | private ListNode head;
8 | private ListNode tail;
9 | private int length;
10 |
11 | private class ListNode {
12 | private int data; // Can be any generic type
13 | private ListNode next;
14 | private ListNode previous;
15 |
16 | public ListNode(int data) {
17 | this.data = data;
18 | }
19 | }
20 |
21 | public DoublyLinkedList() {
22 | this.head = null;
23 | this.tail = null;
24 | this.length = 0;
25 | }
26 |
27 | public boolean isEmpty() {
28 | return length == 0; // or head == null
29 | }
30 |
31 | public int length() {
32 | return length;
33 | }
34 |
35 | public void displayForward() {
36 | if (head == null) {
37 | return;
38 | }
39 |
40 | ListNode temp = head;
41 | while (temp != null) {
42 | System.out.print(temp.data + " --> ");
43 | temp = temp.next;
44 | }
45 | System.out.println("null");
46 | }
47 |
48 | public void displayBackward() {
49 | if (head == null) {
50 | return;
51 | }
52 |
53 | ListNode temp = tail;
54 | while (temp != null) {
55 | System.out.print(temp.data + " --> ");
56 | temp = temp.previous;
57 | }
58 | System.out.println("null");
59 | }
60 |
61 | public void insertFirst(int value) {
62 | ListNode newNode = new ListNode(value);
63 | if (isEmpty()) {
64 | tail = newNode;
65 | } else {
66 | head.previous = newNode;
67 | }
68 | newNode.next = head;
69 | head = newNode;
70 | length++;
71 | }
72 |
73 | public void insertEnd(int value) {
74 | ListNode newNode = new ListNode(value);
75 | if (isEmpty()) {
76 | head = newNode;
77 | } else {
78 | tail.next = newNode;
79 | newNode.previous = tail;
80 | }
81 | tail = newNode;
82 | length++;
83 | }
84 |
85 | public ListNode deleteFirst() {
86 | if (isEmpty()) {
87 | throw new NoSuchElementException();
88 | }
89 |
90 | ListNode temp = head;
91 | if (head == tail) {
92 | tail = null;
93 | } else {
94 | head.next.previous = null;
95 | }
96 | head = head.next;
97 | temp.next = null;
98 | length--;
99 | return temp;
100 | }
101 |
102 | public ListNode deleteLast() {
103 | if (isEmpty()) {
104 | throw new NoSuchElementException();
105 | }
106 |
107 | ListNode temp = tail;
108 | if (head == tail) {
109 | head = null;
110 | } else {
111 | tail.previous.next = null;
112 | }
113 | tail = tail.previous;
114 | temp.previous = null;
115 | length--;
116 | return temp;
117 | }
118 |
119 | public static void main(String[] args) {
120 | DoublyLinkedList dll = new DoublyLinkedList();
121 | dll.insertEnd(1);
122 | dll.insertEnd(2);
123 | dll.insertEnd(3);
124 |
125 | dll.displayForward();
126 |
127 | dll.deleteLast();
128 | dll.deleteLast();
129 |
130 | dll.displayForward();
131 | }
132 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/list/SinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.list;
2 |
3 | public class SinglyLinkedList {
4 |
5 | private ListNode head;
6 |
7 | private static class ListNode {
8 | private int data; // Can be a generic type
9 | private ListNode next; // Reference to next ListNode in list
10 |
11 | public ListNode(int data) {
12 | this.data = data;
13 | this.next = null;
14 | }
15 | }
16 |
17 | public void display() {
18 | ListNode current = head;
19 | while (current != null) {
20 | System.out.print(current.data + " --> ");
21 | current = current.next;
22 | }
23 | System.out.print("null");
24 | System.out.println();
25 | }
26 |
27 | public int length() {
28 | if (head == null) {
29 | return 0;
30 | }
31 | int count = 0;
32 | ListNode current = head;
33 | while (current != null) {
34 | count++;
35 | current = current.next;
36 | }
37 | return count;
38 | }
39 |
40 | public void insertFirst(int value) {
41 | ListNode newNode = new ListNode(value);
42 | newNode.next = head;
43 | head = newNode;
44 | }
45 |
46 | public void insert(int position, int value) {
47 | // 1 -> 4 -> 5
48 | // 1 -> 6 -> 4 -> 5
49 | ListNode node = new ListNode(value);
50 |
51 | if (position == 1) {
52 | node.next = head;
53 | head = node;
54 | } else {
55 | ListNode previous = head;
56 | int count = 1; // position - 1
57 |
58 | while (count < position - 1) {
59 | previous = previous.next;
60 | count++;
61 | }
62 |
63 | ListNode current = previous.next;
64 | previous.next = node;
65 | node.next = current;
66 | }
67 |
68 | }
69 |
70 | public void insertLast(int value) {
71 | ListNode newNode = new ListNode(value);
72 | if (head == null) {
73 | head = newNode;
74 | return;
75 | }
76 | ListNode current = head;
77 | while (null != current.next) {
78 | current = current.next;
79 | }
80 | current.next = newNode;
81 | }
82 |
83 | public ListNode deleteFirst() {
84 | if (head == null) {
85 | return null;
86 | }
87 | ListNode temp = head;
88 | head = head.next;
89 | temp.next = null;
90 | return temp;
91 | }
92 |
93 | public void delete(int position) {
94 | // position is valid and starting from 1
95 | // 3 -> 4 -> 7 -> 8 -> 9 -> null
96 | if (position == 1) {
97 | head = head.next;
98 | } else {
99 | ListNode previous = head;
100 | int count = 1;
101 | while (count < position - 1) {
102 | previous = previous.next;
103 | count++;
104 | }
105 |
106 | ListNode current = previous.next;
107 | previous.next = current.next;
108 | }
109 | }
110 |
111 | public ListNode deleteLast() {
112 | if (head == null) {
113 | return head;
114 | }
115 |
116 | if (head.next == null) {
117 | ListNode temp = head;
118 | head = head.next;
119 | return temp;
120 | }
121 |
122 | ListNode current = head;
123 | ListNode previous = null;
124 |
125 | while (current.next != null) {
126 | previous = current;
127 | current = current.next;
128 | }
129 | previous.next = null; // break the chain
130 | return current;
131 | }
132 |
133 | public boolean find(int searchKey) {
134 | if (head == null) {
135 | return false;
136 | }
137 |
138 | ListNode current = head;
139 | while (current != null) {
140 | if (current.data == searchKey) {
141 | return true;
142 | }
143 | current = current.next;
144 | }
145 | return false;
146 | }
147 |
148 | public ListNode reverse() {
149 | if (head == null) {
150 | return null;
151 | }
152 |
153 | ListNode current = head;
154 | ListNode previous = null;
155 | ListNode next = null;
156 |
157 | while (current != null) {
158 | next = current.next;
159 | current.next = previous;
160 | previous = current;
161 | current = next;
162 | }
163 | return previous;
164 | }
165 |
166 | public ListNode getMiddleNode() {
167 | if (head == null) {
168 | return null;
169 | }
170 | ListNode slowPtr = head;
171 | ListNode fastPtr = head;
172 |
173 | while (fastPtr != null && fastPtr.next != null) {
174 | slowPtr = slowPtr.next;
175 | fastPtr = fastPtr.next.next;
176 | }
177 | return slowPtr;
178 | }
179 |
180 | public ListNode getNthNodeFromEnd(int n) {
181 | if (head == null) {
182 | return null;
183 | }
184 |
185 | if (n <= 0) {
186 | throw new IllegalArgumentException("Invalid value: n = " + n);
187 | }
188 |
189 | ListNode mainPtr = head;
190 | ListNode refPtr = head;
191 |
192 | int count = 0;
193 |
194 | while (count < n) {
195 | if (refPtr == null) {
196 | throw new IllegalArgumentException(n + " is greater than the number of nodes in list");
197 | }
198 | refPtr = refPtr.next;
199 | count++;
200 | }
201 |
202 | while (refPtr != null) {
203 | refPtr = refPtr.next;
204 | mainPtr = mainPtr.next;
205 | }
206 | return mainPtr;
207 | }
208 |
209 | public ListNode insertInSortedList(int value) {
210 | ListNode newNode = new ListNode(value);
211 |
212 | if (head == null) {
213 | return newNode;
214 | }
215 |
216 | ListNode current = head;
217 | ListNode temp = null;
218 |
219 | while (current != null && current.data < newNode.data) {
220 | temp = current;
221 | current = current.next;
222 | }
223 |
224 | newNode.next = current;
225 | temp.next = newNode;
226 | return head;
227 | }
228 |
229 | public void deleteNode(int key) {
230 | ListNode current = head;
231 | ListNode temp = null;
232 |
233 | if (current != null && current.data == key) {
234 | head = current.next;
235 | return;
236 | }
237 |
238 | while (current != null && current.data != key) {
239 | temp = current;
240 | current = current.next;
241 | }
242 |
243 | if (current == null) {
244 | return;
245 | }
246 |
247 | temp.next = current.next;
248 | }
249 |
250 | public boolean containsLoop() {
251 | ListNode fastPtr = head;
252 | ListNode slowPtr = head;
253 |
254 | while (fastPtr != null && fastPtr.next != null) {
255 | fastPtr = fastPtr.next.next;
256 | slowPtr = slowPtr.next;
257 |
258 | if (fastPtr == slowPtr) {
259 | return true;
260 | }
261 | }
262 | return false;
263 | }
264 |
265 | public ListNode startNodeInALoop() {
266 | ListNode fastPtr = head;
267 | ListNode slowPtr = head;
268 |
269 | while (fastPtr != null && fastPtr.next != null) {
270 | fastPtr = fastPtr.next.next;
271 | slowPtr = slowPtr.next;
272 |
273 | if (fastPtr == slowPtr) {
274 | return getStartingNode(slowPtr);
275 | }
276 | }
277 | return null;
278 | }
279 |
280 | private ListNode getStartingNode(ListNode slowPtr) {
281 | ListNode temp = head;
282 | while (temp != slowPtr) {
283 | temp = temp.next;
284 | slowPtr = slowPtr.next;
285 | }
286 | return temp; // starting node of the loop
287 | }
288 |
289 | public void removeLoop() {
290 | ListNode fastPtr = head;
291 | ListNode slowPtr = head;
292 |
293 | while (fastPtr != null && fastPtr.next != null) {
294 | fastPtr = fastPtr.next.next;
295 | slowPtr = slowPtr.next;
296 |
297 | if (fastPtr == slowPtr) {
298 | removeLoop(slowPtr);
299 | return;
300 | }
301 | }
302 | }
303 |
304 | private void removeLoop(ListNode slowPtr) {
305 | ListNode temp = head;
306 | while (temp.next != slowPtr.next) {
307 | temp = temp.next;
308 | slowPtr = slowPtr.next;
309 | }
310 | slowPtr.next = null;
311 | }
312 |
313 | public void createALoopInLinkedList() {
314 | ListNode first = new ListNode(1);
315 | ListNode second = new ListNode(2);
316 | ListNode third = new ListNode(3);
317 | ListNode fourth = new ListNode(4);
318 | ListNode fifth = new ListNode(5);
319 | ListNode sixth = new ListNode(6);
320 |
321 | head = first;
322 | first.next = second;
323 | second.next = third;
324 | third.next = fourth;
325 | fourth.next = fifth;
326 | fifth.next = sixth;
327 | sixth.next = third;
328 | }
329 |
330 | public static ListNode merge(ListNode a, ListNode b) {
331 | // a --> 1 --> 3 --> 5 --> null
332 | // b --> 2 --> 4 --> 6 --> null
333 | // result --> 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> null
334 | ListNode dummy = new ListNode(0);
335 | ListNode tail = dummy;
336 | while (a != null && b != null) {
337 | if (a.data <= b.data) {
338 | tail.next = a;
339 | a = a.next;
340 | } else {
341 | tail.next = b;
342 | b = b.next;
343 | }
344 | tail = tail.next;
345 | }
346 |
347 | // a --> 1 --> 3 --> null
348 | // b --> 2 --> 4 --> 6 --> 7 --> 9 --> 10 --> null
349 | // result --> 1 --> 2 --> 3 --> 4 --> 6 --> 7 --> 9 --> 10 --> null
350 |
351 | if (a == null) {
352 | tail.next = b;
353 | } else {
354 | tail.next = a;
355 | }
356 |
357 | return dummy.next;
358 | }
359 |
360 | public static void main(String[] args) {
361 | SinglyLinkedList sll1 = new SinglyLinkedList();
362 | sll1.insertLast(1);
363 | sll1.insertLast(4);
364 | sll1.insertLast(8);
365 |
366 | SinglyLinkedList sll2 = new SinglyLinkedList();
367 | sll2.insertLast(3);
368 | sll2.insertLast(5);
369 | sll2.insertLast(8);
370 | sll2.insertLast(9);
371 | sll2.insertLast(14);
372 | sll2.insertLast(18);
373 |
374 | sll1.display();
375 | sll2.display();
376 |
377 | SinglyLinkedList result = new SinglyLinkedList();
378 | result.head = merge(sll1.head, sll2.head);
379 |
380 | result.display();
381 | }
382 |
383 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/mathematics/RemoveEvenInteger.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.mathematics;
2 |
3 | public class RemoveEvenInteger {
4 |
5 | public static void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public static int[] removeEven(int[] arr) {
14 | int oddCount = 0;
15 | for (int i = 0; i < arr.length; i++) {
16 | if (arr[i] % 2 != 0) {
17 | oddCount++;
18 | }
19 | }
20 | int[] result = new int[oddCount];
21 | int idx = 0;
22 | for (int i = 0; i < arr.length; i++) {
23 | if (arr[i] % 2 != 0) {
24 | result[idx] = arr[i];
25 | idx++;
26 | }
27 | }
28 | return result;
29 | }
30 |
31 | public static void main(String[] args) {
32 | int[] arr = { 3, 2, 4, 7, 10, 6, 5 }; // 3, 7, 5
33 | printArray(arr);
34 | int[] result = removeEven(arr);
35 | printArray(result);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/matrix/SortedMatrix.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.matrix;
2 |
3 | public class SortedMatrix {
4 |
5 | public void search(int[][] matrix, int n, int x) {
6 | int i = 0;
7 | int j = n - 1;
8 |
9 | while (i < n && j >= 0) {
10 | if (matrix[i][j] == x) {
11 | System.out.println("x found at - " + i + ", " + j);
12 | return;
13 | }
14 | if (matrix[i][j] > x) {
15 | j--;
16 | } else {
17 | i++;
18 | }
19 | }
20 | System.out.println("Value not found");
21 | }
22 |
23 | public static void main(String[] args) {
24 | int[][] matrix = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 51 } };
25 |
26 | SortedMatrix sm = new SortedMatrix();
27 | sm.search(matrix, matrix.length, 32);
28 | sm.search(matrix, matrix.length, 100);
29 | }
30 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/matrix/SpiralMatrix.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.matrix;
2 |
3 | public class SpiralMatrix {
4 |
5 | public static void spiralPrint(int[][] matrix, int r, int c) {
6 | int i;
7 | int k = 0; // k -> r
8 | int l = 0; // l -> c
9 |
10 | while (k < r && l < c) {
11 | // left to right --> column varies --> l -> c - 1, row remains constant
12 | for (i = l; i < c; i++) {
13 | System.out.print(matrix[k][i] + " ");
14 | }
15 | k++;
16 | // top to bottom --> row varies --> k -> r - 1, column remains constant
17 | for (i = k; i < r; i++) {
18 | System.out.print(matrix[i][c - 1] + " ");
19 | }
20 | c--;
21 | if (k < r) {
22 | // right to left --> column varies --> c - 1 -> l, row remains constant
23 | for (i = c - 1; i >= l; i--) {
24 | System.out.print(matrix[r - 1][i] + " ");
25 | }
26 | r--;
27 | }
28 | if (l < c) {
29 | // bottom to top --> row varies --> r - 1 -> k, column remains constant
30 | for (i = r - 1; i >= k; i--) {
31 | System.out.print(matrix[i][l] + " ");
32 | }
33 | l++;
34 | }
35 | }
36 | }
37 |
38 | public static void main(String[] args) {
39 | int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
40 | spiralPrint(matrix, matrix.length, matrix[0].length);
41 | }
42 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/queue/Queue.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.queue;
2 |
3 | import java.util.NoSuchElementException;
4 |
5 | public class Queue {
6 |
7 | private ListNode front;
8 | private ListNode rear;
9 | private int length;
10 |
11 | private class ListNode {
12 | private int data; // Can be a generic type
13 | private ListNode next; // Reference to next ListNode in list
14 |
15 | public ListNode(int data) {
16 | this.data = data;
17 | this.next = null;
18 | }
19 | }
20 |
21 | public Queue() {
22 | front = null;
23 | rear = null;
24 | length = 0;
25 | }
26 |
27 | public int length() {
28 | return length;
29 | }
30 |
31 | public boolean isEmpty() {
32 | return length == 0;
33 | }
34 |
35 | public void enqueue(int data) {
36 | ListNode temp = new ListNode(data);
37 | if (isEmpty()) {
38 | front = temp;
39 | } else {
40 | rear.next = temp;
41 | }
42 |
43 | rear = temp;
44 | length++;
45 | }
46 |
47 | public int dequeue() {
48 | if (isEmpty()) {
49 | throw new NoSuchElementException("Queue is already empty");
50 | }
51 |
52 | int result = front.data;
53 | front = front.next;
54 | if (front == null) {
55 | rear = null;
56 | }
57 | length--;
58 | return result;
59 | }
60 |
61 | public void print() {
62 | if (isEmpty()) {
63 | return;
64 | }
65 |
66 | ListNode current = front;
67 | while (current != null) {
68 | System.out.print(current.data + " --> ");
69 | current = current.next;
70 | }
71 | System.out.println("null");
72 | }
73 |
74 | public static void main(String[] args) {
75 | Queue queue = new Queue();
76 | queue.enqueue(10);
77 | queue.enqueue(15);
78 | queue.enqueue(20);
79 |
80 | queue.print();
81 |
82 | queue.dequeue();
83 | queue.dequeue();
84 |
85 | queue.print();
86 | }
87 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/search/BinarySearch.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.search;
2 |
3 | public class BinarySearch {
4 |
5 | public int binarySearch(int[] nums, int key) {
6 | int low = 0;
7 | int high = nums.length - 1;
8 |
9 | while (low <= high) {
10 | int mid = (high + low) / 2;
11 |
12 | if (nums[mid] == key) {
13 | return mid;
14 | }
15 | if (key < nums[mid]) {
16 | high = mid - 1;
17 | } else {
18 | low = mid + 1;
19 | }
20 | }
21 | return -1;
22 | }
23 |
24 | public static void main(String[] args) {
25 | BinarySearch bs = new BinarySearch();
26 | int[] nums = { 1, 10, 20, 47, 59, 65, 75, 88, 99 };
27 | System.out.println(bs.binarySearch(nums, 65));
28 | }
29 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/search/LinearSearch.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.search;
2 |
3 | public class LinearSearch {
4 |
5 | public int search(int[] arr, int n, int x) {
6 | // edge case
7 | if (arr == null || arr.length == 0) {
8 | throw new IllegalArgumentException("Invalid input");
9 | }
10 |
11 | for (int i = 0; i < n; i++) {
12 | if (arr[i] == x) {
13 | return i;
14 | }
15 | }
16 | return -1;
17 | }
18 |
19 | public static void main(String[] args) {
20 | int[] arr = { 5, 1, 9, 2, 10, 15, 20 };
21 | LinearSearch ls = new LinearSearch();
22 | System.out.println(ls.search(arr, arr.length, 50));
23 | }
24 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/sorting/BubbleSort.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.sorting;
2 |
3 | public class BubbleSort {
4 |
5 | public void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public void sort(int[] arr) {
14 | int n = arr.length;
15 | boolean isSwapped;
16 |
17 | for (int i = 0; i < n - 1; i++) {
18 | isSwapped = false;
19 | for (int j = 0; j < n - 1 - i; j++) {
20 | if (arr[j] > arr[j + 1]) {
21 | int temp = arr[j];
22 | arr[j] = arr[j + 1];
23 | arr[j + 1] = temp;
24 | isSwapped = true;
25 | }
26 | }
27 | if (isSwapped == false) {
28 | break;
29 | }
30 |
31 | }
32 |
33 | }
34 |
35 | public static void main(String[] args) {
36 | int[] arr = new int[] { 5, 1, 2, 9, 10 };
37 | BubbleSort bs = new BubbleSort();
38 | bs.printArray(arr);
39 | bs.sort(arr);
40 | bs.printArray(arr);
41 |
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/sorting/InsertionSort.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.sorting;
2 |
3 | public class InsertionSort {
4 |
5 | public void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public void sort(int[] arr) {
14 | int n = arr.length;
15 |
16 | for (int i = 1; i < n; i++) { // unsorted part
17 | int temp = arr[i];
18 | int j = i - 1; // sorted part
19 |
20 | while (j >= 0 && arr[j] > temp) {
21 | arr[j + 1] = arr[j]; // shifting larger elements to temp by 1 pos
22 | j = j - 1;
23 | }
24 | arr[j + 1] = temp;
25 | }
26 | }
27 |
28 | public static void main(String[] args) {
29 | int[] arr = new int[] { 5, 1, 2, 9, 10 };
30 | InsertionSort is = new InsertionSort();
31 | is.printArray(arr);
32 | is.sort(arr);
33 | is.printArray(arr);
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/sorting/MergeSort.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.sorting;
2 |
3 | public class MergeSort {
4 |
5 | public void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public void sort(int[] arr, int[] temp, int low, int high) {
14 | if (low < high) { // base case
15 | int mid = low + (high - low) / 2; // overflow condition (low + high) / 2;
16 | sort(arr, temp, low, mid);
17 | sort(arr, temp, mid + 1, high);
18 | merge(arr, temp, low, mid, high);
19 | }
20 | }
21 |
22 | private void merge(int[] arr, int[] temp, int low, int mid, int high) {
23 | for (int i = low; i <= high; i++) {
24 | temp[i] = arr[i];
25 | }
26 | int i = low; // traverse left sorted subarray
27 | int j = mid + 1; // traverse right sorted subarray
28 | int k = low; // will merge both arrays into original array (arr)
29 |
30 | while (i <= mid && j <= high) {
31 | if (temp[i] <= temp[j]) {
32 | arr[k] = temp[i];
33 | i++;
34 | } else {
35 | arr[k] = temp[j];
36 | j++;
37 | }
38 | k++;
39 | }
40 |
41 | while (i <= mid) {
42 | arr[k] = temp[i];
43 | k++;
44 | i++;
45 | }
46 | }
47 |
48 | public static void main(String[] args) {
49 | int[] arr = new int[] { 9, 5, 2, 4, 3, -1 };
50 | MergeSort ms = new MergeSort();
51 | ms.sort(arr, new int[arr.length], 0, arr.length - 1);
52 | ms.printArray(arr);
53 | }
54 |
55 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/sorting/SelectionSort.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.sorting;
2 |
3 | public class SelectionSort {
4 |
5 | public void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public void sort(int[] arr) {
14 | int n = arr.length;
15 | for (int i = 0; i < n - 1; i++) {
16 | int min = i;
17 | for (int j = i + 1; j < n; j++) {
18 | if (arr[j] < arr[min]) {
19 | min = j;
20 | }
21 | }
22 | int temp = arr[min];
23 | arr[min] = arr[i];
24 | arr[i] = temp;
25 | }
26 | }
27 |
28 | public static void main(String[] args) {
29 | int[] arr = new int[] { 5, 1, 2, 9, 10 };
30 | SelectionSort ss = new SelectionSort();
31 | ss.printArray(arr);
32 | ss.sort(arr);
33 | ss.printArray(arr);
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/sorting/Sort012.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.sorting;
2 |
3 | public class Sort012 {
4 |
5 | public void printArray(int[] arr) {
6 | int n = arr.length;
7 | for (int i = 0; i < n; i++) {
8 | System.out.print(arr[i] + " ");
9 | }
10 | System.out.println();
11 | }
12 |
13 | public void threeNumberSort(int[] arr) {
14 | // 3 pointer technique
15 | int i = 0; // traverse the array and place 1's in the middle region
16 | int j = 0; // place 0's at the starting range
17 | int k = arr.length - 1; // place 2's at the end
18 | while (i <= k) {
19 | if (arr[i] == 0) {
20 | swap(arr, i, j);
21 | j++;
22 | i++;
23 | } else if (arr[i] == 1) {
24 | i++;
25 | } else if (arr[i] == 2) {
26 | swap(arr, i, k);
27 | k--;
28 | }
29 | }
30 | }
31 |
32 | private static void swap(int[] arr, int first, int second) {
33 | int temp = arr[first];
34 | arr[first] = arr[second];
35 | arr[second] = temp;
36 | }
37 |
38 | public static void main(String[] args) {
39 | int[] arr = new int[] { 2, 0, 0, 1, 0, 2, 0, 1, 0, 2, 2, 0 };
40 | Sort012 st = new Sort012();
41 | st.printArray(arr);
42 | st.threeNumberSort(arr);
43 | st.printArray(arr);
44 | }
45 |
46 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/stack/StringReverse.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.stack;
2 |
3 | import java.util.Stack;
4 |
5 | public class StringReverse {
6 |
7 | public static String reverse(String str) {
8 | Stack stack = new Stack<>();
9 | char[] chars = str.toCharArray();
10 |
11 | for (char c : chars) {
12 | stack.push(c);
13 | }
14 |
15 | for (int i = 0; i < str.length(); i++) {
16 | chars[i] = stack.pop();
17 | }
18 | return new String(chars);
19 | }
20 |
21 | public static void main(String[] args) {
22 | String str = "ABCD";
23 | System.out.println("Before reverse - " + str);
24 | System.out.println("After reverse - " + reverse(str));
25 | }
26 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/stack/impl/array/Stack.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.stack.impl.array;
2 |
3 | public class Stack {
4 |
5 | private int top;
6 | private int[] arr;
7 |
8 | public Stack(int capacity) {
9 | top = -1;
10 | arr = new int[capacity];
11 | }
12 |
13 | public Stack() {
14 | this(10);
15 | }
16 |
17 | public int size() {
18 | return top + 1;
19 | }
20 |
21 | public boolean isEmpty() {
22 | return top < 0;
23 | }
24 |
25 | public boolean isFull() {
26 | return arr.length == size();
27 | }
28 |
29 | public void push(int data) {
30 | if (isFull()) {
31 | throw new RuntimeException("Stack is full !!!");
32 | }
33 | top++;
34 | arr[top] = data;
35 | }
36 |
37 | public int pop() {
38 | if (isEmpty()) {
39 | throw new RuntimeException("Stack is empty !!!");
40 | }
41 | int result = arr[top];
42 | top--;
43 | return result;
44 | }
45 |
46 | public int peek() {
47 | if (isEmpty()) {
48 | throw new RuntimeException("Stack is empty !!!");
49 | }
50 | return arr[top];
51 | }
52 |
53 | public static void main(String[] args) {
54 | Stack stack = new Stack(3);
55 | stack.push(10);
56 | stack.push(15);
57 | stack.push(20);
58 |
59 | System.out.println(stack.peek());
60 | stack.pop();
61 | System.out.println(stack.peek());
62 | stack.pop();
63 | System.out.println(stack.peek());
64 | stack.pop();
65 | stack.pop();
66 | }
67 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/stack/impl/list/Stack.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.stack.impl.list;
2 |
3 | import java.util.EmptyStackException;
4 |
5 | public class Stack {
6 |
7 | private ListNode top;
8 | private int length;
9 |
10 | private class ListNode {
11 | private int data; // Can be a generic type
12 | private ListNode next; // Reference to next ListNode in list
13 |
14 | public ListNode(int data) {
15 | this.data = data;
16 | this.next = null;
17 | }
18 | }
19 |
20 | public Stack() {
21 | top = null;
22 | length = 0;
23 | }
24 |
25 | public int length() {
26 | return length;
27 | }
28 |
29 | public boolean isEmpty() {
30 | return length == 0;
31 | }
32 |
33 | public void push(int data) {
34 | ListNode temp = new ListNode(data);
35 | temp.next = top;
36 | top = temp;
37 | length++;
38 | }
39 |
40 | public int pop() {
41 | if (isEmpty()) {
42 | throw new EmptyStackException();
43 | }
44 | int result = top.data;
45 | top = top.next;
46 | length--;
47 | return result;
48 | }
49 |
50 | public int peek() {
51 | if (isEmpty()) {
52 | throw new EmptyStackException();
53 | }
54 | return top.data;
55 | }
56 |
57 | public static void main(String[] args) {
58 | Stack stack = new Stack();
59 | stack.push(10);
60 | stack.push(15);
61 | stack.push(20);
62 |
63 | System.out.println(stack.peek());
64 | stack.pop();
65 | System.out.println(stack.peek());
66 | stack.pop();
67 | System.out.println(stack.peek());
68 | }
69 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/string/StringUtil.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.string;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Set;
6 |
7 | public class StringUtil {
8 |
9 | public static boolean isSubsequence(String str, String seq) {
10 | int i = 0; // traverse str "abcde"
11 | int j = 0; // traverse seq "aec"
12 |
13 | while (i < str.length() && j < seq.length()) {
14 | if (str.charAt(i) == seq.charAt(j)) {
15 | j++;
16 | }
17 | i++;
18 | }
19 | return j == seq.length();
20 | }
21 |
22 | public static String removeVowels(String str) {
23 | Set vowels = Set.of('a', 'e', 'i', 'o', 'u');
24 | StringBuilder sb = new StringBuilder();
25 |
26 | char[] chars = str.toCharArray();
27 | for (Character ch : chars) {
28 | if (!vowels.contains(ch)) { // c b j k O(1)
29 | sb.append(ch);
30 | }
31 | }
32 | return sb.toString();
33 | }
34 |
35 | public static int firstNonRepeatingCharacter(String str) {
36 | Map characterFrequencyMap = new HashMap<>();
37 | char[] chars = str.toCharArray(); // aba
38 | for (char ch : chars) {
39 | characterFrequencyMap.put(ch, characterFrequencyMap.getOrDefault(ch, 0) + 1);
40 | }
41 |
42 | for (int i = 0; i < chars.length; i++) {
43 | char ch = chars[i];
44 | if (characterFrequencyMap.get(ch) == 1) {
45 | return i;
46 | }
47 | }
48 | return -1;
49 | }
50 |
51 | public static void main(String[] args) {
52 | System.out.println(firstNonRepeatingCharacter("abafbabe"));
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/tree/BinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.tree;
2 |
3 | public class BinarySearchTree {
4 |
5 | private TreeNode root;
6 |
7 | private class TreeNode {
8 | private int data; // Generic type
9 | private TreeNode left;
10 | private TreeNode right;
11 |
12 | public TreeNode(int data) {
13 | this.data = data;
14 | }
15 | }
16 |
17 | public void insert(int value) {
18 | root = insert(root, value);
19 | }
20 |
21 | public TreeNode insert(TreeNode root, int value) {
22 | if (root == null) {
23 | root = new TreeNode(value);
24 | return root;
25 | }
26 |
27 | if (value < root.data) {
28 | root.left = insert(root.left, value);
29 | } else {
30 | root.right = insert(root.right, value);
31 | }
32 | return root;
33 | }
34 |
35 | public void inOrder() {
36 | inOrder(root);
37 | }
38 |
39 | public void inOrder(TreeNode root) {
40 | if (root == null) {
41 | return;
42 | }
43 | inOrder(root.left);
44 | System.out.print(root.data + " ");
45 | inOrder(root.right);
46 | }
47 |
48 | public TreeNode search(int key) {
49 | return search(root, key);
50 | }
51 |
52 | public TreeNode search(TreeNode root, int key) {
53 | if (root == null || root.data == key) { // base case
54 | return root;
55 | }
56 |
57 | if (key < root.data) {
58 | return search(root.left, key);
59 | } else {
60 | return search(root.right, key);
61 | }
62 |
63 | }
64 |
65 | public static void main(String[] args) {
66 | BinarySearchTree bst = new BinarySearchTree();
67 | bst.insert(5);
68 | bst.insert(3);
69 | bst.insert(7);
70 | bst.insert(1);
71 |
72 | bst.inOrder();
73 |
74 | System.out.println();
75 |
76 | if (null != bst.search(10)) {
77 | System.out.println("Key found !!!");
78 | } else {
79 | System.out.println("Key not found !!!");
80 | }
81 | }
82 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/tree/BinaryTree.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.tree;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 | import java.util.Stack;
6 |
7 | public class BinaryTree {
8 |
9 | private TreeNode root;
10 |
11 | private class TreeNode {
12 | private TreeNode left;
13 | private TreeNode right;
14 | private int data; // Can be any generic type
15 |
16 | public TreeNode(int data) {
17 | this.data = data;
18 | }
19 | }
20 |
21 | public void preOrder(TreeNode root) {
22 | if (root == null) {
23 | return;
24 | }
25 |
26 | System.out.print(root.data + " ");
27 | preOrder(root.left);
28 | preOrder(root.right);
29 | }
30 |
31 | public void preOrder() {
32 | if (root == null) {
33 | return;
34 | }
35 |
36 | Stack stack = new Stack<>();
37 | stack.push(root);
38 |
39 | while (!stack.isEmpty()) {
40 | TreeNode temp = stack.pop();
41 | System.out.print(temp.data + " ");
42 | if (temp.right != null) {
43 | stack.push(temp.right);
44 | }
45 | if (temp.left != null) {
46 | stack.push(temp.left);
47 | }
48 | }
49 | }
50 |
51 | public void inOrder(TreeNode root) {
52 | if (root == null) {
53 | return;
54 | }
55 |
56 | inOrder(root.left);
57 | System.out.print(root.data + " ");
58 | inOrder(root.right);
59 | }
60 |
61 | public void inOrder() {
62 | if (root == null) {
63 | return;
64 | }
65 |
66 | Stack stack = new Stack<>();
67 | TreeNode temp = root;
68 |
69 | while (!stack.isEmpty() || temp != null) {
70 | if (temp != null) {
71 | stack.push(temp);
72 | temp = temp.left;
73 | } else {
74 | temp = stack.pop();
75 | System.out.print(temp.data + " ");
76 | temp = temp.right;
77 | }
78 | }
79 | }
80 |
81 | public void postOrder(TreeNode root) {
82 | if (root == null) {
83 | return;
84 | }
85 |
86 | postOrder(root.left);
87 | postOrder(root.right);
88 | System.out.print(root.data + " ");
89 | }
90 |
91 | public void postOrder() {
92 | TreeNode current = root;
93 | Stack stack = new Stack<>();
94 |
95 | while (current != null || !stack.isEmpty()) {
96 | if (current != null) {
97 | stack.push(current);
98 | current = current.left;
99 | } else {
100 | TreeNode temp = stack.peek().right;
101 | if (temp == null) {
102 | temp = stack.pop();
103 | System.out.print(temp.data + " ");
104 | while (!stack.isEmpty() && temp == stack.peek().right) {
105 | temp = stack.pop();
106 | System.out.print(temp.data + " ");
107 | }
108 | } else {
109 | current = temp;
110 | }
111 | }
112 | }
113 | }
114 |
115 | public void levelOrder() {
116 | if (root == null) {
117 | return;
118 | }
119 |
120 | Queue queue = new LinkedList<>();
121 | queue.offer(root);
122 |
123 | while (!queue.isEmpty()) {
124 | TreeNode temp = queue.poll();
125 | System.out.print(temp.data + " ");
126 | if (temp.left != null) {
127 | queue.offer(temp.left);
128 | }
129 | if (temp.right != null) {
130 | queue.offer(temp.right);
131 | }
132 | }
133 | }
134 |
135 | public int findMax() {
136 | return findMax(root);
137 | }
138 |
139 | public int findMax(TreeNode root) {
140 | if (root == null) {
141 | return Integer.MIN_VALUE;
142 | }
143 |
144 | int result = root.data;
145 | int left = findMax(root.left);
146 | int right = findMax(root.right);
147 |
148 | if (left > result) {
149 | result = left;
150 | }
151 |
152 | if (right > result) {
153 | result = right;
154 | }
155 |
156 | return result;
157 |
158 | }
159 |
160 | public void createBinaryTree() {
161 | TreeNode first = new TreeNode(1);
162 | TreeNode second = new TreeNode(2);
163 | TreeNode third = new TreeNode(3);
164 | TreeNode fourth = new TreeNode(4);
165 | TreeNode fifth = new TreeNode(5);
166 | TreeNode sixth = new TreeNode(6);
167 | TreeNode seventh = new TreeNode(7);
168 |
169 | root = first;
170 | first.left = second;
171 | first.right = third;
172 | second.left = fourth;
173 | second.right = fifth;
174 | third.left = sixth;
175 | third.right = seventh;
176 | }
177 |
178 | public static void main(String[] args) {
179 | BinaryTree bt = new BinaryTree();
180 | bt.createBinaryTree();
181 | bt.postOrder();
182 | }
183 | }
--------------------------------------------------------------------------------
/src/com/hubberspot/dsalgo/trie/Trie.java:
--------------------------------------------------------------------------------
1 | package com.hubberspot.dsalgo.trie;
2 |
3 | public class Trie {
4 |
5 | private TrieNode root;
6 |
7 | public Trie() {
8 | root = new TrieNode(); // root is empty
9 | }
10 |
11 | private class TrieNode {
12 | private TrieNode[] children;
13 | private boolean isWord;
14 |
15 | public TrieNode() {
16 | this.children = new TrieNode[26]; // storing english words - a -> z this.isWord = false;
17 | }
18 | }
19 |
20 | public void insert(String word) {
21 | if (word == null || word.isEmpty()) {
22 | throw new IllegalArgumentException("Invalid input");
23 | }
24 |
25 | word = word.toLowerCase();
26 |
27 | TrieNode current = root;
28 | for (int i = 0; i < word.length(); i++) {
29 | char c = word.charAt(i);
30 | int index = c - 'a';
31 | if (current.children[index] == null) {
32 | TrieNode node = new TrieNode();
33 | current.children[index] = node;
34 | current = node;
35 | } else {
36 | current = current.children[index];
37 | }
38 | }
39 | current.isWord = true;
40 |
41 | }
42 |
43 | public boolean search(String word) {
44 | return false;
45 | }
46 |
47 | public static void main(String[] args) {
48 | Trie trie = new Trie();
49 | trie.insert("cat");
50 | trie.insert("cab");
51 | trie.insert("son");
52 | trie.insert("so");
53 | System.out.println("Values inserted successfully !!!");
54 | }
55 | }
--------------------------------------------------------------------------------