Leetcode – Container With Most Water – Solution

  • Problem : Link.
  • Language used : Java.
  • Status : Accepted.

Solution :

public class Solution {
public int maxArea(int[] height) {

int left = 0;
int right = height.length - 1;
int max_area = 0;

while (left <= right){

            max_area = Math.max(max_area, Math.min(height[left], height[right]) * (right - left));

            if(height[left] < height[right])
                left++;
            else 
                right--;
        }

        return max_area;
    }
}

Leetcode – 3Sum – Solution

  • Problem : Link.
  • Language used : Java.
  • Status : Accepted.

Solution :

class Solution {
public List 	<list> threeSum(int[] nums) {
List 	<list> result = new ArrayList 	<list>();
Arrays.sort(nums);</list</list</list

for(int i = 0; i < nums.length; i++){
            int first = nums[i];

            if(i > 0 && nums[i] == nums[i-1]) continue;
int low = i + 1;
int high = nums.length - 1;

while(low < high){
                if (nums[low] + nums[high] + first == 0) {
                    List l = new ArrayList();
l.add(nums[low]);
l.add(nums[high]);
l.add(first);

result.add(l);

// let's ignore the dublicates;
while(low < high && nums[low] == nums[low + 1]) low++;
                    while(low < high && nums[high] == nums[high - 1]) high--;

                    low ++;
                    high --;
                }
                else if(nums[low] + nums[high] > -first){
high --;
}
else {
low++;
}
}
}
return result;
}
}

Leetcode – Search in Rotated Sorted Array – Solution

  • Problem : Link.
  • Language used : Java.
  • Status : Accepted.

Solution :

public class Solution {
public int search(int[] nums, int target) {

int low = 0;
int high = nums.length - 1;

while(low <= high){
            int med = (low + high) / 2;

            if(target == nums[med])
                return med;

            if(nums[med] < nums[high]){
                if(nums[med] <= target && nums[high] >= target)
low = med + 1;
else
high = med - 1;
}
else{
if(nums[med] >= target && nums[low] <= target)
                    high = med - 1;
                else
                    low = med + 1;
            }

        }
        return -1;
    }
}

Leetcode – Product of Array Except Self – Solution

  • Problem : Link.
  • Language used : Java.
  • Status : Accepted.

Solution :

public class Solution {
public int[] productExceptSelf(int[] nums) {
int [] mem = new int [nums.length];

int zeros = 0;
int multiply = 1;

for(int i = 0; i < nums.length; i++)
            if(nums[i] == 0)
                zeros++;
            else
                multiply *= nums[i];

        for(int i = 0; i < nums.length; i++){
            if(zeros > 1)
mem[i] = 0;

else if(zeros == 1){
if(nums[i] == 0)
mem[i] = multiply;
else
mem[i] = 0;
}
else {
mem[i] = multiply / nums[i];
}
}

return mem;
}
}