Skip to main content

22 posts tagged with "Leetcode"

Hola tag description

View All Tags

Maximum Subarray - Kadane's Algorithm

· One min read
Sandeep Bhardwaj

Maximum Subarray - Kadane's Algorithm

/**
* 53. Maximum Subarray - Kadane's Algorithm
* <p>
* Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum
* and return its sum.
* <p>
* Example:
* <p>
* Input: [-2,1,-3,4,-1,2,1,-5,4],
* Output: 6
* Explanation: [4,-1,2,1] has the largest sum = 6.
* Follow up:
* <p>
* If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach,
* which is more subtle.
*/
public class MaximumSubarray {
public int maxSubArray(int[] nums) {
int max_so_far = nums[0];
int max_ending_here = nums[0];

for (int i = 1; i < nums.length; i++) {
max_ending_here = Math.max(max_ending_here + nums[i], nums[i]);

max_so_far = Math.max(max_so_far, max_ending_here);

}
return max_so_far;
}
}

Sort Array By Parity

· One min read
Sandeep Bhardwaj

Sort Array By Parity

/**
* 905. Sort Array By Parity
* Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
* <p>
* You may return any answer array that satisfies this condition.
* <p>
* Example 1:
* <p>
* Input: [3,1,2,4]
* Output: [2,4,3,1]
* The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
* <p>
* Note:
* <p>
* 1 <= A.length <= 5000
* 0 <= A[i] <= 5000
* <p>
*/
public class SortArrayByParity {

public int[] sortArrayByParity(int[] A) {
int left = 0;
int right = A.length - 1;

while (left <= right) {
//swap and increment
if (A[left] % 2 != 0 && A[right] % 2 == 0) {
int temp = A[left];
A[left] = A[right];
A[right] = temp;

left++;
right--;
}

if (A[left] % 2 == 0) {
left++;
}
if (A[right] % 2 != 0) {
right--;
}
}
return A;
}
}

Valid Parentheses

· 2 min read
Sandeep Bhardwaj

Valid Parentheses

/**
* 20. Valid Parentheses
* <p>
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
* <p>
* An input string is valid if:
* <p>
* Open brackets must be closed by the same type of brackets.
* Open brackets must be closed in the correct order.
* Note that an empty string is also considered valid.
* <p>
* Example 1:
* <p>
* Input: "()"
* Output: true
* Example 2:
* <p>
* Input: "()[]{}"
* Output: true
* Example 3:
* <p>
* Input: "(]"
* Output: false
*/
public class ValidParentheses {

public boolean isValid(String s) {

Stack<Character> stack = new Stack<>();

for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);

// for open parentheses push to stack
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
continue;
}

if (stack.isEmpty()) {
return false;
}

char top = stack.pop();

if (ch == ')' && top != '(') {
return false;
}

if (ch == '}' && top != '{') {
return false;
}

if (ch == ']' && top != '[') {
return false;
}
}

return stack.isEmpty();
}

public boolean isValid2(String s) {
Stack<Character> stack = new Stack<Character>();

for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '{') {
stack.push('}');
} else if (c == '[') {
stack.push(']');
} else if (stack.isEmpty() || stack.pop() != c) {
return false;
}
}
return stack.isEmpty();
}
}

Find All Numbers Disappeared in an Array

· One min read
Sandeep Bhardwaj

Find All Numbers Disappeared in an Array

/**
* 448. Find All Numbers Disappeared in an Array
* <p>
* Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
* <p>
* Find all the elements of [1, n] inclusive that do not appear in this array.
* <p>
* Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
* <p>
* Example:
* <p>
* Input:
* [4,3,2,7,8,2,3,1]
* <p>
* Output:
* [5,6]
*/
public class FindAllNumbersDisappearedInAnArray {
public List<Integer> findDisappearedNumbers(int[] nums) {

List<Integer> results = new ArrayList<>();

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

//negate the output
nums[val - 1] = -Math.abs(nums[val - 1]);
}

for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
results.add(i + 1);
}

}
return results;
}
}

Move Zeroes

· One min read
Sandeep Bhardwaj

Move Zeroes

