Skip to main content
ratans6128
May 21, 2023
Solved

Find missing element in an array.

  • May 21, 2023
  • 6 replies
  • 0 views

Given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element.

Example 1:

Input:
N = 5
A[] = {1,2,3,5}
Output: 4

    Best answer by stefanhelzle0001

    a!localVariables(
      local!list: {1,2,3,5},
      difference(1 + enumerate(max(local!list)), local!list)
    )

    6 replies

    stefanhelzle0001
    Brainy
    May 21, 2023

    a!localVariables(
      local!list: {1,2,3,5},
      difference(1 + enumerate(max(local!list)), local!list)
    )

    amans0009
    May 22, 2023

    this code will not work for {1,2,3,4,5} where  N = 6  or for similar cases

    peter.lewis
    Employee
    May 22, 2023

    Just swap max(local!list) with your actual maximum number - try this:

    a!localVariables(
      local!maxNumber: 6,
      local!list: {1, 2, 3, 4, 5},
      difference(1 + enumerate(local!maxNumber), local!list)
    )

    amans0009
    May 22, 2023

    alternate approach ->

    a!localVariables(
      local!list: { 1, 2, 3, 4, 5, 6, 9, 8, 10, 11 },
      local!n: length(local!list) + 1,
      (local!n * (local!n + 1)) / 2 - sum(local!list)
    )

    May 22, 2023

    a!localVariables(
    local!number: { 1, 2, 3,4,5,7},
    local!n: length(local!number) ,
    ((local!n +1) *(local!n+2))/2 - sum(local!number),

    )