Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions Python/uniqueNo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@

"""
uniqueNo.py

Find the unique number in an array where every other element appears exactly twice.

Input (stdin):
- First line: optional integer n (number of elements)
- Remaining tokens: integers (either n integers, or a list of integers)

Output:
- Prints the unique integer (the one that appears once) to stdout.

If no input is provided, a small demo runs.
"""

import sys
from typing import Iterable


def unique_number(arr: Iterable[int]) -> int:
"""Return the unique number when every other number appears exactly twice.

This uses XOR properties: x ^ x = 0 and x ^ 0 = x, so XORing all numbers
leaves the unique value.
"""
res = 0
for x in arr:
res ^= x
return res


def parse_input(stream) -> list:
data = stream.read().strip().split()
if not data:
return []
try:
nums = [int(tok) for tok in data]
except ValueError:
raise

# If first token is count and matches remaining length, skip it
if len(nums) >= 2 and nums[0] == len(nums) - 1:
return nums[1:]
Comment on lines +43 to +44
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical bug: ambiguous count detection can remove the unique number.

The heuristic nums[0] == len(nums) - 1 cannot reliably distinguish between a count prefix and an actual array element. This causes incorrect results when the unique number happens to be the first element AND equals len(nums) - 1.

Example failure case:

  • Input: 5 1 2 3 1 2 (no count, unique number is 5)
  • After parsing: nums = [5, 1, 2, 3, 1, 2]
  • Condition: nums[0] (5) == len(nums) - 1 (5) → True
  • Result: skips first element → [1, 2, 3, 1, 2] → returns 3 (incorrect, should be 5)

Recommended fix: Remove the ambiguity by requiring a consistent input format. Choose one of:

  1. Always require a count prefix:
 def parse_input(stream) -> list:
 	data = stream.read().strip().split()
-	if not data:
+	if len(data) < 2:
 		return []
 	try:
 		nums = [int(tok) for tok in data]
 	except ValueError:
 		raise
 
-	# If first token is count and matches remaining length, skip it
-	if len(nums) >= 2 and nums[0] == len(nums) - 1:
-		return nums[1:]
-	return nums
+	# Always treat first token as count
+	count = nums[0]
+	if count != len(nums) - 1:
+		raise ValueError(f"Count mismatch: expected {count} elements, got {len(nums) - 1}")
+	return nums[1:]
  1. Never use a count prefix:
 def parse_input(stream) -> list:
 	data = stream.read().strip().split()
 	if not data:
 		return []
 	try:
 		nums = [int(tok) for tok in data]
 	except ValueError:
 		raise
-
-	# If first token is count and matches remaining length, skip it
-	if len(nums) >= 2 and nums[0] == len(nums) - 1:
-		return nums[1:]
 	return nums

Update the docstring accordingly.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In Python/uniqueNo.py around lines 43 to 44, the heuristic checking if nums[0]
== len(nums) - 1 is ambiguous and can drop a legitimate first element (e.g.,
when the unique number equals len(nums)-1); fix by removing the count-prefix
handling and always treat the input list as the full array (i.e., delete the
conditional that strips nums[0] and ensure all callers/parsing expect no leading
count), and update the module docstring to state that inputs must not include a
count prefix (or alternatively, if you prefer the opposite, mandate and parse a
required count prefix explicitly—pick one and make the code and docstring
consistent).

return nums
Comment on lines +43 to +45
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): We've found these issues:

Suggested change
if len(nums) >= 2 and nums[0] == len(nums) - 1:
return nums[1:]
return nums
return nums[1:] if len(nums) >= 2 and nums[0] == len(nums) - 1 else nums



def main() -> int:
try:
arr = parse_input(sys.stdin)
except Exception:
print("Error: failed to parse input. Expected integers.")
return 1

if not arr:
demo = [2, 3, 5, 4, 5, 3, 4]
print("No input detected — running demo array:", demo)
print("Unique number:", unique_number(demo))
return 0

print(unique_number(arr))
return 0


if __name__ == '__main__':
raise SystemExit(main())