Day 20 of LeetCode Challenge

Cloud and DevOps Engineer with hands-on expertise in AWS, CI/CD pipelines, Docker, Kubernetes, and Monitoring tools. Adept at building and automating scalable, fault-tolerant cloud infrastructures, and consistently improving system performance, security, and reliability in dynamic environments.
Problem 1: Majority Element
Link to the problem: https://leetcode.com/problems/majority-element/

class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i:nums){
if(map.containsKey(i))
map.put(i, map.get(i)+1);
else
map.put(i, 1);
}
int max = 0;
int ans = 0;
for(Map.Entry e:map.entrySet()){
if(max<(int) e.getValue()){
max = (int) e.getValue();
ans = (int) e.getKey();
}
}
return ans;
}
}
Problem 2: Valid Anagram
Link to the problem: https://leetcode.com/problems/valid-anagram/

class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())
return false;
HashMap<Character, Integer> map1 = new HashMap<>();
HashMap<Character, Integer> map2 = new HashMap<>();
for(int i=0; i<s.length(); i++){
char char1 = s.charAt(i);
char char2 = t.charAt(i);
if(map1.containsKey(char1))
map1.put(char1, map1.get(char1)+1);
else
map1.put(char1, 1);
if(map2.containsKey(char2))
map2.put(char2, map2.get(char2)+1);
else
map2.put(char2, 1);
}
if(!map1.equals(map2))
return false;
return true;
}
}
Problem 3: Max Consecutive Ones
Link to the problem: https://leetcode.com/problems/max-consecutive-ones/

class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int ans = 0;
for(int i:nums){
if(i==1)
count++;
else{
ans = ans>count?ans:count;
count=0;
}
}
return ans>count?ans:count;
}
}
Problem 4: Next Greater Element I
Link to the problem: https://leetcode.com/problems/next-greater-element-i/

class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] ans = new int[nums1.length];
for(int i=0; i<nums1.length; i++){
int j=0;
while(nums2[j]!=nums1[i])
j++;
int index = j;
j++;
while(j<nums2.length && nums2[j]<nums2[index])
j++;
if(j>nums2.length-1)
ans[i]=-1;
else
ans[i]=nums2[j];
}
return ans;
}
}
Problem 5: Set Mismatch
Link to the problem: https://leetcode.com/problems/set-mismatch/

class Solution {
public int[] findErrorNums(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] ans = new int[2];
for(int i:nums){
if(map.containsKey(i))
ans[0] = i;
else
map.put(i, 1);
}
for(int i=1; i<=nums.length; i++){
if(!map.containsKey(i)){
ans[1] = i;
break;
}
}
return ans;
}
}




