Array Flashcards

1
Q

[Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
Example 2:

Input: nums = [1,1,2]
Output: [1]
Example 3:

Input: nums = [1]
Output: []

A

class Solution {
public List<Integer> findDuplicates(int[] nums) {
// 4 -3 -2 -7 -3 -1
List<Integer> li = new ArrayList<>();
for(int i =0;i<nums.length;i++){
int index = Math.abs(nums[i])-1;
nums[index]= nums[index]*-1 ;
if(nums[index]>0){
li.add(index+1);
}
}
return li;
}
}</Integer></Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. Unique Number of Occurrences
    Easy

Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:

Input: arr = [1,2]
Output: false
Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

A

class Solution {
public boolean uniqueOccurrences(int[] arr) {
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
hm.put(arr[i], hm.getOrDefault(arr[i], 0) + 1);
}
Set<Integer> set = hm.keySet();
HashSet<Integer> hs = new HashSet<>();
for (Integer i : set) {
if (!hs.contains(hm.get(i))) {
hs.add(hm.get(i));
} else {
return false;
}
}
return true;</Integer></Integer>

} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. Intersection of Two Arrays
    Easy

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.

A

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> s = new HashSet<>();
Set<Integer> f = new HashSet<>();
for(int i =0;i<nums1.length;i++){
s.add(nums1[i]);
}
for(int i =0;i<nums2.length;i++){
if(s.contains(nums2[i])){
f.add(nums2[i]);
}
}
int[] output = new int[f.size()];
int length = 0;
for(Integer i : f){
output[length]=i;
length++;
}
return output;
}
}</Integer></Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Replace Elements with Greatest Element on Right Side
    Easy

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Example 1:

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation:
- index 0 –> the greatest element to the right of index 0 is index 1 (18).
- index 1 –> the greatest element to the right of index 1 is index 4 (6).
- index 2 –> the greatest element to the right of index 2 is index 4 (6).
- index 3 –> the greatest element to the right of index 3 is index 4 (6).
- index 4 –> the greatest element to the right of index 4 is index 5 (1).
- index 5 –> there are no elements to the right of index 5, so we put -1.

A

