If I were given the option to solve the 5 most important leetcode problems I would solve these 5 problems. I am sharing the list of 5 problems with a solution.
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(' || c=='{' || c=='[' )
stack.push(c);
else if(c==')'){
if(!stack.empty() && stack.peek()=='(') stack.pop();
else return false;
}
else if (c=='}'){
if(!stack.empty() && stack.peek()=='{') stack.pop();
else return false;
}
else if (c==']'){
if(!stack.empty() && stack.peek()=='[') stack.pop();
else return false;
}
}
if(stack.empty()) return true;
return false;
}
}
2. Best Time to buy and sell stock
public int maxProfit(int[] prices) {
// int profit = 0;
// int buyAt = Integer.MAX_VALUE;
// for (int price : prices) {
// if (buyAt < price) {
// profit += price - buyAt;
// }
// buyAt = price;
// }
// return profit;
int profit = 0;
for (int i = 1;i<prices.length;i++) {
if (prices[i] > prices[i-1]) {
profit += prices[i] - prices[i-1];
}
}
return profit;
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list= new ArrayList<List<Integer>>();
find(list,candidates,target,new ArrayList<Integer>(),0);
return list;
}
private void find(List<List<Integer>> list,int[] candidates,int target,ArrayList<Integer> temp,int i)
{
if(target==0)
{
list.add(new ArrayList<Integer>(temp));
return;
}
if(i==candidates.length)
return;
// pick
if(candidates[i]<=target){
temp.add(candidates[i]);
find(list,candidates,target-candidates[i],temp,i);
temp.remove(temp.size()-1);
}
// not pick
find(list,candidates,target,temp,i+1);
}
4. Two Sum
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int n = nums.length;
int[] res = new int[2];
for (int i = 0;i<n;i++) {
if (map.containsKey(target - nums[i])) {
res[0] = map.get(target - nums[i]);
res[1] = i;
} else {
map.put(nums[i], i);
}
}
return res;
}
public int calculate(String s) {
//Use stack for evaluating expression
int len = s.length();
if(s==null || (len = s.length())==0) return 0;
Stack<Integer> stack = new Stack<>();
int num = 0;
char sign = '+';
for (int i = 0;i<len;i++) {
if (Character.isDigit(s.charAt(i))) {
num = num*10 + s.charAt(i) - '0';
}
if((!Character.isDigit(s.charAt(i)) &&' '!=s.charAt(i)) || i==len-1){
if(sign=='-'){
stack.push(-num);
}
if(sign=='+'){
stack.push(num);
}
if(sign=='*'){
stack.push(stack.pop()*num);
}
if(sign=='/'){
stack.push(stack.pop()/num);
}
sign = s.charAt(i);
num = 0;
}
}
int re = 0;
for(int i:stack){
re += i;
}
return re;
}
So above are five commonly asked leet code problems of tech interviews, I will be sharing more in the subsequent articles.
Thanks for reading!!