Single non-repeating number

    by nikoo28

    Let us suppose you are given an array of integers. The special thing about this array is that all numbers are repeated twice except one. Find the single non-repeating number.

    Example 1:
    Input: [2, 1, 1]
    Output: 2

    Example 2:
    Input: [4, 5, 5, 2, 2]
    Output: 4

    Problem statement:

    You are given an array of all positive integers. All the integers are repeated exactly twice except one. We need to find that number with a linear time complexity and using the minimum space possible.

    Brute Force Method:

    When tackling such problems, it is always a good idea to find a working solution first and then try to optimize it. The most obvious solution would be to iterate through the entire array one element at a time. If we find that integer somewhere in between, it means it is occurring twice. If we reach the end of the array and no we don’t find any occurrence, it means that is the unique element, and hence the answer.

    But, if you think about this method, it is very much time consuming. What if the unique element in the array is at the very end? We would have been wasting so much time to look for other elements in the array. This would end up in a worst time complexity of O(n^2). Certainly there is an efficient way to solve it.

    Optimized Method:

    We can reduce the time complexity, by using a hash-map for each integer, and the frequency of each element.

    • iterate over each element and create a map to store how many times the element has occurred.
    • Iterate over the hash-map and look for the integer that has the frequency ‘1’. The corresponding integer would be the single non repeated element.
    • This would solve the problem in O(n) time with a space complexity of O(1).
    Fig: Converting array to hash-map
    Space Optimized Method:

    A space optimized solution means not taking up extra space to evaluate the result. The above problem can be solved in O(1) extra space but it requires some mathematical magic of bitwise operators. Refer to “Some bitwise operations you should know” to read more about bitwise operators. We would be using 2 properties of XOR operator ( ^ ) or \oplus to solve this problem.

    A \oplus A = 0
    A \oplus 0 = A

    This implies that any integer when XOR’d with itself would give the result to be 0, and if any integer is XOR’d by 0 would give the result as the number itself. One must also know that XOR operator is commutative by nature.

    Algorithm:

    A step-wise approach would look like:

    • Initialize a variable result that would store the XOR’d result of all integers.
    • Iterate through the array from start to end.
    • XOR the new element with the previous result.
    • Once the loop completes, you would have the single non-repeating element. This approach would work because all the other elements in the array would have XOR’d to 0.
    Code:
    // method to find the unique number
    public int singleNumber(int[] nums) {
    
      // variable to store the xor result of all integers
      int sing = nums[0];
    
      // start a loop for all elements
      for (int i = 1; i < nums.length; i++) {
    
        // xor the element with the previous result
        sing = sing ^ nums[i];
      }
    
      // return the result
      return sing;
    }
    Code language: Java (java)

    Time Complexity: O(n)
    Space Complexity: O(1)

    A working solution is available here.
    The code is also available on Github.
    A similar problem is available on Leetcode.

    Video Explanation:
    YouTube player
    0 comments
    1 FacebookTwitterLinkedinWhatsappEmail
  • Strings

    Longest Palindromic Substring

    by nikoo28
    4 minutes read

    Let us suppose that we are given a string ‘str’. You need to find out the longest palindrome as a substring. Note that the elements of the string should be contagious. Example 1:Input: “aaebabad”Output: “bab”Note: “aba” is also a valid answer Example 2:Input: “cbeereed”Output: “eeree” Terminology: Palindrome: A palindrome is a type of string that reads the same when reading left to right and right to left. An example of a palindrome can be “level”, “racecar”, “kayak” etc. Sub-string: A string formed formed using the characters of the string that …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array A, find the sum of maximum sum of two non-overlapping subarrays, with lengths L and M.In other words, return the largest V for which V = (A[i] + A[i+1] …. A[i+L-1]) + (A[j] + A[j+1] …. A[j+M-1])Input: A = {3, 8, 1, 3, 2, 1, 8, 9, 0}; L = 3, M = 2Output: 29 The problem statement is quite clear. We need to find 2 contiguous sub-arrays from an array Add the elements of both these arrays The sum should be the maximum possible sum …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    Array Nesting

    by nikoo28
    4 minutes read

    Question: Given a zero-indexed array ‘A’ of length ‘N’ which contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], …} subjected to a particular condition. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]],.. and so on. By that analogy, we stop adding elements as soon as we get a duplicate. Input: A = {5, 4, 0, 3, …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Strings

    CamelCase matching

    by nikoo28
    3 minutes read

    Question: Given a set of queries and a pattern, we need to determine if some of those queries can be made from the given pattern by adding one or more lower case character. Output a boolean array where array[i] says true, if the query is possible, else false. Input: queries= {“StudyAlgorithms”, “StudyAlgorithmsTest”, “StanAlluring”, “SimulationAlteration”, “StopStayAlive”}pattern = “StAl” Output: {true, false, true, true, false} Let us try to understand the output.The pattern defined to us is St*Al* (if we see it in terms of a regex) StudyAlgorithms can be made as …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    Container with maximum water

    by nikoo28
    4 minutes read

    Question: Let us suppose we have a two dimensional plane where the the length of lines determine the height of a container. We need to determine the maximum capacity of water this kind of an arrangement can hold. The heights are represented by an array. Input: [1, 8, 6, 2, 5, 4, 8, 3, 7] Output: 49 Let us try to visualize the problem at hand diagrammatically. Let the array be represented as: If we try to pour water from the top in the entire arrangement you can visualize that …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array, there is a largest element N. Check if that number is at least twice than all the other elements in the array. Return the index if it is, else return -1Input: {3, 6, 1, 0}Output: -1 6 is the largest integer, and for every other number in the array x,6 is more than twice as big as x. The index of value 6 is 1, so we return 1. Let us try to make one more exampleInput: nums = [1, 2, 3, 4] Output: -1Explanation: 4 …

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More