class Solution {
public int[] replaceElements(int[] arr) {
for(int i =0;i<arr.length;i++){
int max_val = -1;
for(int j = i+1;j<arr.length;j++){
if(arr[j]>max_val){
max_val = arr[j];
}

        }
        arr[i]=max_val;     
    }
    return arr;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. Unique Email Addresses
    Easy
    Every valid email consists of a local name and a domain name, separated by the ‘@’ sign. Besides lowercase letters, the email may contain one or more ‘.’ or ‘+’.

For example, in “alice@leetcode.com”, “alice” is the local name, and “leetcode.com” is the domain name.
If you add periods ‘.’ between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.

For example, “alice.z@leetcode.com” and “alicez@leetcode.com” forward to the same email address.
If you add a plus ‘+’ in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.

For example, “m.y+name@email.com” will be forwarded to “my@email.com”.
It is possible to use both of these rules at the same time.

Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.

Example 1:

Input: emails = [“test.email+alex@leetcode.com”,”test.e.mail+bob.cathy@leetcode.com”,”testemail+david@lee.tcode.com”]
Output: 2
Explanation: “testemail@leetcode.com” and “testemail@lee.tcode.com” actually receive mails.
Example 2:

Input: emails = [“a@leetcode.com”,”b@leetcode.com”,”c@leetcode.com”]
Output: 3

A

class Solution {

public int numUniqueEmails(String[] emails) {
    Set<String> hs = new HashSet<>();
    for(int i =0;i<emails.length;i++){
        StringBuilder sb  = new StringBuilder();
        String[] prefixArray = emails[i].split("@");
        String[] furtherPrefix = prefixArray[0].split("\\+");
      
        String prefixFinal = furtherPrefix[0].replaceAll("\\.","");
         sb.append(prefixFinal).append("@").append(prefixArray[1]);
          System.out.println(sb);
        hs.add(sb.toString());

    }

    return hs.size();
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  1. Best Time to Buy and Sell Stock
    Easy

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

A

class Solution {
public int maxProfit(int[] prices) {
int minValue =Integer.MAX_VALUE;
int profit = 0;
int maxProfit=0

   for(int i = 0;i<prices.length;i++){
 minValue=Math.min(minValue,prices[i]);

       profit = prices[i]-minValue;

       if(profit>maxProfit){
           maxProfit = profit;
       }
   }
   return maxProfit;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
  1. Merge Sorted Array
    Easy

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Example 3:

A

class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
m =m-1;
n = n-1;
int curr = nums1.length-1;
while(curr>=0){

       if(m<0){
           nums1[curr]=nums2[n];
           n--;
           curr--;
       }

        else if(n<0){
           nums1[curr]=nums1[m];
           m--;
           curr--;
       }
       else {
           if(nums2[n]>nums1[m]){
           nums1[curr]=nums2[n];
           curr--;
           n--;
       }
       else {
           nums1[curr]=nums1[m];
           curr--;
           m--;
       }
    }
} } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
  1. Peak Index in a Mountain Array
    Medium

An array arr is a mountain if the following properties hold:

arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < … < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > … > arr[arr.length - 1]
Given a mountain array arr, return the index i such that arr[0] < arr[1] < … < arr[i - 1] < arr[i] > arr[i + 1] > … > arr[arr.length - 1].

You must solve it in O(log(arr.length)) time complexity.

Example 1:

Input: arr = [0,1,0]
Output: 1
Example 2:

Input: arr = [0,2,1,0]
Output: 1
Example 3:

Input: arr = [0,10,5,2]
Output: 1

A

class Solution {
public int peakIndexInMountainArray(int[] arr) {

    int left = 0;

    int right = arr.length-1;

    while(left<=right){
        int mid = (left+right)/2;

        if(arr[mid]>arr[mid+1] && arr[mid]>arr[mid-1]){
            return mid;
        }

        else if(arr[mid]<arr[mid+1]){
            left = mid+1;
        }
        else{
            right = mid;
        }
    }
    return -1;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
  1. Find Peak Element(multiple peaks)
    Medium
    11.2K
    4.5K
    company
    Facebook
    company
    Amazon
    c
    A peak element is an element that is strictly greater than its neighbors.

Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in O(log n) time.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

A

class Solution {
public int findPeakElement(int[] arr) {
if(arr.length==1) return 0;
if(arr[0] > arr[1]) return 0;
if(arr[arr.length-2] < arr[arr.length-1]) return arr.length-1;

    int left = 0;
    int right = arr.length-1;
    while(left<=right){
        int mid = (left+right)/2;

        if(arr[mid]>arr[mid+1] && arr[mid]>arr[mid-1]){
            return mid;
        }
        else if(arr[mid]<arr[mid+1]){
            left = mid+1;
        }
        else{
            right = mid;
        }
    }
    return -1;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
  1. Group Anagrams
    Medium

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
Example 2:

Input: strs = [””]
Output: [[””]]
Example 3:

Input: strs = [“a”]
Output: [[“a”]]

A

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> output = new ArrayList<>();
Map<String,List<String>> hm = new HashMap<>();
for(int i =0;i<strs.length;i++){
String s = strs[i];
char[] charArr = s.toCharArray();
Arrays.sort(charArr);
System.out.println(charArr);
if(!hm.containsKey(String.valueOf(charArr)))
hm.put(String.valueOf(charArr),new ArrayList<String>());
hm.get(String.valueOf(charArr)).add(s);
}
Set<String> set = hm.keySet();
for(String s : set){
output.add(hm.get(s));
}
return output;</String></String></String></String></String>

} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
  1. Kth Largest Element in an Array
    Medium

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

A

class Solution {
public int findKthLargest(int[] nums, int k) {
//1,2,2,3,3,4,5,5,6
//1,2,3,4,5,6

PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0;i<nums.length;i++){
pq.add(nums[i]);
}
for(int i =0;i<nums.length-k;i++){
pq.poll();
}
return pq.poll();
}
}</Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
  1. Best Time to Buy and Sell Stock II
    Medium
    You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.

A

class Solution {

public int maxProfit(int[] prices) {
    int minValue = prices[0];
    int maxValue = prices[0];
    int maxProfit = 0;
    int x=0;
    while(x<prices.length-1){

        while(x<prices.length-1 && prices[x]>=prices[x+1]){
            x++;
        }
        minValue = prices[x];

        while(x<prices.length-1 && prices[x]<=prices[x+1]){
            x++;
        }
        maxValue = prices[x];

        maxProfit = maxProfit + maxValue - minValue;
    }
    return maxProfit;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
  1. Product of Array Except Self
    Medium

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

A

class Solution {
public int[] productExceptSelf(int[] nums) {
int preffixProd = 1;
int suffixProd = 1;
int[] result = new int[nums.length];
result[0]=1;
for(int i =1;i<nums.length;i++){
preffixProd = preffixProd *nums[i-1];
result[i]=preffixProd;
}

    for(int j=nums.length-2;j>=0;j--){
        suffixProd = suffixProd * nums[j+1];
        result[j]= result[j] * suffixProd;
    }
    return result;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
  1. Top K Frequent Elements
    Medium

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:

Input: nums = [1], k = 1
Output: [1]

A

class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int[] output = new int[k];
for(int i =0;i<nums.length;i++){
map.put(nums[i], map.getOrDefault(nums[i],0)+1);
}
List<Integer> list = new ArrayList<>(map.keySet());
Collections.sort(list,(a, b)->map.get(b)-map.get(a));</Integer>

    for(int i =0;i<output.length;i++){
        output[i]=list.get(i);
    }
    return output;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
  1. Find the Duplicate Number
    Medium

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2
Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

A

class Solution {
public int findDuplicate(int[] nums) {
int l =0;
int r=nums.length-1;
int dup =-1;

    while(l<=r){
        int mid = l+(r-l)/2;
        
        int count=count(nums,mid);
        if(count>mid){
            dup=mid;
            r=mid-1;
        }
            
        else
            l=mid+1;
    }
    return dup;
}


private int count(int[] nums, int mid){
    int count=0;
    for(int i=0;i<nums.length;i++){
        if(nums[i]<=mid)
            count++;
    }
    return count;
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
  1. Majority Element II
    Medium

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Example 1:

Input: nums = [3,2,3]
Output: [3]
Example 2:

Input: nums = [1]
Output: [1]
Example 3:

Input: nums = [1,2]
Output: [1,2]

A

class Solution {
public List<Integer> majorityElement(int[] nums) {
Set<Integer> set = new HashSet<>();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0;i<nums.length;i++){
pq.add(nums[i]);
}
int curr = Integer.MAX_VALUE;
int count = 0;
int maxCount = 0;
for(int i =0;i<nums.length;i++){
if(pq.peek()==curr){
pq.poll();
count++;
}
else{
curr= pq.poll();
count = 1;
}
if(nums.length/3<count){
set.add(curr);
}
}
return new ArrayList<>(set);
}
}</Integer></Integer></Integer>

17
Q
  1. Maximum Subarray
    Medium

Given an integer array nums, find the
subarray
with the largest sum, and return its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.
Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

A

class Solution {
public int maxSubArray(int[] nums) {

  int maxSum  = Integer.MIN_VALUE;
  int runningSum = 0;
  int max_start = 0;
  int max_end = 0;
  for(int i = 0;i<nums.length;i++){

      runningSum = runningSum + nums[i];
      if(runningSum>maxSum){
          maxSum= runningSum;
          max_end = i;
      }
      else if(runningSum<0){
          max_start = i+1;
          runningSum=0;
      }
  }
System.out.println("max_start "+ max_start +" max_end  "+max_end);
  return maxSum;
} }
18
Q
  1. Longest Consecutive Sequence
    Medium

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

A

class Solution {

public int longestConsecutive(int[] nums) {
int count = 0;
int maxCount = 0;
int curr = Integer.MAX_VALUE;
    PriorityQueue<Integer> pq = new PriorityQueue<>();

    for(int i =0;i<nums.length;i++){
        pq.add(nums[i]);
    }
    for(int i =0;i<nums.length;i++){
     if(curr+1==pq.peek()){
         count++;
        curr =  pq.poll();
         }
         else if(curr==pq.peek()){
              curr =  pq.poll();
         }
    else{
        count = 1;
        curr= pq.poll();
    }
    if(count>maxCount){
        maxCount = count;
    }
    
}

return maxCount; }

}

19
Q
  1. Peak Index in a Mountain Array
    Medium

An array arr is a mountain if the following properties hold:

arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < … < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > … > arr[arr.length - 1]
Given a mountain array arr, return the index i such that arr[0] < arr[1] < … < arr[i - 1] < arr[i] > arr[i + 1] > … > arr[arr.length - 1].

You must solve it in O(log(arr.length)) time complexity.

Example 1:

Input: arr = [0,1,0]
Output: 1
Example 2:

Input: arr = [0,2,1,0]
Output: 1
Example 3:

Input: arr = [0,10,5,2]
Output: 1

A

class Solution {
public int peakIndexInMountainArray(int[] nums) {
int l =0;
int r= nums.length-1;
int mid =0;
while(l <= r){
mid = (l+r)/2;
if(nums[mid]>nums[mid+1])
r=mid;
else
l=mid+1;

        if(nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1]){
            return mid;
        }
            
    }
    return -1;
} }
20
Q
  1. Rotate Array by K
    Medium
    17K
    1.8K
    company
    Amazon

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

A

class Solution {
public void rotate(int[] nums, int k) {
if(nums.length==1){
return;
}
rotateBy(nums, 0, nums.length-1);
rotateBy(nums,0,k-1);
rotateBy(nums, k, nums.length-1);
}
public void rotateBy(int[] nums, int start, int end){
while(start<=end){
int temp = nums[start];
nums[start]=nums[end];
nums[end] = temp;
end–;
start++;
}
}
}

21
Q
  1. 3Sum
    Medium

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

A

class Solution {

public List<List<Integer>> threeSum(int[] nums) {
     List<List<Integer>> output = new ArrayList<>();
    Arrays.sort(nums);
   
    for(int i =0;i<nums.length;i++){
         if(i!=0 && nums[i]==nums[i-1]){
    continue;
    }
        int left = i+1;
        int right = nums.length - 1;

        while(left<right){
            if(nums[i]+nums[left]+nums[right]==0){
                List<Integer> li = new ArrayList<>();
                li.add(nums[i]);
                li.add(nums[left]);
                li.add(nums[right]);
                left++;
                right--;
                output.add(li);
                while(left<right && nums[left]==nums[left-1]){
                    left++;
                }
                while(left<right && nums[right]==nums[right+1]){
                    right--;
                }
            }
            else if(nums[i]+nums[left]+nums[right]>0){
                right--;
            }
            else left++;
        }
    }
    return output;
} }
22
Q
  1. Maximum Subarray
    Medium

Given an integer array nums, find the
subarray
with the largest sum, and return its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.
Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

A

class Solution {
public int maxSubArray(int[] nums) {

  int maxSum  = Integer.MIN_VALUE;
  int runningSum = 0;
  //int max_start = 0;
 // int max_end = 0;
  for(int i = 0;i<nums.length;i++){

      runningSum = runningSum + nums[i];
      if(runningSum>maxSum){
          maxSum= runningSum;
        //  max_end = i;
      }
      else if(runningSum<0){
        //  max_start = i+1;
          runningSum=0;
      }
  }
System.out.println("max_start "+ max_start +" max_end  "+max_end);
  return maxSum;
} }
23
Q
  1. Subarray Sum Equals K
    Medium

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,1,1], k = 2
Output: 2
Example 2:

Input: nums = [1,2,3], k = 3
Output: 2

A

class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int runningSum = 0;
Map<Integer, Integer> hm = new HashMap<>();
hm.put(0,1);
for(int i =0;i<nums.length;i++){
runningSum = runningSum + nums[i];

       if(hm.containsKey(runningSum-k)){
           count = count+ hm.get(runningSum-k);
       }

       hm.put(runningSum, hm.getOrDefault(runningSum, 0)+1);
       
   }

   return count;
}
}
24
Q
  1. Find First and Last Position of Element in Sorted Array
    Medium

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

A

class Solution {
boolean isFound = false;
public int[] searchRange(int[] nums, int target) {

    int [] output = new int[2];

    int leftIndex = findLeftIndex(nums, target);
    int rightIndex = findRightIndex(nums, target);

    if(isFound==true){
        output[0] = leftIndex;
        output[1] = rightIndex;
    }
    else{
        output[0] = -1;
        output[1] = -1;
    }
    return output;
}

   int findLeftIndex(int[] nums, int target){
       int left = 0;
       int right = nums.length-1; while(left<=right){
       int mid = (left+right)/2;

       if(nums[mid]==target){
           isFound = true;
           right = mid-1;
       }
       else if(nums[mid]<target){
           left = mid+1;
       }
       else {
           right = mid-1;
       }
   }
        return left;
   }

    int findRightIndex(int[] nums, int target){
    int left = 0;
    int right = nums.length-1;

    
    while(left<=right){
       int mid = (left+right)/2;

       if(nums[mid]==target){
           isFound = true;
           left = mid+1;
       }
       else if(nums[mid]>target){
           right = mid-1;
       }
       else{
        left = mid+1;
       }
        }
       return right;
   }
    
}
25
Q
  1. Meeting Rooms

Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:

Input: intervals = [[7,10],[2,4]]
Output: true

A

class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals,(a,b)->a[0]-b[0]);

    for(int i =1;i<intervals.length;i++){

        if(intervals[i-1][1]> intervals[i][0]){
            return false;
        }

    }
    return true;
} }
26
Q
  1. Meeting Rooms II
    Medium

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:

Input: intervals = [[7,10],[2,4]]
Output: 1

A

class Solution {
public int minMeetingRooms(int[][] intervals) {
Arrays.sort(intervals, (a,b)->a[0]-b[0]);

    PriorityQueue<Integer> pq = new PriorityQueue<>();
    pq.add(intervals[0][1]);

    for(int i =1;i<intervals.length;i++){
        if(intervals[i][0]<pq.peek()){
            pq.add(intervals[i][1]);
        }
        else{
            pq.poll();
            pq.add(intervals[i][1]);
        }
    }

    return pq.size();
    
} }
27
Q
  1. Merge Intervals
    Medium

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

A

class Solution {
public int[][] merge(int[][] intervals) {

   Arrays.sort(intervals,(a,b)->a[0]-b[0]);
    List<int[]> li = new ArrayList<>();
    li.add(intervals[0]);

    for(int i =1;i<intervals.length;i++){
        int curr=intervals[i][0];
        int[] temp = li.get(li.size()-1);
        if(temp[1] >= intervals[i][0]){
            temp[1]=Math.max(li.get(li.size()-1)[1],intervals[i][1]);
        }
        else{
            li.add(intervals[i]);
        }
    }

    int size = li.size();
    int[][] output = new int[size][2];
    for(int i = 0;i<li.size();i++){
        output[i][0]=li.get(i)[0];
        output[i][1]=li.get(i)[1];
    }
    return output;
    
} }
28
Q
  1. Find All Duplicates in an Array
    Medium

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
Example 2:

Input: nums = [1,1,2]
Output: [1]
Example 3:

Input: nums = [1]
Output: []

A

class Solution {
public List<Integer> findDuplicates(int[] nums) {
// 4 -3 -2 -7 -3 -1
List<Integer> li = new ArrayList<>();
for(int i =0;i<nums.length;i++){
int index = Math.abs(nums[i])-1;
nums[index]= nums[index]*-1;</Integer></Integer>

      if(nums[index]>0){
          li.add(index+1);
      }
  }
  return li;
} }
29
Q
  1. Maximum Product Subarray
    Medium

Given an integer array nums, find a
subarray
that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray

A

class Solution {
public int maxProduct(int[] nums) {

    int min = nums[0];
    int max = nums[0];
    int result = nums[0];
    int length = nums.length;
    if (length == 0)
        return 0;

    for (int i = 1; i < nums.length; i++) {
        int temp_max = Math.max(max * nums[i], Math.max(min * nums[i], nums[i]));
        min = Math.min(max * nums[i], Math.min(min * nums[i], nums[i]));
        max = temp_max;
        result = Math.max(result, max);
    }
    return result;
} }
30
Q
  1. Robot Return to Origin
    Easy

There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are ‘R’ (right), ‘L’ (left), ‘U’ (up), and ‘D’ (down).

Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.

Note: The way that the robot is “facing” is irrelevant. ‘R’ will always make the robot move to the right once, ‘L’ will always make it move left, etc. Also, assume that the magnitude of the robot’s movement is the same for each move.

Example 1:

Input: moves = “UD”
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

A

class Solution {
public boolean judgeCircle(String moves) {
if(moves.length()==0){
return true;
}
int x = 0;
int y = 0;
for(int i =0;i<moves.length();i++){
if(moves.charAt(i)==’R’){
x = x+1;
}
else if(moves.charAt(i)==’L’){
x = x-1;
}
else if(moves.charAt(i)==’U’){
y = y+1;
}
else if(moves.charAt(i)==’D’){
y = y-1;
}
}
if(x==0 && y==0){
return true;
}
return false;
}
}

31
Q

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Example 1:

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
Example 2:

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.

A

class Solution {
public int missingNumber(int[] nums) {

    int[] output = new int[nums.length+1];

    for(int i =0;i<nums.length;i++){
        output[nums[i]]= -2;
    }

    for(int i =0;i<output.length;i++){
        if(output[i]==0)return i;
    }
    return 0;
} }

class Solution {
public int missingNumber(int[] nums) {
int sum = 0;
int expectedSum = 0;

   for(int i =0;i<=nums.length;i++){
       expectedSum = expectedSum +i;
   }
    for(int i =0;i<nums.length;i++){
       sum = sum +nums[i];
   }
   
   return expectedSum-sum;
} }
32
Q
  1. Shuffle an Array

Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.

Implement the Solution class:

Solution(int[] nums) Initializes the object with the integer array nums.
int[] reset() Resets the array to its original configuration and returns it.
int[] shuffle() Returns a random shuffling of the array.

A

class Solution {
private int[] array;
private int[] original;
public Solution(int[] nums) {
array = nums;
original = nums.clone();
}

public int[] reset() {
    return original;
}

public int[] shuffle() {
        for (int i = 0; i < array.length; i++) {
        swapAt(i, randRange(i, array.length));
    }
    return array;
}

 Random rand = new Random();

private int randRange(int min, int max) {
    int random = rand.nextInt(max - min);
    return random ;
}

private void swapAt(int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
} }

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/

33
Q
  1. Find Minimum in Rotated Sorted Array
    Medium

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.

Example 1:

Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Example 2:

Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.

A

class Solution {
public int findMin(int[] nums) {
// If the list has just one element then return that element.
if (nums.length == 1) {
return nums[0];
}
int left = 0, right = nums.length - 1;

    if (nums[right] > nums[0]) {
        return nums[0];
    }

    while (left<=right) {
  
        int mid = (left+right) / 2;
        if (nums[mid] > nums[mid + 1]) {
            return nums[mid + 1];
        }
        if (nums[mid - 1] > nums[mid]) {
            return nums[mid];
        }

        if (nums[mid] > nums[0]) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return Integer.MAX_VALUE;
} }
34
Q
  1. Two City Scheduling
    Medium
    Topics
    Companies
    A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.

Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.

Example 1:

Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Example 2:

Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859
Example 3:

Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086

A

class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (a, b) -> (a[0] - a[1]) - (b[0] - b[1]));
int sum = 0;
for (int i = 0; i < costs.length / 2; i++) {
sum += costs[i][0] + costs[i + costs.length / 2][1];
}
return sum;

} }
35
Q
  1. Insert Delete GetRandom O(1)
    Medium
    Topics
    Companies
    Implement the RandomizedSet class:

RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1) time complexity.

Example 1:

Input
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

A
36
Q
A