[Python] minimum moves needed for distinct array

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    You are given an array A containing N integers, where each integer is in the range [1..N]. In each move, you can increase or decrease the value of any element by 1, with the constraint that after each move, all numbers must remain in the range [1..N]. Your objective is to determine the minimum number of moves required to ensure that all elements in the array are distinct, meaning no number appears more than once in the array.

    You are tasked with implementing a function:

    int solution(int A[]);

    If the result exceeds 1,000,000,000, the function should return -1.

    solution([6, 2, 3, 5, 6, 3]) -> returns 4

    solution([1, 2, 1]) -> returns 2

    solution([2, 1, 4, 4]) -> returns 1

    adding my solution in python. It works for some cases but fails when input is lets say [2,1,5,5] because I am assuming the target array with have numbers as index + 1 which might not be a correct assumption. Need to write an efficient solution.

    def solution(A, changes = 0):
    # Step 1: Sort the array to align the elements in increasing order
    A.sort()
    # Step 2: Loop through the sorted array to calculate the 'changes' required
    for i in range(len(A)):
    # The expected value at index i is (i + 1), because we want the array to be [1, 2, 3, ...]
    # Calculate the absolute difference between the sorted value and the expected value
    changes += abs(A - (i + 1))
    # Step 3: Return the total number of changes
    return changes
    # Test cases
    print(solution([6, 2, 3, 5, 6, 3])) # Should return 4
    print(solution([1, 2, 1])) # Should return 2
    print(solution([2, 1, 4, 4])) # Should return 1

    Continue reading...

Compartilhe esta Página