• Home
  • Quick Bytes
  • Algorithms
  • Java
  • iOS
  • Android
  • Certifications
  • About Me

Lets Code Them Up!

  • Leetcode – Two Sum

    February 7th, 2020

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
    

    Brute force solution

    Take an item from array and look for target – that item in the array.

    This will be an O(n^2) solution as we are trying to find pair for each element by looping through the remaining elements.

    class TwoSum {
        public int[] twoSum(int[] nums, int target) {
            
            //loop through the array
            for(int i = 0; i < nums.length; i++){
                
                //fix the first element in the pair
                int first = nums[i];
                
                //loop through remaining elements to find the second 
                // element of the pair
                for(int j = i+1; j < nums.length; j++){
                    
                    //return the indices of the pair
                    if(first + nums[j] == target){
                        return new int[]{i, j};
                    }
                }
            }
            
            //return empty array if not pair found
            return new int[]{};
        }
    }
    

    Optimized

    Using a hashmap to look if target-key exists for every array element, if yes, we have found the pair. If no, then we add that key to hashmap.

    Time complexity is O(n), using only one loop to traverse array of size n and space complexity is also O(n), hashmap storing all elements of array of size n

    
    
    class TwoSumOptimized {
        public int[] twoSum(int[] nums, int target) {
            
            //Hashmap to store the nums[i] and i, where 0<i<nums.length
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            
            //loop through the array
            for(int num = 0; num < nums.length; num++){
                
                //find difference between target and nums[num]
                int compliment = target - nums[num];
                
                //if map contains the compliment then we have the result indices of num and map.get(compliment)
                if(map.containsKey(compliment)){
                    return new int[]{map.get(compliment), num};
                }
                
                //put nums[num] and num in map as key, value pair
                map.put(nums[num], num);
            }
            
            //return empty array if no pair found
            return new int[]{};
        }
    }
    

    Code – TwoSum.java and TwoSumOptimized.java

    Source – leetcode 

  • SQL – Types of Triangle

    February 5th, 2020

    Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table:

    • Equilateral: It’s a triangle with  sides of equal length.
    • Isosceles: It’s a triangle with  sides of equal length.
    • Scalene: It’s a triangle with  sides of differing lengths.
    • Not A Triangle: The given values of A, B, and C don’t form a triangle.

    Input Format

    The TRIANGLES table is described as follows:

    Each row in the table denotes the lengths of each of a triangle’s three sides.

    Sample Input

    Sample Output

    Isosceles 
    Equilateral 
    Scalene 
    Not A Triangle

    Solution

    1. Conditions for a triangle with A, B, C sides will be A+B>C, A+C>B, B+C>A
    2. Conditions for equilateral triangle is when A=B and B=C
    3. Conditions for isosceles triangle is either A=B or B=C or A=C
    4. If not 2 and 3 then scalene

    MySQL

    SELECT IF(A+B>C AND A+C>B AND B+C>A, 
           IF(A=B AND B=C, 'Equilateral', 
           IF(A=B OR B=C OR A=C, 'Isosceles', 
           'Scalene')), 
           'Not A Triangle') 
    FROM TRIANGLES;

     

    Oracle

    SELECT 
        CASE  
            WHEN NOT ((a+b>c) AND (a+c>b) AND (b+c>a)) THEN 'Not A Triangle'
            WHEN a = b AND b = c THEN 'Equilateral'
            WHEN a = b OR b = c OR c = a THEN 'Isosceles'
            ELSE 'Scalene'
        END AS result
    FROM triangles;

    Source – Hackerrank

  • Find distinct elements common to all rows of a matrix

    February 4th, 2020

    Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order.

    Examples:

    Input : mat[][] = {  {2, 1, 4, 3},
                         {1, 2, 3, 2},  
                         {3, 6, 2, 3},  
                         {5, 2, 5, 3}  }
    Output : 2 3
    
    Input : mat[][] = {  {12, 1, 14, 3, 16},
                         {14, 2, 1, 3, 35},  
                         {14, 1, 14, 3, 11},  
                         {14, 25, 3, 2, 1},
                         {1, 18, 3, 21, 14}  }
    Output : 1 3 14
    
    

    Python Solution

    def common_elements(matrix): 
      # declare dictionary and result array
      keys = {} 
      results = [] 
      
      #initialize dictionary with null list values
      for i in range(0, len(matrix)): 
        for j in range(0, len(matrix[i])): 
          if matrix[i][j] not in keys: 
            keys[matrix[i][j]] = []
      
      # update matrix[row][col] array with values
      for i in range(0, len(matrix)): 
        for j in range(0, len(matrix[i])): 
          if i not in keys[matrix[i][j]]:
            keys[matrix[i][j]].append(i)
      
      # if length of value of key is equal to matrix length add it to result
      for key in keys: 
          if len(keys[key]) == len(matrix):
            results.append(key)
    
      return results      
        
    matrix =   [[2, 1, 4, 3],
              [1, 2, 3, 2], 
              [3, 6, 2, 3],    
              [5, 2, 5, 3]]
              
    print(common_elements(matrix))

    Source – Geekforgeeks

    Code – Github

  • How to install and use MySQL on MAC

    January 25th, 2020

    Quite recently I had to install MySQL on my MAC laptop for a personal project. I was able to easily install the MySQL server. But I ran into several issues while trying to connect to the MySQL server on MAC. Thanks to this post by Akansha Jain on medium, I am able to use MYSQL on my system from command line. Her post describes almost all the errors you encounter while installing and using MySQL server on MAC and how to resolve them.   

  • Non Consecutive Ones

    September 22nd, 2019

    Question

    Given a positive integer `n`, return an array of all the binary strings of length n that *DO NOT* contain consecutive `1`s.
    
    ```
    Input: n (Integer)
    Output: [Str] (Array of Strings)
    ```
    
    # Example
    
    ```
    Input: 2
    Output: ["00", "01", "10"]
    
    Input: 3
    Output: ["000", "001", "010", "100", "101"]
    ```
    
    # Constraints
    
    ```
    Time Complexity: O(2^N)
    Auxiliary Space Complexity: O(2^N)
    ```

    Solution

    public static ArrayList<String> result;
    	public static ArrayList<String> nonConsecutiveOnes(int n){
    		result = new ArrayList<String>();
    		nonConsecutiveOnesHelper("", n);
    		return result;
    	}
    	
    	private static void nonConsecutiveOnesHelper(String s, int n) {
    		
    		//base case
    		if(s.length() == n) {
    			result.add(s);
    			return;
    		}
    		
    		//string with '0' ending
    		nonConsecutiveOnesHelper(s+"0",n);
    		
    		if(!s.endsWith("1"))
    			nonConsecutiveOnesHelper(s+"1",n);
    	}
  • Capital Permutations

    September 22nd, 2019

    Question

    Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.  Return a list of all possible strings we could create.
    
    Examples:
    Input: S = "a1b2"
    Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
    
    Input: S = "3z4"
    Output: ["3z4", "3Z4"]
    
    Input: S = "12345"
    Output: ["12345"]
    Note:
    
    S will be a string with length between 1 and 12.
    S will consist only of letters or digits.

    Solution

    class Solution {
        public static List<String> permutations;
        public List<String> letterCasePermutation(String S) {
            permutations = new ArrayList<String>();
            permute(S, "", 0);
            return permutations;
        }
        
        private static void permute(String s, String sub, int depth){
            if(depth == s.length()){
                System.out.println(sub);
                permutations.add(sub);
                return;
            }
            if(Character.isDigit(s.charAt(depth)))
                permute(s, sub+s.charAt(depth), depth+1);
            else if(s.charAt(depth) == Character.toUpperCase(s.charAt(depth))){
                 permute(s, sub+s.charAt(depth), depth+1);
                permute(s, sub+Character.toLowerCase(s.charAt(depth)), depth+1);
            }else{
                permute(s, sub+s.charAt(depth), depth+1);
                permute(s, sub+Character.toUpperCase(s.charAt(depth)), depth+1);
            }
        }
          
    }
←Previous Page
1 … 10 11 12 13 14 … 22
Next Page→

Proudly powered by WordPress