Top Interview 150
1) (Q.88 Array/String) https://leetcode.com/problems/merge-sorted-array/submissions/1185980607?
envType=study-plan-v2&envId=top-interview-150
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1; // Initialize i to the last element of nums1 (even if m is 0)
int j = n - 1;
int k = m + n - 1;
// Iterate backwards, filling nums1 from the end
while (k >= 0) {
if (j >= 0 && (i < 0 || nums2[j] > nums1[i])) {
nums1[k--] = nums2[j--];
} else if (i >= 0) {
nums1[k--] = nums1[i--];
} else {
// Handle the case where nums1 is empty (m is 0)
nums1[k--] = nums2[j--];
}
}
}
}
2) (Q.27) https://leetcode.com/problems/remove-element/submissions/1186375981?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public int removeElement(int[] nums, int val)
{
int k = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] != val)
{
nums[k++] = nums[i];
}
}
return k;
}
}
3) (Q.121) https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/1186446945?
envType=study-plan-v2&envId=top-interview-150
class Solution {
public int maxProfit(int[] prices)
{
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < prices.length; i++)
{
if (prices[i] < minPrice)
{
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit)
{
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}
4) (Q.26) https://leetcode.com/problems/remove-duplicates-from-sorted-array/submissions/1186458395?
envType=study-plan-v2&envId=top-interview-150
class Solution {
public int removeDuplicates(int[] nums)
{
int k = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] != nums[k])
{
nums[++k] = nums[i];
}
}
return k+1;
}
}
5) (Q. 80). https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/submissions/1186769166?
envType=study-plan-v2&envId=top-interview-150
class Solution {
public int removeDuplicates(int[] nums)
{
int n = nums.length;
int count = 1;
int k=1;
for (int i = 1; i < n; i++)
{
if (nums[i] == nums[i - 1])
{
count++;
if (count <= 2)
{
nums[k++] = nums[i];
}
}
else
{
count = 1;
nums[k++] = nums[i];
}
}
return k;
}
}
6) (Q.169). https://leetcode.com/problems/majority-element/submissions/1186774793?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public int majorityElement(int[] nums)
{
int candidate = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++)
{
if (nums[i] == candidate)
{
count++;
}
else
{
count--;
if (count == 0)
{
candidate = nums[i];
count = 1;
}
}
}
count = 0;
for (int num : nums)
{
if (num == candidate)
{
count++;
}
}
return candidate;
}
}
7) (Q.189) https://leetcode.com/problems/rotate-array/submissions/1186786589?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public void rotate(int[] nums, int k)
{
int n = nums.length;
k = k % n;
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}
private void reverse(int[] nums, int start, int end)
{
while (start < end)
{
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
8) Q.122 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/submissions/1186791020?
envType=study-plan-v2&envId=top-interview-150
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
}
9) (Q.55) https://leetcode.com/problems/jump-game/submissions/1186795810?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public boolean canJump(int[] nums)
{
int maxJump = 0;
for (int i = 0; i < nums.length; i++)
{
if (i > maxJump)
{
return false;
}
maxJump = Math.max(maxJump, i + nums[i]);
if (maxJump >= nums.length - 1)
{
return true;
}
}
return false;
} }
10) (Q.45) https://leetcode.com/problems/jump-game-ii/submissions/1186800569?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public int jump(int[] nums) {
int jumps = 0;
int currentJumpEnd = 0;
int farthest = 0;
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == currentJumpEnd) {
jumps++;
currentJumpEnd = farthest;
}
}
return jumps;
}
}
11)(Q.274) https://leetcode.com/problems/h-index/submissions/1187355889?envType=study-plan-
v2&envId=top-interview-150
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
int n = citations.length;
for (int i = 0; i < n; i++) {
int h = n - i;
if (citations[i] >= h) {
return h;
}
}
return 0;
}
}
12) (Q. 380.) https://leetcode.com/problems/insert-delete-getrandom-o1/submissions/1187371040?
envType=study-plan-v2&envId=top-interview-150
class RandomizedSet
{
ArrayList<Integer> nums;
HashMap<Integer, Integer> valToIndex;
Random rand;
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;
for(int i=0; i<gas.length; i++)
{
int diff = gas[i]-cost[i];
curr+=diff;
total+=diff;
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();
while( num > 999 )
{
ans.append('M');
num -= 1000;
}
if( num > 899 )
{
ans.append("CM");
num -= 900;
}
else if( num > 499 )
{
ans.append('D');
num -= 500;
}
else if( num > 399 )
{
ans.append("CD");
num -= 400;
}
while( num > 99 )
{
ans.append('C');
num -= 100;
}
if( num > 89 )
{
ans.append("XC");
num -= 90;
}
else if( num > 49 )
{
ans.append( 'L' );
num -= 50;
}
else if( num > 39 )
{
ans.append("XL");
num -= 40;
}
while( num > 9 )
{
ans.append('X');
num -= 10;
}
if( num > 8 )
{
ans.append("IX");
num -= 9;
}
else if( num > 4 )
{
ans.append('V');
num -= 5;
}
else if( num > 3 )
{
ans.append("IV");
num -= 4;
}
while( num > 0 )
{
ans.append('I');
num -= 1;
}
return ans.toString();
}
}
19) (Q.58) https://leetcode.com/problems/length-of-last-word/submissions/1188453809?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public int lengthOfLastWord(String s)
{
s = s.trim();
int length = 0;
for (int i = s.length() - 1; i >= 0; i--)
{
if (s.charAt(i) == ' ')
{
if (length > 0)
{
break;
}
}
else
{
length++;
}
}
return length;
}
}
20) (Q.14) https://leetcode.com/problems/longest-common-prefix/submissions/1188457545?envType=study-
plan-v2&envId=top-interview-150
class Solution
{
public String longestCommonPrefix(String[] strs)
{
String prefix = strs[0];
for (int i = 1; i < strs.length; i++)
{
while (strs[i].indexOf(prefix) != 0)
{
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty())
{
return "";
}
}
}
return prefix;
}
}
21) (Q.151) https://leetcode.com/problems/reverse-words-in-a-string/submissions/1188548157?
envType=study-plan-v2&envId=top-interview-150
class Solution
{
public String reverseWords(String s)
{
String[] words = s.trim().split("\\s+");
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--)
{
reversed.append(words[i]).append(" ");
}
return reversed.toString().trim();
}
}
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();
if(numRows > length || numRows <= 1){
return s;
}
char[] zigzag = new char[length];
int count=0;
int interval = 2*numRows - 2;
for(int i=0;i<numRows;i++){
int step = interval - 2*i;
for(int j=i;j<length;j+=interval){
zigzag[count] = s.charAt(j);
count++;
if(step>0 && step<interval && j+step<length){
zigzag[count] = s.charAt(j+step);
count++;
}
}
}
return new String(zigzag);
}
}
23) (Q.28) https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/submissions/
1188568214?envType=study-plan-v2&envId=top-interview-150
class Solution
{
public int strStr(String haystack, String needle)
{
return haystack.indexOf(needle);
}
}
24) (Q. 68) https://leetcode.com/problems/text-justification/submissions/1188571995?envType=study-plan-
v2&envId=top-interview-150
class Solution
{
public List<String> fullJustify(String[] words, int maxWidth)
{
List<String> list = new ArrayList<>();
int i = 0;
while (i < words.length)
{
int sum = 0;
int prefixLength = 0;
int j = i;
while (j < words.length && sum + prefixLength + words[j].length() <= maxWidth)
{
sum += prefixLength + words[j].length();
prefixLength = 1;
j++;
}
var sb = new StringBuilder();
if (j != words.length)
{
var numOfAdditionalSpaces = maxWidth - sum;
var numOfGuaranteedSpaces = j > i + 1 ? numOfAdditionalSpaces / (j - i - 1) : 0;
var spacesLeft = numOfAdditionalSpaces - numOfGuaranteedSpaces * (j - i - 1);
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.*;
public class Solution
{
public List<Integer> spiralOrder(int[][] matrix)
{
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
{
return result;
}
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0, right = cols - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom)
{
// Traverse top row
for (int j = left; j <= right; j++)
{
result.add(matrix[top][j]);
}
top++;
// Traverse right column
for (int i = top; i <= bottom; i++)
{
result.add(matrix[i][right]);
}
right--;
// Traverse bottom row
if (top <= bottom)
{
for (int j = right; j >= left; j--)
{
result.add(matrix[bottom][j]);
}
bottom--;
}
// Traverse left column
if (left <= right)
{
for (int i = bottom; i >= top; i--)
{
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
}
EXTRA Problems Daily Problems:
1) (Q.2709) https://leetcode.com/problems/greatest-common-divisor-traversal/submissions/1186365617
class Solution {
int[] parent;
int[] count;
int max;
public boolean canTraverseAllPairs(int[] nums) {
for (int x : nums)
max = Math.max(max, x);
int n = nums.length;
parent = new int[max +1];
count = new int[max+1];
if(n == 1) return true;
for(int i = 0; i < n; i++)
if(nums[i]==1) return false;
for(int i = 1; i <= max; i++)
parent[i] = i;
for(int x:nums)
count[x]++;
boolean[] visited = new boolean[max+1];
for(int i = 2; i* 2 <= max; i++){
if(visited[i]) continue;
for(int j = i+i; j <= max; j+=i){
visited[j] = true;
if(count[j]!=0){
union(i, j);
}
}
}
int p = find(nums[0]);
for(int i = 1; i < n; i++)
if(find(nums[i]) != p) return false;
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