Last active
July 8, 2025 07:59
-
-
Save sidsbrmnn/2309755a1f85da0c027dd21bfc9894b2 to your computer and use it in GitHub Desktop.
7-Eleven SDE 2 Interview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Problem Statement: | |
| * ------------------- | |
| * Given an array of integers and two distinct integers x and y, | |
| * the task is to find the minimum distance between any occurrence of x and y in the array. | |
| * The distance between two positions is defined as the absolute difference of their indexes. | |
| * | |
| * Example: | |
| * --------- | |
| * Input: | |
| * 8 | |
| * 2 5 7 5 4 4 2 7 | |
| * 7 2 | |
| * Output: | |
| * 1 | |
| */ | |
| #include <algorithm> | |
| #include <iostream> | |
| #include <vector> | |
| using namespace std; | |
| int minDistance(vector<int> &arr, int x, int y) { | |
| int N = arr.size(); | |
| int prev = -1; | |
| int prevVal = -1; | |
| for (int i = 0; i < arr.size(); i++) { | |
| if (arr[i] == x || arr[i] == y) { | |
| if (prev != -1 && arr[i] != prevVal) { | |
| dist = min(N, i - prev); | |
| } | |
| prev = i; | |
| prevVal = arr[i]; | |
| } | |
| } | |
| return dist; | |
| } | |
| int main(void) { | |
| int n; | |
| cin >> n; | |
| vector<int> arr(n); | |
| for (int i = 0; i < n; i++) { | |
| cin >> arr[i]; | |
| } | |
| int x, y; | |
| cin >> x >> y; | |
| cout << minDistance(arr, x, y) << endl; | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def minimumDistance(arr, x, y): | |
| dist = n | |
| prev = -1 | |
| prevValue = -1 | |
| for value, idx in enumerate(arr): | |
| if value == x or value == y: | |
| if prev != -1 and prevValue != value: | |
| dist = min(dist, idx - prev) | |
| prev = idx | |
| prevValue = value | |
| return dist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment