Posts

Showing posts with the label Leetcode 30 day challenge

Single Number - Leetcode

Given a non-empty  array of integers, every element appears twice except for one. Find that single one. Example 1: Input: [2,2,1] Output: 1   Example 2: Input: [4,1,2,1,2] Output: 4     class Solution { public int singleNumber(int[] nums) { int result = 0 ; for ( int i : nums) { result ^= i; } return result;   } }  Here we are going to do XOR operation. Because each number in array is repeated twice. So, XOR of same number is always 0 and  number which is not repeated will be stored in result.

Diameter of Binary Tree - Leetcode

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3 , which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them.  /**  * Definition for a binary tree node.  * public class TreeNode {  *     int val;  *     TreeNode left;  *     TreeNode right;  *     TreeNode(int x) { val = x; }  * }  */ public class Solution {     int max = 0;        public int diameterOfBinaryTree(TreeNode root) {         depth(root);         return max;     }        private int depth(TreeNode root) {         if (root == null) return 0;                int left = depth(root.left);         int right = depth(root.right);            

Min Stack - Leetcode

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2. class MinStack {     /** initialize your data structure here. */        Stack<Integer> stack = new Stack<Integer>();     public MinStack() {         // stack = new Stack<Integer>();     }         public void push(int x) {         stack.push(x);     }         public void pop() {         stack.pop();     }         public int top() {         return stack.peek();     }         public int getMin() {          int min = Integer.MAX_VALUE;

Backspace String Compare - Leetcode

Given two strings  S  and T , return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c" , T = "ad#c" Output: true Explanation : Both S and T become "ac".    Example 2: Input: S = "ab##" , T = "c#d#" Output: true     Explanation : Both S and T become "".    Example 3: Input: S = "a##c" , T = "#a#c" Output: true Explanation : Both S and T become "c".    Example 4: Input: S = "a#c" , T = "b" Output: false Explanation : S becomes "c" while T becomes "b".    Note : 1 <= S.length <= 200 1 <= T.length <= 200 S  and T only contain lowercase letters and '#' characters. class Solution {     public boolean backspaceCompare(String s, String t) {                 while(s.contains("#") || t.contains("#")){             if(s.contains(&

Middle of the linked list - Leetcode

Given a non-empty, singly linked list with head node head , return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list (Serialization: [3,4,5] ) The returned node has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a ListNode object ans, such that: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.   Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6] ) Since the list has two middle nodes with values 3 and 4, we return the second one. Here it can be done in two ways. Option 1: 1)Take two pointers one as slow and other as fast. 2)Initially both pointing to the head. 3)Slow points the next element and fast points next of next element. 4)Step 3 has to repeated until fast equal to null and fast of next equal to null. 5)After this point, slow will poin

Counting Elements - Leetcode

Given an integer array arr , count element  x such that x + 1 is also in arr . If there're duplicates in  arr , count them seperately. Example 1: Input: arr = [1,2,3] Output: 2 Explanation:  1 and 2 are counted cause 2 and 3 are in arr.   Example 2: Input: arr = [1,1,3,3,5,5,7,7] Output: 0 Explanation:  No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.   Example 3: Input: arr = [1,3,2,3,5,0] Output: 3 Explanation:  0, 1 and 2 are counted cause 1, 2 and 3 are in arr.   Example 4: Input: arr = [1,1,2,2] Output: 2 Explanation:  Two 1s are counted cause 2 is in arr. Constraints: 1 <= arr.length <= 1000 0 <= arr[i] <= 1000  Here the array to be converted as ArrayList or it can be done within the array itself . But if we done using only array then it consumes more time. Now consider for arraylist solution. 1)Retrieve each element from array using for each loop. 2)For each n element if there is n+1 then it is to be co

Group Anagrams

Given an array of strings, group anagrams together. Click this link to try it on Leetcode Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"] , Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. class Solution {     public List<List<String>> groupAnagrams(String[] strs) {   if (strs.length == 0) return new ArrayList();         Map<String, List> ans = new HashMap<String, List>();         for (String s : strs) {             char[] ca = s.toCharArray();             Arrays.sort(ca);             String key = String.valueOf(ca);             if (!ans.containsKey(key)) ans.put(key, new ArrayList());             ans.get(key).add(s);         }         return new ArrayList(ans.values());     } } Here string is to be stored

Best Time to Buy and Sell Stock II - Leetcode

Say you have an array for which the i th element is the price of a given stock on day i . Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5),    Then buy on day 4 (price = 3) and sell on day 5 (price = 6),  profit = 6-3 = 3.   Example 2: Input: [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.  Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are  engaging multiple transactions at the same time. You must sell before buying again.   Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e

Happy Number - LeetCode

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example:  Input: 19 Output: true Explanation: 1 2 + 9 2 = 82 8 2 + 2 2 = 68 6 2 + 8 2 = 100 1 2 + 0 2 + 0 2 = 1       Here the solution has to be done with in-build method. If we squaring the sum of each digit it will end up at 1, but in another case if sum is 4 it will be on loop and doesn't end. So we have to break the loop at 1 or 4. If 1 it is happy number else it is not a happy number. Click this link to try it on Leetcode class Solution {     public boolean isHappy(int n) {         int sum=0, t1;         while(sum >= 0){             sum = 0;             while(n != 0){                 t1 = n%10;

Move Zeroes - LeetCode

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. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0]     class Solution { public void moveZeroes(int[] nums) { int i, tmp=0; for(i=0;i<nums.length;i++){ if(nums[i]!=0){ nums[tmp++] = nums[i]; } } for(i=tmp;i<nums.length;i++){ nums[i] = 0; } } }    Click this link to try it on Leetcode     Here, the solution has to be completed in a in-build function.  In this we are going to take a temporary variable starts from 0 and  changing the array by updating the non-zero values to the same array.  Once the traversal is completed, temporary variable describes the  count of zeroes. Then starting from temporary variable position  till end of array has to be updates as 0.      For more Leetcode Problems