LeetCode – Multiply Strings (Java)

Given two numbers represented as strings, return multiplication of the numbers as a string. Analysis The key to solve this problem is multiplying each digit of the numbers at the corresponding positions and get the sum values at each position. That is how we do multiplication manually. Java Solution public String multiply(String num1, String num2) … Read more

LeetCode – Intersection of Two Arrays II (Java)

Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Java Solution 1 public int[] intersect(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i: nums1){ if(map.containsKey(i)){ map.put(i, map.get(i)+1); }else{ map.put(i, 1); } }   ArrayList<Integer> … Read more

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 – 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