Detect Voter Fraud in Python

Voter fraud detection involves identifying cases where a voter has cast multiple votes in an election. In Python, we can detect this by checking if any voter ID appears more than once in our voting records.

Each vote is represented as [candidate_id, voter_id], where the candidate_id is who they voted for and voter_id uniquely identifies the voter.

Problem Statement

Given a list of votes where each vote contains [candidate_id, voter_id], we need to determine if any voter has voted more than once.

For example, if the input is [[5, 1], [5, 0], [5, 4], [5, 3], [5, 0]], the output should be True because voter with ID 0 appears twice.

Algorithm

The approach uses a set to track unique voter IDs:

  • Create an empty set to store unique voter IDs
  • For each vote, add the voter ID to the set
  • Compare the size of the set with the total number of votes
  • If sizes differ, duplicate voters exist (fraud detected)

Implementation

class Solution:
    def detect_fraud(self, votes):
        unique_voters = set()
        for vote in votes:
            unique_voters.add(vote[1])  # Add voter_id to set
        return len(unique_voters) != len(votes)

# Test the solution
solution = Solution()
votes = [[5, 1], [5, 0], [5, 4], [5, 3], [5, 0]]
result = solution.detect_fraud(votes)
print(f"Fraud detected: {result}")
Fraud detected: True

Alternative Approach Using Collections

We can also use Counter to count occurrences of each voter ID:

from collections import Counter

def detect_fraud_counter(votes):
    voter_ids = [vote[1] for vote in votes]
    voter_count = Counter(voter_ids)
    return any(count > 1 for count in voter_count.values())

# Test with the same data
votes = [[5, 1], [5, 0], [5, 4], [5, 3], [5, 0]]
result = detect_fraud_counter(votes)
print(f"Fraud detected: {result}")

# Show which voters voted multiple times
voter_ids = [vote[1] for vote in votes]
voter_count = Counter(voter_ids)
duplicate_voters = [voter_id for voter_id, count in voter_count.items() if count > 1]
print(f"Duplicate voters: {duplicate_voters}")
Fraud detected: True
Duplicate voters: [0]

How It Works

The set-based approach works because sets only store unique elements. When we add voter IDs to a set:

  • First occurrence of voter ID 0 gets added
  • Second occurrence of voter ID 0 is ignored (already in set)
  • Final set size (4) is less than total votes (5)
  • This difference indicates duplicate voting

Conclusion

Using a set to track unique voter IDs provides an efficient O(n) solution for fraud detection. The Counter approach offers additional insights by showing which specific voters cast multiple votes.

Updated on: 2026-03-25T10:20:10+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements