LeetCode Problem: Top Interview Questions
LeetCode Problem: Top Interview Questions
1. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[]
. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. For example:
1 | Example 1: |
To solve the problem, we need to use two pointers, the process is like this:
Here is the code of reverse string:
1 | public class ReverseString { |
2. Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one. For example:
1 | Example 1: |
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Using HashSet
The first way is to use HashSet
, which uses hash table to implement set
. The reason why we use HashSet is that, for the HashSet, the add and remove operations are all in O(1)
. When we use for
loop, the time complexity is O(n)
in total. However, using HashSet
takes extra memory. Take [2, 2, 1, 3, 3]
as an example, the process is like this:
- We add the 1st element
2
into the set. - The 2nd element is
2
, as2
is already in the set, we remove2
from the set. - We add the 3rd element
1
into the set. - We add the 4th element
3
into the set. - The 5th element is
3
, as3
is already in the set, we remove3
from the set. - After traversing
[2, 2, 1, 3, 3]
, there is only1
in the set, which is the single number.
The code is like this:
1 | import java.util.HashSet; |
Using Bit Manipulation
A more clever way is to use Bitwise XOR
, we know that:
Take [2, 2, 1, 3, 3]
as an example:
1 XOR 2 XOR 2 = 1
, 1 XOR 3 XOR 3 = 1
, and then 1 XOR 0 = 1
, therefore our final result is 1, which is the single number. Here is the code:
1 | public class SingleNumber { |
By the way, we can also use Bitwise AND
(&
) to check whether a number is odd or even:
1 | if (a & 1 == 1) { |
3. Move Zeros
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
1 | Example: |
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
This problem is easy to solve:
1 | public class MoveZeros { |
4. Power of Two
Given an integer, write a function to determine if it is a power of two. Here is the code:
1 | public boolean isPowerOfTwo(int n) { |
5. Majority Element
The easiest way to solve the problem is like this:
1 | public int majorityElement(int[] nums) { |
The common way of solving this problem is using HashMap
:
1 | import java.util.HashMap; |
6. Roman to Integer
To solve this problem, we need to traverse the input string backward. And there are two cases, addition
or subtraction
.
For example, if our input string is VI
, and at the beginning our result is 0
. We traverse I
first, and do the addition, our result becomes 0 + 1 = 1
. Then we traverse V
, as V
is larger than I
, we do the addition again, and our result becomes 1 + 5 = 6
.
If our input string is IV
, at the beginning our result is 0
. We traverse V
first, and do the addition, our result becomes 0 + 5 = 5
. Then we traverse I
, as I
is less than V
, we do the subtraction, and our result becomes 5 - 1 = 4
.
Here is the code to solve the problem:
1 | import java.util.HashMap; |
7. Count Primes
Count the number of prime numbers less than a non-negative number, n.
1 | Example: |
For this problem, if we use brute force, it would be in O(n^2)
. And the following code is a little efficient, which is in O(n^1.5)
:
1 | public class CountPrimes { |
However, the above code is still too slow. A more efficient way is to use an algorithm called Sieve of Eratoshenes
, which is in O(nloglogn)
.
As shown, the idea of Sieve of Eratoshenes
is like this:
For the first prime
2
, we rule out all its multiples, e.g.,2+2=4
, so we rule out4
;4+2=6
, so we rule out6
;6+2=8
, so we rule out8
…For the second prime
3
, we rule out all its multiples, e.g.,3+3=6
, so we rule out6
;6+3=9
, so we rule out9
;9+3=12
, so we rule out12
…For the third prime
5
, we rule out all its multiples, e.g.,5+5=10
, so we rule out10
;10+5=15
, so we rule out15
;15+5=20
, so we rule out20
…For the third prime
7
, we rule out all its multiples, e.g.,7+7=14
, so we rule out14
;14+7=21
, so we rule out21
;21+7=28
, so we rule out28
…Then, all the left numbers, including 2, 3, 5, 7, are prime numbers.
Given a number N
, if we want to find all the primes in range[2,N]
, all we need to do is:
- Find out all the primes in
range[2,sqrt(N)]
. - For each prime in
range[2,sqrt(N)]
, rule out its multiples.
Here is the code to implement this algorithm:
1 | public class CountPrimes { |
8. Sqrt(x)
Implement int sqrt(int x)
. Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
1 | Example 1: |
Note that we only consider the square root of integers(i.e., 1, 2, 3, …). The first method is brute force:
1 | public int mySqrt(int x) { |
A more efficient way is to use binary search
:
1 | public int mySqrt(int x) { |
The process of the above code is like this: https://www.youtube.com/watch?v=hBAz_bDvWGk
9. Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n)
complexity.
1 | Example: |
As our algorithm should be in O(n)
, we can use hashtable
to solve the problem:
1 | import java.util.HashSet; |
The process of the above code is like this: https://www.youtube.com/watch?v=iBcS_PBJTDE
10. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i
. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.
1 | Example 1: |
Here is the code to solve the problem:
1 | public class BestTime { |
day | 0 | 1 | 2 | 3 | 4 | 5 |
price | 7 | 1 | 5 | 3 | 6 | 4 |
If we are on day i
, we can ask ourselves:
What is the maximum profit I can make today?
Firstly, we should check what is the minimum value before this day, then we subtract the minimum value using today’s price to get the maximum profit on day i
. That’s why we should keep updating our min
.
We can make our code more efficient:
1 | public class BestTime { |
11.LeetCode Problem: Pascal’s Triangle
In Pascal’s triangle, each number is the sum of the two numbers directly above it:
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle. For example, if numRows = 5
, we get the following result:
1 | [ |
We can firstly observe the above result. We can easily find the following pattern for a particular row i
:
- There are always
i
elements in rowi
. - The first element and the last element are always
1
. - The
j
th element in rowi
is the sum ofj-1
th element andj
th element in rowi-1
.
For example, for row 4
(i.e., [1,3,3,1]
), we can find that:
- There are 4 elements in total.
- The first element and the last element are
1
. - The 2nd element
3
is the sum of the 1st and 2nd element in row3
, namely,3 = 1 + 2
.
Here is the code to solve the pascal’s triangle problem:
1 | import java.util.ArrayList; |
12. Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid. An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
1 | Example 1: |
We can use a stack
to solve this problem:
1 | public class ValidParentheses { |
13. Counting Bits
Given a non negative integer number num
. For every numbers i
in the range 0 ≤ i ≤ num
calculate the number of 1’s in their binary representation and return them as an array.
1 | Example 1: |
Here is the code to solve this problem:
1 | public class CountingBits { |
Here is the explanation of the above code:
Given an even number, say 8
, which is 1000
in binary, if we divide 8
by 2
, all digits need to shift one place to the right:
1 | 8/2 ==> 4 |
As shown, since the last digit of an even number is always 0
, the number of 1’s in 8
is same as the number of 1’s in 8/2
.
Given an odd number, say 7
, which is 0111
in binary, if we divide 7
by 2
, all digits need to shift one place to the right:
1 | 7/2 ==> 3 |
As shown, since the last digit of an odd number is always 1
, the number of 1’s in 7
is one more than the number of 1’s in 7/2
.
14. Queue Reconstruction By Height
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k)
, where h
is the height of the person and k
is the number of people in front of this person who have a height greater than or equal to h
. Write an algorithm to reconstruct the queue. For example:
1 | Input: |
Here is the code to solve this problem:
1 | import java.util.*; |
The idea of the above code is shown in the following video: https://www.youtube.com/watch?v=z4FdQNfpyuM
15. Daily Tempretures
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73]
, your output should be [1, 1, 4, 2, 1, 1, 0, 0]
.
An efficient way to solve this problem is to use stack
:
1 | public class Solution { |
And here is a good video explanation: https://www.youtube.com/watch?v=WGm4Kj3lhRI