LeetCode – Fraction to Recurring Decimal (Java)

Problem Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, return “0.5”. Given numerator = 2, denominator = 1, return “2”. Given numerator = 2, denominator … Read more

LeetCode – Compare Version Numbers (Java)

Problem Compare two version numbers version1 and version2. If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number ... Read more

LeetCode – Word Break II (Java)

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, given s = “catsanddog”, dict = [“cat”, “cats”, “and”, “sand”, “dog”], the solution is [“cats and dog”, “cat sand dog”]. Java Solution … Read more

LeetCode – Maximum Product Subarray (Java)

Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. Java Solution – Dynamic Programming This is similar to maximum subarray. Instead of sum, the sign of number affect the product value. … Read more

LeetCode – Find Minimum in Rotated Sorted Array II (Java)

Follow up for “Find Minimum in Rotated Sorted Array”: What if duplicates are allowed? Would this affect the run-time complexity? How and why? Java Solution 1 – Recursion This is a follow-up problem of finding minimum element in rotated sorted array without duplicate elements. We only need to add one more condition, which checks if … Read more

LeetCode – Combinations (Java)

Given two integers n and k, return all possible combinations of k numbers out of 1 … n. For example, if n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] Java Solution public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();   if … Read more

LeetCode – Longest Common Prefix (Java)

Problem Write a function to find the longest common prefix string amongst an array of strings. Analysis To solve this problem, we need to find the two loop conditions. One is the length of the shortest string. The other is iteration over every element of the string array. Java Solution public String longestCommonPrefix(String[] strs) { … Read more