LeetCode – Minimum Window Substring (Java)

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = “ADOBECODEBANC”, T = “ABC”, Minimum window is “BANC”. Java Solution public String minWindow(String s, String t) { HashMap<Character, Integer> goal = new HashMap<>(); int goalSize = … Read more

LeetCode – Divide Two Integers (Java)

Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. Analysis This problem can be solved based on the fact that any number can be converted to the format of the following: num=a_0*2^0+a_1*2^1+a_2*2^2+…+a_n*2^n The time complexity is O(logn). Java Solution public int divide(int dividend, int divisor) { //handle special … Read more

LeetCode – Length of Last Word (Java)

Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word in the string. If the last word does not exist, return 0. Java Solution We can scan the string from the end. When there is a letter, start counting the number of letters. This should … Read more

LeetCode – Add Binary (Java)

Given two binary strings, return their sum (also a binary string). For example, a = “11”, b = “1”, the return is “100”. Java Solution Very simple, nothing special. Note how to convert a character to an int. public String addBinary(String a, String b) { if(a==null || a.length()==0) return b; if(b==null || b.length()==0) return a; … Read more

Merge K Sorted Arrays in Java

This is a classic interview question. Another similar problem is “merge k sorted lists“. This problem can be solved by using a heap. The time complexity is O(nlog(k)), where n is the total number of elements and k is the number of arrays. It takes O(log(k)) to insert an element to the heap and it … Read more

LeetCode – Remove Nth Node From End of List (Java)

Given a linked list, remove the nth node from the end of list and return its head. For example, given linked list 1->2->3->4->5 and n = 2, the result is 1->2->3->5. Java Solution 1 – Naive Two Passes Calculate the length first, and then remove the nth from the beginning. public ListNode removeNthFromEnd(ListNode head, int … Read more

LeetCode – Add and Search Word – Data structure design (Java)

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. Java Solution 1 This problem is similar with Implement Trie. The solution 1 below uses … Read more