Skip to content

Conversation

@Anshuman7080
Copy link

Single Loop: Instead of a nested loop to find distances, we maintain the last seen index of each number in the array using a simple array last_seen. This allows us to compute the distance in constant time.

Memory Management: Dynamic memory allocation is used for arrays a, b, and last_seen to avoid stack overflow issues with large inputs.

Array Size: We assume the elements in a are in the range of 0 to 10000 (you might want to adjust this based on actual constraints).

Result Calculation: The second loop calculates the minimum distance only once.

Complexity:
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n) for the additional arrays used.
This optimized approach should perform much better for larger input sizes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant