LeetCode – Wiggle Subsequence (Java)

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. Java Solution The problem is converted to finding the turning point. When nums[i] … Read more

LeetCode – Product of Array Except Self (Java)

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Java Solution 1 public int[] productExceptSelf(int[] nums) { int[] result = … Read more

Implement a Queue using an Array in Java

There following Java code shows how to implement a queue without using any extra data structures in Java. We can implement a queue by using an array. import java.lang.reflect.Array; import java.util.Arrays;   public class Queue<E> {   E[] arr; int head = -1; int tail = -1; int size;   public Queue(Class<E> c, int size) … Read more

LeetCode – Lowest Common Ancestor of a Binary Tree (Java)

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. Java Solution 1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null) return null;   if(root==p || root==q) return root;   TreeNode l = lowestCommonAncestor(root.left, p, q); TreeNode r = lowestCommonAncestor(root.right, p, q);   if(l!=null&&r!=null){ return root; … Read more

LeetCode – Lowest Common Ancestor of a Binary Search Tree (Java)

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. Analysis This problem can be solved by using BST property, i.e., left < parent < right for each node. There are 3 cases to handle. Java Solution 1 – Recursive public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, … Read more

LeetCode – Palindrome Linked List (Java)

Given a singly linked list, determine if it is a palindrome. Java Solution 1 – Creat a new reversed list We can create a new list in reversed order and then compare each node. The time and space are O(n). public boolean isPalindrome(ListNode head) { if(head == null) return true;   ListNode p = head; … Read more

LeetCode – Implement Queue using Stacks (Java)

Implement the following operations of a queue using stacks. push(x) — Push element x to the back of queue. pop() — Removes the element from in front of queue. peek() — Get the front element. empty() — Return whether the queue is empty. Java Solution class MyQueue {   Stack<Integer> temp = new Stack<Integer>(); Stack<Integer> … Read more