Posts

Showing posts with the label Leetcode July Month Challenges

3Sum

Given an array nums of n integers, are there elements a , b , c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]   class Solution {     public List<List<Integer>> threeSum(int[] nums) {         if (nums.length < 3) return new ArrayList<>();         Arrays.sort(nums);         Set<List<Integer>> triplet= new HashSet<>();         for (int i = 0; i < nums.length - 2; i++) {             int j = i + 1;             int k = nums.length - 1;             while (j < k) {                 int sum = nums[i] + nums[j] + nums[k];                 if (sum == 0) triplet.add(Arrays.asList(nums[i], nums[j++], nums[k--]));                 else if (sum > 0) k--;                 else if (sum < 0) j++;             }   

Island Perimeter

Image
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: Input: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image below:   class Solution {     public int islandPerimeter(int[][] grid) {         int lands = 0, neighbours = 0;         for (int i = 0; i < grid.length; i++) {             for (int j = 0; j < grid[i].length; j++) {                 if (grid[i][j] == 1) {     

Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Example 2: Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321. FAILED APPROACH:   class Solution {     public int[] plusOne(int[] digits) {         digits[digits.length-1]+=1;         return digits;     } } Try it on Leetcode Above code seems to be correct, the mistake occurs when at end contains 9      Input        Output   Output according to our code i.e., [9]      -  [1, 0]    -    [10]        [9, 9]  - [1, 0, 0] -    [9, 10] Thus above code is not a solution for this problem. SUCCESSFULL APPR

Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y , calculate the Hamming distance. Note: 0 ≤ x , y < 2 31 . Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.   class Solution {     public int hammingDistance(int x, int y) {         String str = Integer.toBinaryString(x^y);         return str.replaceAll("0","").length();     } } Try it on Leetcode Here, we are going to solve in more easiest way. The hint hidden in this problem is, we need to convert integer to binary and compare both for any differences in 1's position. 1) Do XOR for both numbers.(XOR of same digits (0, 1) will be same). From this, we get difference in 1's position, but it will be in int type. 2) Convert int to binary using toBinaryString(). 3) R

Ugly Number II

Write a program to find the n -th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5 .  Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note:   1 is typically treated as an ugly number. n does not exceed 1690 .   class Solution {         public int nthUglyNumber(int n) {             int[] ugly = new int[n];             ugly[0] = 1;             int indexOf2 = 0, indexOf3 = 0, indexOf5 = 0;             int factorOf2 = 2, factorOf3 = 3, factorOf5 = 5;             for(int i=1;i<n;i++){                 int min = Math.min(Math.min(factorOf2,factorOf3),factorOf5);                 ugly[i] = min;                 if(factorOf2 == min)                     factorOf2 = 2*ugly[++indexOf2];                 if(factorOf3 == min)                     factorOf3 = 3*ugly[++indexOf3];                 if(factorOf5 == min)                     factorOf5 = 5*ugly[++

Prison Cells After N Days

There are 8 prison cells in a row, and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. Otherwise, it becomes vacant. (Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.) We describe the current state of the prison in the following way:  cells[i] == 1 if the i -th cell is occupied, else cells[i] == 0 . Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.) Example 1: Input: cells = [0,1,0,1,1,0,0,1] , N = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day

Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7] , 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ]   /**  * Definition for a binary tree node.  * public class TreeNode {  *     int val;  *     TreeNode left;  *     TreeNode right;  *     TreeNode() {}  *     TreeNode(int val) { this.val = val; }  *     TreeNode(int val, TreeNode left, TreeNode right) {  *         this.val = val;  *         this.left = left;  *         this.right = right;  *     }  * }  */ class Solution {     public List<List<Integer>> levelOrderBottom(TreeNode root) {         LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();         if(root==null)             return result;                 Queue<TreeNode> q= new Link

Arranging Coins

You have a total of n coins that you want to form in a staircase shape, where every k -th row must have exactly k coins. Given n , find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3.   class Solution {     public int arrangeCoins(int n) {         int i = 1;         while(n >= 0){             n = n-i;             i++;         }         return i-2;     } } Try it on Leetcode Here it is one of easiest solution. Each time i increases and at same time subtract it from total coins. Repeat this step until n becomes less than 0. Finally return i-2(i.e., to eliminate last i value and last i increment) Also Check it: Click here fo