/**
* 283. Move Zeroes
* <p>
* Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the
* non-zero elements.
* <p>
* Example:
* <p>
* Input: [0,1,0,3,12]
* Output: [1,3,12,0,0]
* Note:
* <p>
* You must do this in-place without making a copy of the array.
* Minimize the total number of operations.
*/
public class MoveZeroes {
public void moveZeroes(int[] nums) {
int left = 0;
int right = 0;

while (left <= right && right < nums.length) {
if (nums[left] == 0 && nums[right] == 0) {
right++;
continue;
}

if (nums[left] == 0) {
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;

left++;
right++;
continue;
}

//if left is not zero
left++;
right++;
}

}
}

Single Number

· One min read
Sandeep Bhardwaj

Single Number

/**
* 136. Single Number
* <p>
* Given a non-empty array of integers, every element appears twice except for one. Find that single one.
* <p>
* Note:
* <p>
* Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
* <p>
* Example 1:
* <p>
* Input: [2,2,1]
* Output: 1
* Example 2:
* <p>
* Input: [4,1,2,1,2]
* Output: 4
*/
public class SingleNumber {
public int singleNumber(int[] nums) {

int result = 0;

for (int num : nums) {
result ^= num;
}

return result;

}
}

Maximum Depth of Binary Tree

· One min read
Sandeep Bhardwaj

Maximum Depth of Binary Tree

/**
* 104. Maximum Depth of Binary Tree
* Given a binary tree, find its maximum depth.
* <p>
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
* <p>
* Note: A leaf is a node with no children.
* <p>
* Example:
* <p>
* Given binary tree [3,9,20,null,null,15,7],
* return its depth = 3.
*/
public class MaximumDepthOfBTree {
public int maxDepth(TreeNode root) {

if(root==null)
{
return 0;
}

int left = maxDepth(root.left);
int right = maxDepth(root.right);

return Math.max(left,right)+1;
}
}

Remove Duplicates from Sorted List

· One min read
Sandeep Bhardwaj

Remove Duplicates from Sorted List

/**
* 83. Remove Duplicates from Sorted List
* <p>
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* <p>
* Example 1:
* <p>
* Input: 1->1->2
* Output: 1->2
* Example 2:
* <p>
* Input: 1->1->2->3->3
* Output: 1->2->3
*/
public class RemoveDuplicatesFromSortedList {
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null) {
if (current.next == null)
break;

if (current.val == current.next.val) {
//removing duplicate breaking the link
current.next = current.next.next;
} else {
current = current.next;
}

}
return head;
}
}

Remove Duplicates from Sorted Array

· 2 min read
Sandeep Bhardwaj

Remove Duplicates from Sorted Array

/**
* 26. Remove Duplicates from Sorted Array
* <p>
* Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
* <p>
* Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
* <p>
* Example 1:
* <p>
* Given nums = [1,1,2],
* <p>
* Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
* <p>
* It doesn't matter what you leave beyond the returned length.
* Example 2:
* <p>
* Given nums = [0,0,1,1,1,2,2,3,3,4],
* <p>
* Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
* <p>
* It doesn't matter what values are set beyond the returned length.
*/
public class RemoveDuplicatesFromSortedArray {
public int removeDuplicates(int[] nums) {
int unique = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] != nums[i]) {
nums[unique] = nums[i];
unique++;
}
}
return unique;
}
}

Remove All Adjacent Duplicates In String

· 2 min read
Sandeep Bhardwaj

Remove All Adjacent Duplicates In String

/**
* 1047. Remove All Adjacent Duplicates In String
* <p>
* Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
* <p>
* We repeatedly make duplicate removals on S until we no longer can.
* <p>
* Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
* <p>
* <p>
* <p>
* Example 1:
* <p>
* Input: "abbaca"
* Output: "ca"
* Explanation:
* For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.
* The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
*/
public class RemoveDuplicates {
public String removeDuplicates(String S) {

Stack<Character> stack = new Stack<>();

for (int i = 0; i < S.length(); i++) {
char ch = S.charAt(i);

if (!stack.isEmpty() && stack.peek() == ch) {
stack.pop();
} else {
stack.push(ch);
}
}

StringBuffer result = new StringBuffer();
while (!stack.isEmpty()) {
result.append(stack.pop());
}

return result.reverse().toString();
}
}