Docsity

Java Algorithm and Data Structure Solutions, Study notes of Java Programming

Partial preview of the text

Download Java Algorithm and Data Structure Solutions and more Study notes Java Programming in PDF only on Docsity!

Coding Interview in

Java

Program Creek

May 1 st, 2016

Contents

1 Rotate Array in Java

You may have been using Java for a while. Do you think a simple Java array question

can be a challenge? Let’s use the following problem to test.

Problem: Rotate an array of n elements to the right by k steps. For example, with n

= 7 and k = 3 , the array [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] is rotated to [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ]. How many different

ways do you know to solve this problem?

1.1 Solution 1 - Intermediate Array

In a straightforward way, we can create a new array and then copy elements to the

new array. Then change the original array by using System.arraycopy().

public void rotate(int[] nums, int k) { if(k > nums.length) k=k%nums.length;

int[] result = new int[nums.length];

for(int i=0; i < k; i++){ result[i] = nums[nums.length-k+i]; }

int j=0; for(int i=k; i<nums.length; i++){ result[i] = nums[j]; j++; }

System.arraycopy( result, 0, nums, 0, nums.length ); }

Space is O(n) and time is O(n). You can check out the difference between Sys-

tem.arraycopy() and Arrays.copyOf().

1.2 Solution 2 - Bubble Rotate

Can we do this in O( 1 ) space?

This solution is like a bubble sort.

public static void rotate(int[] arr, int order) { if (arr == null || order < 0) {

1 Rotate Array in Java

throw new IllegalArgumentException("Illegal argument!"); }

for (int i = 0; i < order; i++) { for (int j = arr.length - 1; j > 0; j--) { int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } } }

However, the time is O(n*k).

Here is an example (length= 7 , order= 3 ):

i= 0 1 2 3 4 5 6 0 1 2 3 4 6 5 ... 6 0 1 2 3 4 5 i= 6 0 1 2 3 5 4 ... 5 6 0 1 2 3 4 i= 5 6 0 1 2 4 3 ... 4 5 6 0 1 2 3

1.3 Solution 3 - Reversal

Can we do this in O( 1 ) space and in O(n) time? The following solution does.

Assuming we are given 1 , 2 , 3 , 4 , 5 , 6 and order 2. The basic idea is:

  1. Divide the array two parts: 1,2,3,4 and 5, 6
  2. Reverse first part: 4,3,2,1,5,
  3. Reverse second part: 4,3,2,1,6,
  4. Reverse the whole array: 5,6,1,2,3,

