62.4k views
0 votes
Let A be a vector of n integers, each between 1 and n. The values in A are all distinct excepts for one, which appears twice. Let k be the value that is repeated twice 1. Write pseudocode for an efficient algorithm that returns k. Your score depends on the correctness and efficiency of your algorithm 2. Compute the running time of your algorithm and express it using asymptotic notation.

1 Answer

5 votes

Final answer:

To find the repeated number in an array of n distinct integers where one number is repeated, initialize a counting array, loop through the array, increment corresponding counts, and return the number with a count of 2. The running time of the algorithm is O(n).

Step-by-step explanation:

Given an array A with n distinct integers except one, which is repeated, the algorithm to find the repeated number k is as follows:

  1. Initialize an array count of size n + 1 to zero.
  2. Loop through the elements of array A.
  3. For each element A[i], increment count[A[i]].
  4. If count[A[i]] becomes 2, return A[i] as k.

The running time of this algorithm is O(n) as it makes a single pass through the array of size n.

User Miguelitomp
by
8.2k points