You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an array of integers and a target number, find all pairs of elements in the array whose values add up to the target and return the sum of their indices.
5
+
6
+
For example, given [2, 3, 4, 6, 8] and 10, you will find two valid pairs:
7
+
8
+
2 and 8 (2 + 8 = 10), whose indices are 0 and 4
9
+
4 and 6 (4 + 6 = 10), whose indices are 2 and 3
10
+
Add all the indices together to get a return value of 9.
=> i = 3 -> continue because used[3] = True -> skip
144
+
145
+
Final sum = 6
146
+
147
+
The use of j!=i
148
+
149
+
Here, index_map[compliment] is a list of all indices where the complement value occurs.
150
+
That list can include the current index i itself if arr[i] equals its own complement.
151
+
152
+
When does i == j happen
153
+
154
+
It happens when the element can pair with itself to reach the target.
155
+
156
+
Example 1: self-pair case
157
+
158
+
arr = [5]
159
+
target = 10
160
+
161
+
=> i = 0, val = 5
162
+
=> compliment = 10 - 5 = 5
163
+
=> index_map[5] = [0]
164
+
=> So j = 0 -> same as i.
165
+
166
+
If we didn't check j != i, we'd incorrectly count the element pairing with itself.
167
+
168
+
Example 2: Multiple identical values
169
+
170
+
arr = [5, 5]
171
+
target = 10
172
+
173
+
=> i = 0, val = 5, compliment = 5
174
+
=> index_map[5] = [0, 1]
175
+
=> loop over j:
176
+
=> j = 0 -> same as i -> skip because of j!=i
177
+
=> j = 1 -> valid pair -> summ += 0 + 1
178
+
=> Without j!=i, the first iteration would try to pair index 0 with itself
179
+
180
+
181
+
* Why it matters:
182
+
==> Correctness: Prevents self-paring unless there are actually two distinct elements.
183
+
==> Safety: Avoids double counting when the complement equals the value itself.
184
+
==> Logic: We only want pairs of two different indices.
185
+
186
+
* Key Takeaway:
187
+
==> i == j happens when the value equals its own complement (e.g., target = 10, value = 5).
188
+
==> The check j!=i ensures we don't pair an element with itself unless another copy exists.
189
+
==> Yes, i always moves forward, but the inner loop iterates over all indices of the complement, which can include i itself. That's why the guard is necessary.
190
+
191
+
192
+
The real time example:
193
+
194
+
arr = [5, 5, 10]
195
+
target = 10
196
+
197
+
we want pairs that sum to 10.
198
+
199
+
Step 1: Build index_map
200
+
201
+
index_map = {
202
+
5: [0, 1],
203
+
10: [2]
204
+
}
205
+
206
+
So value 5 occurs at indices 0 and 1, and value 10 occurs at index 2.
207
+
208
+
Step 2: Iterate over array
209
+
210
+
i = 0, val = 5
211
+
=> compliment = 10 - 5 = 5
212
+
=> index_map[5] = [0, 1]
213
+
=> Loop over j:
214
+
=> j = 0 -> same as i -> skip because of j!=i
215
+
=> j = 1 -> valid pair -> summ += 0 + 1
216
+
mark used[0] = True, used[1] = True
217
+
218
+
i = 1, val = 5
219
+
=> used[1] = True -> continue (skip this index)
220
+
i = 2, val = 10
221
+
=> compliment = 10 - 10 = 0
222
+
=> 0 not in index_map -> no pair
223
+
224
+
Step 3: Result
225
+
=> Only one valid pair: indices (0, 1) -> sum = 1
226
+
=> Without j!=i, the algorithm would have tried to pair index 0 with itself (0 + 0), which is invalid.
227
+
228
+
Which j!=i is essential
229
+
=> It prevents self-pairing when the value equals its own complement (like 5 + 5 = 10).
230
+
=> Ensures we only use two distinct indices.
231
+
=> Works correctly even when duplicates exist.
232
+
233
+
234
+
REAL-TIME ANALOGY:
235
+
236
+
Imagine you're pairing for a dance:
237
+
238
+
=> Each person has a "number" (array index).
239
+
=> The target is the total score tey must reach together.
240
+
=> If you allow someone to pair with themselves, they'd be dancing alone
241
+
- which breaks the rule.
242
+
That's why we check j!=i : to ensure two different people form the pair.
243
+
244
+
245
+
"continue" means skip this person if they're already paired, and j!=i means don't let some pair with themselves.
246
+
"""
247
+
248
+
249
+
defpairwise(arr, target):
250
+
251
+
used= [False] *len(arr) # Tracking used elements
252
+
total=0
253
+
254
+
foriinrange(len(arr)):
255
+
ifused[i]:
256
+
continue
257
+
forjinrange(i+1, len(arr)):
258
+
ifnotused[j] andarr[i] +arr[j] ==target:
259
+
total+=i+j
260
+
used[i] =True
261
+
used[j] =True
262
+
break# move to next i after finding a pair
263
+
264
+
returntotal
265
+
266
+
"""
267
+
This solution
268
+
269
+
=> Avoid double counting: Once an element is used in a pair, mark it as used so it doesn't get reused.
270
+
=> Efficiency: This is O(n^2) in worst case, but fine for moderate input sizes.
271
+
=> Correctness: Matches the example:
272
+
pair(2, 8) -> indices 0 + 4 = 4
273
+
pair(4, 6) -> indices 2 + 3 = 5
274
+
Total = 9
275
+
"""
276
+
277
+
"""
278
+
Key Takeaways
279
+
=> Brute force flaw: dictionary overwrites earlier pairs for same i.
280
+
=> Optimal flaw: dictionary stores only last index per value, and double counts pairs.
281
+
=> Correct fix: store all indices, and use a used array.
282
+
continue means: if this index is already paired, skip the rest of the loop body and move to the next iteration.
0 commit comments