Posts

Showing posts from March, 2022

Binary Tree Traversal

  public class TreeNode { Integer value ; TreeNode left ; TreeNode right ; public TreeNode(Integer value) { this . value = value; } public Integer getValue() { return value ; } public void setValue(Integer value) { this . value = value; } public TreeNode getLeft() { return left ; } public void setLeft(TreeNode left) { this . left = left; } public TreeNode getRight() { return right ; } public void setRight(TreeNode right) { this . right = right; } } public class TreeTraversal { public static TreeNode createTree() { TreeNode rootNode = new TreeNode( 9 ); TreeNode node1 = new TreeNode( 7 ); TreeNode node2 = new TreeNode( 10 ); TreeNode node3 = new TreeNode( 3 ); TreeNode node4 = new TreeNode( 8 ); rootNode.setLeft(node1); rootNode.setRight(node2); node1.setLeft(node3); node1.setRight(node

Sliding Window Algorithm

Image
The main idea behind the sliding window technique is to convert two nested loops into a single loop. Usually, the technique helps us to reduce the time complexity from O(n^2) to O(n). The condition to use the sliding window technique is that the problem asks to find the maximum (or minimum) value for a function that calculates the answer repeatedly for a set of ranges from the array. Namely, if these ranges can be sorted based on their start, and their end becomes sorted as well, then we can use the sliding window technique. Let’s start with a problem for illustration where we can apply this technique –  Given an array of integers of size ‘n’. Our aim is to calculate the maximum sum of ‘k’  consecutive elements in the array. Input  : arr[] = {100, 200, 300, 400}          k = 2  Output : 700 Input  : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}          k = 4 Output : 39 We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. Input  : arr[] = {2, 3}          k = 3 Output : Invalid The

System Design URL Shortening Service

Image
URL shortening services like  bit.ly  or  TinyURL  are very popular to generate shorter aliases for long URLs. You need to design this kind of web service where if a user gives a long URL then the service returns a short URL and if the user gives a short URL then it returns the original long URL.  For example, shortening the given URL through TinyURL:  https://www.interviewready.org/get-your-dream-job-with /?ref=leftbar-rightbar We get the result given -  https://tinyurl.com/y7vg2xjl Requirement Before you jump into the solution always clarify all the assumptions you’re making at the beginning of the interview. Ask questions to identify the scope of the system. This will clear the initial doubt, and you will get to know what are the specific detail interviewer wants to consider in this service.  Given a long URL, the service should generate a shorter and unique alias of it. When the user hits a short link, the service should redirect to the original link. Links will expire after a stan

Database Selection

Image

Caching

Image
What is a cache? A cache is a component that stores portions of data that would otherwise either take a long time to calculate/process. Caches may also originate from another underlying backend system, where caching is used to prevent additional requests for round trips for frequently used data. Caching can be used to improve performance or reduce application latencies in both these cases. A cache hit means the data required for the request is in the cache and is served from the cache. A cache miss means the data required for the request is not in the cache and would need to be computed by the backend systems.  Why we should cache?? 1) Reduce network calls. (Store data in cache and return that data to user instead to hit the DB) 2) Avoid repeated computations. (Suppose we want average age of employees, its a costly operation, we should store it in cache) 3) Reduce DB load. 4) Increase the response time. Cache Policy -  When I have to add data ad when we have to evict the data. 1) We c

Largest Pair Sum

Iterate the list and store the max element in J and add with the elements in the list to check if it greater than SUM. public class LargestPairSum { public static void main(String args[]) { int arr[] = {- 1 , 3 , 5 , - 6 , 8 , - 9 , 10 , 4 , - 2 , 7 }; largestPairSum (arr, arr. length ); } private static int largestPairSum( int [] arr, int n) { int j = 0 ; int max = n == 1 ? arr[ 0 ] + arr[ 1 ] : arr[ 0 ]; for ( int i = 0 ; i < n; i++) { int sum = arr[j] + arr[i]; if (sum > max) { max = sum; if (arr[j] < arr[i]) { j = i; } } } System. out .println( "Max--" + max); return max; } }

Find second largest pair

 First find 3 largest numbers and the sum of first and third integer is the 2nd largest number. The size of Array should be greater than 3. public class FindSecondLargestPair {     public static void main(String args[]) {         int[] nums = {-1, 3, 5, -6, 8, -9, 10, 4, -2, 7};         secondLargestPair(nums, nums.length);     }     public static void secondLargestPair (int[] arr, int arr_size) {         int i, first, second, third;         /* There should be atleast three elements */         if (arr_size < 3)         {             System.out.print(" Invalid Input ");             return;         }         third = first = second = Integer.MIN_VALUE;         for (i = 0; i < arr_size ; i ++)         {             /* If current element is greater than             first*/             if (arr[i] > first)             {                 third = second;                 second = first;                 first = arr[i];             }             /* If arr[i] is in between first a

Find Permutations of a string

Image
 Example ABC -> [ABC, ACB, BAC, BCA, CBA, CAB] public class FindPermutations {     // COmplexity     // O(TIme to find one permutation * Number of permutations)     // O(n*n!)     public static void main(String args[]) {         permutate("abc", 0, 2);     }     public static void permutate(String s, int low, int high) {         if (low == high) {             System.out.println(s);             return;         }         for (int i = low; i <= high; i++) {             s = swap(s, low, i);             permutate(s, low + 1, high);             s = swap(s, low, i); //Back track to the previous string to get other permutations.Just similar of first step         }     }     private static String swap(String s, int index1, int index2) {         char[] charArray = s.toCharArray();         char char1 = charArray[index1];         charArray[index1] = charArray[index2];         charArray[index2] = char1;         return new String(charArray);     } }

Array Containing Duplicates

public class ArrayContainsDuplicate {     public static void main(String args[])     {         int[] nums = {1,2,3,1};         boolean returnValue = containsDuplicate(nums);         System.out.println("returnValue-->"+returnValue);     }     public static boolean containsDuplicate(int[] nums) {         if(nums.length==1) return false;         HashSet<Integer> hashSet = new HashSet<>();         for(int i =0; i<nums.length;i++)         {             if(!hashSet.add(nums[i]))return true;         }         return false;     } }

Find Loop in a Linked List

Image
 Problem Statement In this problem, we are given a linked list with a loop. We have to find the first node of the loop in the linked list. Problem Statement Understanding Let’s try to understand the problem statement with the help of examples. Suppose the given list is: According to the problem statement, we need to find the starting node of the loop. From the linked list, we can see that there is a loop in the linked list starting at node with value 3 and containing 3 nodes 3, 5, and 7. The last node of the loop points back to the first node of the loop. As node with value 3 is the first node of the loop, so we will return 3 as output. Approach and Algorithm (Floyd’s Cycle Detection) Our approach will be simple: 1) Firstly, we have to detect the loop in the given linked list. For detecting a loop in any linked list, we know the most efficient algorithm is the  Floyd Cycle detection Algorithm . 2) In Floyd's cycle detection algorithm, we initialize 2 pointers,  slow  and  fast . Bo