LeetCode – Search a 2D Matrix II (Java)

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. For example, consider the following matrix: [ [1, 4, 7, … Read more

How to Check if an Array Contains a Value in Java Efficiently?

How to check if an array (unsorted) contains a certain value? This is a very useful and frequently used operation in Java. It is also a top voted question on Stack Overflow. As shown in top voted answers, this can be done in several different ways, but the time complexity could be very different. In the following I will show the time cost of each method.

Read more

LeetCode – Longest Increasing Subsequence (Java)

Given an unsorted array of integers, find the length of longest increasing subsequence. For example, given [10, 9, 2, 5, 3, 7, 101, 18], the longest increasing subsequence is [2, 3, 7, 101]. Therefore the length is 4. Java Solution 1 – Naive Let max[i] represent the length of the longest increasing subsequence so far. … Read more

LeetCode – Power of Three (Java)

Given an integer, write a function to determine if it is a power of three. Java Solution 1 – Iteration public boolean isPowerOfThree(int n) { if(n==1) return true;   boolean result = false;   while(n>0){ int m = n%3; if(m==0){ n=n/3; if(n==1) return true; }else{ return false; } }   return result; }public boolean isPowerOfThree(int … Read more

LeetCode – Binary Search Tree Iterator (Java)

Problem Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. … Read more

Two Sum III – Data structure design (Java)

Design and implement a TwoSum class. It should support the following operations: add and find. add – Add the number to an internal data structure. find – Find if there exists any pair of numbers which sum is equal to the value. For example, add(1); add(3); add(5); find(4) -> true find(7) -> false Java Solution … Read more

LeetCode – Repeated DNA Sequences (Java)

Problem All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: “ACGAATTCCG”. When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. For example, … Read more