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

LeetCode – Range Addition (Java)

Assume you have an array of length n initialized with all 0’s and are given k update operations. Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex … endIndex] (startIndex and endIndex inclusive) with inc. Return the modified array after all k operations were executed. For example, … Read more

LeetCode – Majority Element II (Java)

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. Java Solution This problem is similar to Majority Element I. Time = O(n) and Space = O(1). public List<Integer> majorityElement(int[] nums) { List<Integer> result = new … Read more

LeetCode – Kth Smallest Element in a BST (Java)

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. (1 ≤ k ≤ BST’s total elements) Java Solution 1 – Inorder Traversal We can inorder traverse the tree and get the kth smallest element. Time is O(n). public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> stack = … Read more

LeetCode – Summary Ranges (Java)

Given a sorted integer array without duplicates, return the summary of its ranges for consecutive numbers. For example, given [0,1,2,4,5,7], return [“0->2″,”4->5″,”7”]. Analysis When iterating over the array, two values need to be tracked: 1) the first value of a new range and 2) the previous value in the range. Java Solution public List<String> summaryRanges(int[] … Read more