public static void rotate(int[] arr, int order) { if (arr == null || arr.length==0 || order < 0) { throw new IllegalArgumentException("Illegal argument!"); }

if(order > arr.length){ order = order %arr.length; }

14 | 531 Program Creek

2 Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid op-

erators are +, -, *, /. Each operand may be an integer or another expression. For

example:

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

2.1 Naive Approach

This problem can be solved by using a stack. We can loop through each element in the

given array. When it is a number, push it to the stack. When it is an operator, pop two

numbers from the stack, do the calculation, and push back the result.

The following is the code. However, this code contains compilation errors in leet-

code. Why?

public class Test {

public static void main(String[] args) throws IOException { String[] tokens = new String[] { "2", "1", "+", "3", "*" }; System.out.println(evalRPN(tokens)); }

2 Evaluate Reverse Polish Notation

public static int evalRPN(String[] tokens) { int returnValue = 0; String operators = "+-*/";

Stack stack = new Stack();

for (String t : tokens) { if (!operators.contains(t)) { //push to stack if it is a number stack.push(t); } else {//pop numbers from stack if it is an operator int a = Integer.valueOf(stack.pop()); int b = Integer.valueOf(stack.pop()); switch (t) { case "+": stack.push(String.valueOf(a + b)); break; case "-": stack.push(String.valueOf(b - a)); break; case "*": stack.push(String.valueOf(a (^) * b)); break; case "/": stack.push(String.valueOf(b / a)); break; } } }

returnValue = Integer.valueOf(stack.pop());

return returnValue; } }

The problem is that switch string statement is only available from JDK 1. 7. Leetcode

apparently use a JDK version below 1. 7.

2.2 Accepted Solution

If you want to use switch statement, you can convert the above by using the following

code which use the index of a string "+-*/".

public class Solution { public int evalRPN(String[] tokens) {

int returnValue = 0;

18 | 531 Program Creek

3 Isomorphic Strings

Given two strings s and t, determine if they are isomorphic. Two strings are isomor-

phic if the characters in s can be replaced to get t.

For example,"egg" and "add" are isomorphic, "foo" and "bar" are not.

3.1 Analysis

We need to define a method which accepts a map & a value, and returns the value’s

key in the map.

3.2 Java Solution

public boolean isIsomorphic(String s, String t) { if(s==null || t==null) return false;

if(s.length() != t.length()) return false;

if(s.length()==0 && t.length()==0) return true;

HashMap<Character, Character> map = new HashMap<Character,Character>(); for(int i=0; i<s.length(); i++){ char c1 = s.charAt(i); char c2 = t.charAt(i);

Character c = getKey(map, c2); if(c != null && c!=c1){ return false; }else if(map.containsKey(c1)){ if(c2 != map.get(c1)) return false; }else{ map.put(c1,c2); } }

return true; }

3 Isomorphic Strings

// a method for getting key of a target value public Character getKey(HashMap<Character,Character> map, Character target){ for (Map.Entry<Character,Character> entry : map.entrySet()) { if (entry.getValue().equals(target)) { return entry.getKey(); } }

return null; }

22 | 531 Program Creek

4 Word Ladder

public class Solution { public int ladderLength(String beginWord, String endWord, Set wordDict) { LinkedList queue = new LinkedList(); queue.add(new WordNode(beginWord, 1));

wordDict.add(endWord);

while(!queue.isEmpty()){ WordNode top = queue.remove(); String word = top.word;

if(word.equals(endWord)){ return top.numSteps; }

char[] arr = word.toCharArray(); for(int i=0; i<arr.length; i++){ for(char c=’a’; c<=’z’; c++){ char temp = arr[i]; if(arr[i]!=c){ arr[i]=c; }

String newWord = new String(arr); if(wordDict.contains(newWord)){ queue.add(new WordNode(newWord, top.numSteps+1)); wordDict.remove(newWord); }

arr[i]=temp; } } }

return 0; } }

24 | 531 Program Creek

5 Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation

sequence(s) from start to end, such that: 1 ) Only one letter can be changed at a time,

2 ) Each intermediate word must exist in the dictionary.

For example, given: start = "hit", end = "cog", and dict = ["hot","dot","dog","lot","log"],

return:

[

["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]

5.1 Analysis

This is an extension of Word Ladder.

The idea is the same. To track the actual ladder, we need to add a pointer that points

to the previous node in the WordNode class.

In addition, the used word can not directly removed from the dictionary. The used

word is only removed when steps change.

5.2 Java Solution

class WordNode{ String word; int numSteps; WordNode pre;

public WordNode(String word, int numSteps, WordNode pre){ this.word = word; this.numSteps = numSteps; this.pre = pre; } }

public class Solution { public List<List> findLadders(String start, String end, Set dict) { List<List> result = new ArrayList<List>();

5 Word Ladder II

String newWord = new String(arr); if(unvisited.contains(newWord)){ queue.add(new WordNode(newWord, top.numSteps+1, top)); visited.add(newWord); }

arr[i]=temp; } }

return result; } }

Program Creek 27 | 531

6 Median of Two Sorted Arrays

There are two sorted arrays A and B of size m and n respectively. Find the median of the

two sorted arrays. The overall run time complexity should be O(log (m+n)).

6.1 Java Solution 1

If we see log(n), we should think about using binary something.

This problem can be converted to the problem of finding kth element, k is (A’s

length + B’ Length)/ 2.

If any of the two arrays is empty, then the kth element is the non-empty array’s kth

element. If k == 0 , the kth element is the first element of A or B.

For normal cases(all other cases), we need to move the pointer at the pace of half of

an array length to get log(n) time.

public static double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length;

if ((m + n) % 2 != 0) // odd return (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1); else { // even return (findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1)

  • findKth(A, B, (m + n) / 2 - 1, 0, m - 1, 0, n - 1)) (^) * 0.5; } }

public static int findKth(int A[], int B[], int k, int aStart, int aEnd, int bStart, int bEnd) {

int aLen = aEnd - aStart + 1; int bLen = bEnd - bStart + 1;

// Handle special cases if (aLen == 0) return B[bStart + k]; if (bLen == 0) return A[aStart + k]; if (k == 0) return A[aStart] < B[bStart]? A[aStart] : B[bStart];

int aMid = aLen (^) * k / (aLen + bLen); // a’s middle count int bMid = k - aMid - 1; // b’s middle count