Leet Codes Top 150 Interview Solutions
Leet Codes Top 150 Interview Solutions
public RandomizedSet() {
nums = new ArrayList<>();
valToIndex = new HashMap<>();
rand = new Random();
}
public boolean insert(int val) {
if (valToIndex.containsKey(val))
return false;
nums.add(val);
valToIndex.put(val, nums.size() - 1);
return true;
}
public boolean remove(int val) {
if (!valToIndex.containsKey(val))
return false;
int index = valToIndex.get(val);
if (index < nums.size() - 1) {
int lastVal = nums.get(nums.size() - 1);
nums.set(index, lastVal);
valToIndex.put(lastVal, index);
}
nums.remove(nums.size() - 1);
valToIndex.remove(val);
return true;
}
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}
13) (Q.238) https://leetcode.com/problems/product-of-array-except-self/submissions/1188367284?
envType=study-plan-v2&envId=top-interview-150
class Solution {
public int[] productExceptSelf(int[] nums)
{
int n = nums.length;
int[] answer = new int[n];
int l = 1;
for (int i = 0; i < n; i++)
{
answer[i] = l;
l *= nums[i];
}
int r = 1;
for (int i = n - 1; i >= 0; i--)
{
answer[i] *= r;
r*= nums[i];
}
return answer;
}
}
14)(Q.134) https://leetcode.com/problems/gas-station/submissions/1188377330?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public int canCompleteCircuit(int[] gas, int[] cost)
{
int pos = -1;
int curr = 0;
int total = 0;
if(curr<0)
{
curr=0;
pos=i;
}
}
if(total>=0)
return pos+1;
return -1;
}
}
15)(Q.135) https://leetcode.com/problems/candy/submissions/1188382899?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public int candy(int[] ratings)
{
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1);
for (int i = 1; i < n; i++)
{
if (ratings[i] > ratings[i - 1])
{
candies[i] = candies[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--)
{
if (ratings[i] > ratings[i + 1])
{
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
int totalCandies = 0;
for (int candy : candies)
{
totalCandies += candy;
}
return totalCandies;
}
}
16) (Q.42) https://leetcode.com/problems/trapping-rain-water/submissions/1188392635?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public int trap(int[] height)
{
int n = height.length;
int l = 0, r = n - 1;
int lM = 0, rM = 0;
int Water = 0;
while (l < r)
{
lM = Math.max(lM, height[l]);
rM = Math.max(rM, height[r]);
if (height[l] < height[r])
{
Water += lM - height[l];
l++;
}
else
{
Water += rM - height[r];
r--;
}
}
return Water;
}
}
17) (Q.13) https://leetcode.com/problems/roman-to-integer/submissions/1188445860?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public int romanToInt(String s)
{
int ans = 0, num = 0;
for (int i = s.length()-1; i >= 0; i--)
{
switch(s.charAt(i))
{
case 'I': num = 1; break;
case 'V': num = 5; break;
case 'X': num = 10; break;
case 'L': num = 50; break;
case 'C': num = 100; break;
case 'D': num = 500; break;
case 'M': num = 1000; break;
}
if (4 * num < ans)
ans -= num;
else
ans += num;
}
return ans;
}
}
18) (Q.12) https://leetcode.com/problems/integer-to-roman/submissions/1188450440?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public String intToRoman(int num)
{
StringBuilder ans = new StringBuilder();
}
}
22) (Q.06) https://leetcode.com/problems/zigzag-conversion/submissions/1188556552?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public String convert(String s, int numRows) {
int length = s.length();
sb.append(words[i]);
for (int k = i + 1; k < j; k++)
{
sb.append(" ".repeat(numOfGuaranteedSpaces + 1));
if (spacesLeft > 0)
{
sb.append(" ");
spacesLeft--;
}
sb.append(words[k]);
}
sb.append(" ".repeat(spacesLeft));
}
else
{
sb.append(words[i]);
for (int k = i + 1; k < words.length; k++)
sb.append(" ").append(words[k]);
sb.append(" ".repeat(maxWidth - sum));
}
list.add(sb.toString());
i = j;
}
return list;
}
}
25) (Q.125) https://leetcode.com/problems/valid-palindrome/submissions/1189311826?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public boolean isPalindrome(String s)
{
int left = 0;
int right = s.length() - 1;
while (left <= right)
{
char a = s.charAt(left);
char b = s.charAt(right);
if (!('A' <= a && a <= 'Z') && !('a' <= a && a <= 'z') && !('0' <= a && a <= '9'))
{
left++;
continue;
}
if (!('A' <= b && b <= 'Z') && !('a' <= b && b <= 'z') && !('0' <= b && b <= '9'))
{
right--;
continue;
}
if (a <='Z')
{
a += 'a'-'A';
}
if (b <= 'Z')
{
b += 'a'-'A';
}
if (a != b)
{
return false;
}
left++;
right--;
}
return true;
}
}
26) (Q.392) https://leetcode.com/problems/is-subsequence/submissions/1189317296?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public boolean isSubsequence(String s, String t)
{
int i=0,j=0;
int n=t.length();
int m=s.length();
char ss[]=s.toCharArray();
char tt[]=t.toCharArray();
if(m<1)
return true;
while(i<n)
{
if(tt[i]==ss[j])
{
j++;
}
i++;
if(j==m)
return true;
}
return false;
}
}
27) (Q.167) https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/submissions/1189325136?
envType=study-plan-v2&envId=top-interview-150
class Solution
{
public int[] twoSum(int[] numbers, int target)
{
int left = 0;
int right = numbers.length - 1;
int ans[]=new int[2];
while (left < right)
{
int sum = numbers[left] + numbers[right];
if (sum == target)
{
ans[0] = left+1;
ans[1] = right+1;
return ans;
}
else if(sum<target)
{
left++;
}
else
{
right--;
}
}
return ans;
}
}
28) (Q.11) https://leetcode.com/problems/container-with-most-water/submissions/1189336924?
envType=study-plan-v2&envId=top-interview-150
class Solution
{
public int maxArea(int[] height)
{
int l = 0, r = height.length-1;
int res = 0;
while (l < r)
{
int h = Math.min(height[l], height[r]);
res = Math.max(res, h * (r-l));
while (l < r && height[l] <= h)
{
l++;
}
while (l < r && height[r] <= h)
{
r--;
}
}
return res;
}
}
29) (Q. 15) https://leetcode.com/problems/3sum/submissions/1189341715?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public List<List<Integer>> threeSum(int[] nums)
{
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++)
{
if (i == 0 || (i > 0 && nums[i] != nums[i - 1]))
{
int left = i + 1, right = nums.length - 1, target = -nums[i];
while (left < right)
{
if (nums[left] + nums[right] == target)
{
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1])
left++;
while (left < right && nums[right] == nums[right - 1])
right--;
left++;
right--;
}
else if (nums[left] + nums[right] < target)
{
left++;
}
else
{
right--;
}
}
}
}
return result;
}
}
30) (Q.209) https://leetcode.com/problems/minimum-size-subarray-sum/submissions/1191525673?
envType=study-plan-v2&envId=top-interview-150
class Solution
{
public int minSubArrayLen(int target, int[] nums)
{
int sum = 0;
int a = 0;
while (a < nums.length)
{
sum += nums[a];
a++;
if (sum >= target)
{
break;
}
}
if (sum < target)
{
return 0;
}
int b = 1;
while (a + b - 1 < nums.length)
{
sum -= nums[b - 1];
sum += nums[a + b - 1];
if (sum >= target)
{
while (sum >= target)
{
sum -= nums[a + b - 1];
if (sum >= target)
{
a--;
}
}
sum += nums[a + b - 1];
}
b++;
}
while (sum >= target)
{
sum -= nums[nums.length - a];
if (sum >= target)
{
a--;
}
}
return a;
}
}
31) (Q.03) https://leetcode.com/problems/longest-substring-without-repeating-characters/submissions/
1191544675?envType=study-plan-v2&envId=top-interview-150
class Solution
{
public int lengthOfLongestSubstring(String ss)
{
int len = 0;
int s = 0;
int e = 0;
while (e < ss.length())
{
char c = ss.charAt(e);
for(int i = s; i < e; i++)
{
if(ss.charAt(i) == c)
{
s = i+1;
break;
}
}
len = Math.max(len, e-s+1);
e++;
}
return len;
}
}
32) (Q.30) https://leetcode.com/problems/substring-with-concatenation-of-all-words/submissions/
1191548840?envType=study-plan-v2&envId=top-interview-150
class Solution
{
public List<Integer> findSubstring(String s, String[] words)
{
List<Integer> result = new ArrayList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) {
return result;
}
int wordLength = words[0].length();
int totalWords = words.length;
int concatLength = wordLength * totalWords;
Map<String, Integer> wordCountMap = new HashMap<>();
for (String word : words) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
for (int i = 0; i <= s.length() - concatLength; i++) {
Map<String, Integer> seen = new HashMap<>();
int j = 0;
while (j < totalWords) {
String word = s.substring(i + j * wordLength, i + (j + 1) * wordLength);
if (!wordCountMap.containsKey(word)) {
break;
}
seen.put(word, seen.getOrDefault(word, 0) + 1);
if (seen.get(word) > wordCountMap.getOrDefault(word, 0)) {
break;
}
j++;
}
if (j == totalWords) {
result.add(i);
}
}
return result;
}
}
33) (Q.76) https://leetcode.com/problems/minimum-window-substring/submissions/1191551132?
envType=study-plan-v2&envId=top-interview-150
class Solution
{
public String minWindow(String s, String t)
{
int[] map = new int[128];
int tLen = t.length(), sLen = s.length();
int left = 0, right = 0, count = t.length(), gap = Integer.MAX_VALUE;
int start = 0;
for (char ch : t.toCharArray())
{
map[ch]++;
}
char[] ch = s.toCharArray();
while (right < sLen)
{
if (map[ch[right++]]-- > 0)
{
count--;
}
while (count == 0)
{
if (gap > right - left)
{
gap = right - left;
start = left;
}
if (map[ch[left++]]++ == 0)
{
count++;
}
}
}
return gap == Integer.MAX_VALUE ? "" : new String(ch, start, gap);
}
}
34) (Q.36) https://leetcode.com/problems/valid-sudoku/submissions/1191554179?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public boolean isValidSudoku(char[][] board)
{
int line[][] = new int[9][9];
int col[][] = new int[9][9];
int square[][] = new int[9][9];
for(int i = 0; i < 9 ; i++)
{
for(int j = 0; j < 9; j++)
if(board[i][j] != '.')
{
int pos = board[i][j] - '0' - 1;
int pos_square = (i/3) + (j / 3)*3;
if(++line[i][pos] > 1 || ++col[j][pos] > 1 || ++square[pos_square][pos] > 1)return false;
}
}
return true;
}
}
35) (Q.54) https://leetcode.com/problems/spiral-matrix/submissions/1191557890?envType=study-plan-
v2&envId=top-interview-150
import java.util.*;
return true;
}
private int find(int x) {
return parent[x] == x ? x : (parent[x] = find(parent[x]));
}
private void union(int x, int y) {
x = find(x);
y = find(y);
if (x == y)
return;
parent[y] = x;
}
}
2)(Q.100) https://leetcode.com/problems/same-tree/submissions/1186811561?envType=daily-
question&envId=2024-02-26
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
*}
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q)
{
if (p == null && q == null)
return true;
if (p == null || q == null)
return false;
if (p.val != q.val)
return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
3) (Q.513) https://leetcode.com/problems/find-bottom-left-tree-value/submissions/1188545335?
envType=daily-question&envId=2024-02-28
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
*}
*/
class Solution {
int leftmost = 0;
int leftmostrow = -1;
void visit(TreeNode root, int depth) {
if (root == null) return;
if (depth > leftmostrow) {
leftmost = root.val;
leftmostrow = depth;
}
visit(root.left, depth+1);
visit(root.right, depth+1);
}
public int findBottomLeftValue(TreeNode root) {
visit(root, 0) ;
return leftmost;
}
}
In this all the methods by default public and abstract
To use interfaces in he class we use implement keyword