Data Structures Basics
1. Arrays
int[] arr = new int[10];
arr[1] = 34;
arr[1] = 35;
int i = arr[1];
int size = arr.length;
// Fill array with a value
Arrays.fill(arr, -1);
// Sort
Arrays.sort(arr); // Ascending
Arrays.sort(arr, (a, b) -> b - a); // Descending
2. Character
char c1 = 'a';
char[] arr = "test".toCharArray();
char c2 = str.charAt(2);
// Character
Character.toLowerCase(c)
Character.isLowerCase(c);
Character.toUpperCase(c)
Character.isUpperCase(c);
Character.isLetter(c)
Character.isDigit(c)
Character.isAlphabetic(c);
Character.isLetterOrDigit(c)
3. String and StringBuilder
// String
String str = new String();
str = "abc";
int size = str.length();
char[] arr = str.toCharArray();
String sub = str.substring(1, 3); //[a, b)
str.toLowerCase();
str.toUpperCase();
str.replaceAll("a", "z");
// String Builder
StringBuilder sb = new StringBuilder();
sb.append("hellohowareyou?");
sb.insert(2, "z");
sb.delete(1, 3) // [from, to)
sb.deleteCharAt(0);
sb.reverse();
sb.substring(1);
sb.substring(3, 5); // [from, to)
4. List and ArrayList
List<Integer> list = new ArrayList<>();
list.add(5);
list.addAll(List.of(6, 7, 8, 9, 10));
// Index based
list.remove(3);
list.set(0, 9);
list.get(0);
int size = list.size();
list.clear();
list.isEmpty();
// Inefficient - O(n)
list.contains(77);
list.indexOf(10);
Integer[] arr = list.toArray(new Integer[0]);
int[] arrPrimitive = list.stream().mapToInt(Integer::intValue).toArray();
// Sort O(nlog(n))
Collections.sort(list);
Collections.sort(list, (a, b) -> b - a);
Collections.sort(personList, (p1, p2) -> p2.age - p1.age);
5. Set
Stack<Integer> st = new Stack<>();
st.push(1);
st.pop();
st.peek();
6. Queue and Deque
// -----------------Queue-----------------
Queue<Integer> q = new LinkedList<>();
q.add(1);
q.remove();
q.peek();
// Without exception
q.offer(2);
q.poll()
// -----------------Deque-----------------
Deque<Integer> dq = new LinkedList<>();
dq.addFirst(1);
dq.addLast(2);
int f1 = dq.getFirst();
int l1 = dq.getLast();
int f2 = dq.removeFirst();
int l2 = dq.removeLast();
7. PriorityQueue
// Basics
PriorityQueue<Integer> pq = new PriorityQueue<>();
PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Comparator.reverseOrder());
// Add/Offer
pq.add(5);
// Remove/Poll
Integer item = pq.remove();
// Return without removing
Integer item = pq.peek();
// -----------------Inefficient-----------------
// Contains
boolean exists = pq.contains(5);
// Remove specific object
pq.remove(5);
//--------------Custom comparators--------------------
// Max heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
// Based on string length
PriorityQueue<String> strPQByLength = new PriorityQueue<>((s1, s2) -> s2.length() - s1.length());
// Lexicographical Order
PriorityQueue<String> strPQLexi = new PriorityQueue<>();
// Reverse Lexicographical Order
PriorityQueue<String> strPQLexiDesc = new PriorityQueue<>(Comparator.reverseOrder());
// ----------------Custom Objects------------------
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Based on age in descending order
PriorityQueue<Person> personPQ = new PriorityQueue<>((p1, p2) -> p2.age - p1.age);
Visualization helper methods
I have created few helper methods to visualize a data structure during an algorithm.
1. Two pointers
- int[] : Integer Array
private void tpi(int[] s, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
for (int i = 0; i < s.length; i++) {
if (i == l && i == r) {
System.out.printf("[(%s)]", s[i]);
} else if (i == l) {
System.out.printf("(%s)", s[i]);
} else if (i == r) {
System.out.printf("[%s]", s[i]);
} else {
System.out.print(s[i]);
}
System.out.print(" ");
}
System.out.printf("| l=%s, r=%s %n", l, r);
}
- char[] : Character Array
// Two pointer char array
private void tpc(char[] s, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
for (int i = 0; i < s.length; i++) {
if (i == l && i == r) {
System.out.printf("[(%s)]", s[i]);
} else if (i == l) {
System.out.printf("(%s)", s[i]);
} else if (i == r) {
System.out.printf("[%s]", s[i]);
} else {
System.out.print(s[i]);
}
System.out.print(" ");
}
System.out.printf("| l=%s, r=%s %n", l, r);
}
- String : String
// Two pointer string
private void tps(String s, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
for (int i = 0; i < s.length(); i++) {
if (i == l && i == r) {
System.out.printf("[(%s)]", s.charAt(i));
} else if (i == l) {
System.out.printf("(%s)", s.charAt(i));
} else if (i == r) {
System.out.printf("[%s]", s.charAt(i));
} else {
System.out.print(s.charAt(i));
}
System.out.print(" ");
}
System.out.printf("| l=%s, r=%s %n", l, r);
}
2. Sliding Window
- int[] : Integer Array
// Sliding window int array
private void swi(int[] nums, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
for (int i = 0; i < nums.length; i++) {
if (i == l) {
System.out.print("[");
}
System.out.print(nums[i]);
if (i == r) {
System.out.print("]");
}
System.out.print(" ");
}
System.out.printf("| l=%s, r=%s %n", l, r);
}
- char[] : Character Array
// Sliding window char array
private void swi(char[] chars, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
for (int i = 0; i < chars.length; i++) {
if (i == l) {
System.out.print("[");
}
System.out.print(chars[i]);
if (i == r) {
System.out.print("]");
}
System.out.print(" ");
}
System.out.printf("| l=%s, r=%s %n", l, r);
}
- String : String
// Sliding window string
private void sws(String s, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
for (int i = 0; i < s.length(); i++) {
if (i == l) {
System.out.print("[");
}
System.out.print(s.charAt(i));
if (i == r) {
System.out.print("]");
}
System.out.print(" ");
}
System.out.printf("| l=%s, r=%s %n", l, r);
}
3. Binary Search
// Print binary search
private void pbs(int[] a, int m, int l, int r, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
System.out.printf("L: %s, M: %s, R: %s | ", l, m, r);
for (int i = 0; i < a.length; i++) {
if (i == m) {
if (m == l && m == r) {
System.out.printf("[({%s})]", a[i]);
} else if (m == l) {
System.out.printf("({%s})", a[i]);
} else if (m == r) {
System.out.printf("[{%s}]", a[i]);
} else {
System.out.printf("{%s}", a[i]);
}
} else if (i == l && i == r) {
System.out.printf("[(%s)]", a[i]);
} else if (i == l) {
System.out.printf("(%s)", a[i]);
} else if (i == r) {
System.out.printf("[%s]", a[i]);
} else {
System.out.print(a[i]);
}
System.out.print(" ");
}
System.out.println();
}
4. Two dimension Array
- int[][] : Integer Array
// Two dimension integer
private void tdi(int[][] a) {
for (int[] row : a) {
System.out.println(Arrays.toString(row));
}
System.out.println("---");
}
- char[][] : Character Array
// Two dimension char
private void tdc(char[][] a) {
for (char[] row : a) {
System.out.println(Arrays.toString(row));
}
System.out.println("---");
}
- String[][] : String
// Two dimension String
private void tds(String[][] a) {
for (String[] row : a) {
System.out.println(Arrays.toString(row));
}
System.out.println("---");
}
5. Print Linked list
// Print linked list
private void pll(ListNode head, String... prefix) {
if (prefix.length == 0) {
prefix = new String[] { "" };
}
System.out.print(prefix[0]);
int size = 0;
ListNode curr = head;
while (curr != null) {
size++;
curr = curr.next;
}
curr = head;
int i = 0;
while (curr != null) {
if (i == size / 2) {
System.out.printf("[%s] -> ", curr.val);
} else {
System.out.printf("%s -> ", curr.val);
}
curr = curr.next;
i++;
}
System.out.print("null\n");
}
6. Print Binary Tree
// Print binary tree
private void pbt(final TreeNode node) {
String result = ppt(node, new StringBuilder(), true, new StringBuilder());
System.out.println(result);
}
private String pbtUtil(TreeNode node, StringBuilder prefix, boolean isTail, StringBuilder sb) {
if (node.right != null) {
pbtUtil(node.right, new StringBuilder().append(prefix).append(isTail ? "│ " : " "), false,
sb);
}
sb.append(prefix).append(isTail ? "└── " : "┌── ").append(node.val).append("\n");
if (node.left != null) {
pbtUtil(node.left, new StringBuilder().append(prefix).append(isTail ? " " : "│ "), true, sb);
}
return sb.toString();
}
Top comments (0)