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 – Tic-Tac-Toe (Java)

Design a Tic-tac-toe game that is played between two players on a n x n grid. Java Solution 1 – Naive We can simply check the row, column and the diagonals and see if there is a winner. public class TicTacToe {   int[][] matrix;   /** Initialize your data structure here. */ public TicTacToe(int … Read more

LeetCode – Walls and Gates (Java)

Java Solution 1 – DFS public void wallsAndGates(int[][] rooms) { if(rooms==null || rooms.length==0||rooms[0].length==0) return;   int m = rooms.length; int n = rooms[0].length;   boolean[][] visited = new boolean[m][n];   for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(rooms[i][j]==0){ fill(rooms, i-1, j, 0, visited); fill(rooms, i, j+1, 0, visited); fill(rooms, i+1, j, 0, visited); fill(rooms, … Read more

LeetCode – Serialize and Deserialize Binary Tree (Java)

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Java Solution 1 – Level Order Traveral // … 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