Skip to content

Instantly share code, notes, and snippets.

View shailrshah's full-sized avatar
🖥️
Available

Shail Shah shailrshah

🖥️
Available
View GitHub Profile
@shailrshah
shailrshah / SortMap.java
Last active March 18, 2018 23:32
Sort a Map by value(descending) and then key(ascending)
private static <K extends Comparable<K>, V extends Comparable<V>>Map<K, V> sortMap(Map<K, V> map) {
List<Map.Entry<K, V>> entries = mapToEntries(map);
sortEntries(entries);
return entriesToMap(entries);
}
private static <K extends Comparable<K>, V extends Comparable<V>> List<Map.Entry<K,V>> mapToEntries(Map<K, V> map) {
return new ArrayList<>(map.entrySet());
}
@shailrshah
shailrshah / pointersBasic.c
Created January 25, 2018 14:15
Basics about Pointers
#include <stdio.h>
int main() {
int foo = 1994;
// let pFoo be a pointer that points to an integer variable, whose value is the address of foo
int* pFoo = &foo;
printf("pFoo = &foo = %p = %p\n", pFoo, &foo);
// go to the variable pFoo points to (foo) and get its value. This is called dereferencing pFoo.
@shailrshah
shailrshah / MinRotatedSortedArray.java
Last active November 28, 2017 04:08
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. The array may contain duplicates.
public int findMin(int[] a) {
int l = 0, r = a.length - 1;
while(l < r) {
int m = l + (r - l) / 2;
if(a[l] < a[r]) return a[l];
if(m>=1 && a[m-1] > a[m]) return a[m];
if(a[l] > a[m]) r = m - 1;
else if(a[l] < a[m]) l = m + 1; // or a[m] > a[r]
@shailrshah
shailrshah / DigitRootProblem.java
Created November 17, 2017 23:49
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
//Digit root Problem
//Congruence formula
public int addDigits(int n) {
int b = 10;
if(n == 0) return 0;
else if(n % (b - 1) == 0) return b-1;
else return n % (b - 1);
@shailrshah
shailrshah / Triangles.java
Created November 17, 2017 23:25
Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
// if a > b and a > c, then a < b + c for a triangle to be formed
public int triangleNumber(int[] a) {
int n = a.length;
if(n < 3) return 0;
int count = 0;
Arrays.sort(a);
for(int i = 2; i < n; i++) {
int left = 0, right = i-1;
while(left < right) {
@shailrshah
shailrshah / longestCommonPrefix.java
Created November 14, 2017 21:59
Find the longest common prefix for a given array of strings
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0)
return "";
int minLength = getMinLength(strs);
for(int i = 0; i < minLength; i++) { //For each index
char ch = strs[0].charAt(i);
for(int j = 1; j < strs.length; j++){ // For each string
if(strs[j].charAt(i) != ch)
return strs[0].substring(0, i);
}
@shailrshah
shailrshah / AddLinkedList.java
Created November 14, 2017 16:54
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4…
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) return null;
ListNode help1 = l1, help2 = l2, dummyHead = new ListNode(0), help3 = dummyHead;
int c = 0;
while(help1 != null || help2 != null) {
int a = help1 == null ? 0 : help1.val;
int b = help2 == null ? 0 : help2.val;
int sum = a + b + c;
@shailrshah
shailrshah / BSTIterator.java
Created November 13, 2017 16:01
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
public class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
pushLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
@shailrshah
shailrshah / RegExpMatch.java
Created November 13, 2017 14:37
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).
public boolean isMatch(String str, String pat) {
char[] s = str.toCharArray();
char[] p = pat.toCharArray();
boolean[][] dp = new boolean[s.length+1][p.length+1];
dp[0][0] = true;
for(int j = 1; j < dp[0].length; j++) { // For cases like (a, a*)
if(p[j-1] == '*')
dp[0][j] = dp[0][j-2];
@shailrshah
shailrshah / LRUCache.java
Created November 13, 2017 03:58
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached …
class LRUCache {
int capacity;
Map<Integer, ListNode> map;
ListNode head, tail;
private static class ListNode {
int key, value;
ListNode prev, next;
ListNode(int key, int value) {
this.key = key;