Easy 0 solved 0% acceptance

Hamming Distance

Compare two DNA strings position by position and count the differences.

What you'll learn

  • Compare two strings position by position
  • Count mismatches
  • Validate equal lengths

Problem

Compare two DNA strings position by position and count the differences. Only characters at the same position are compared; do not insert, delete, or shift characters. No biology knowledge is needed.

Implement hamming_distance(first, second).

Input

first: The first DNA string.

second: The equal-length second DNA string.

Output

Return the number of positions with different characters.

Constraints

Both strings have the same length, from 0 to 100,000. Characters are uppercase A, C, G, or T.

Examples

Example 1
Input:
first = "ACCT"
second = "AGCA"

Expected output:
expected = 2
Input:
std::string first = "ACCT";
std::string second = "AGCA";

Expected output:
long long expected = 2;
Input:
string first = "ACCT";
string second = "AGCA";

Expected output:
long expected = 2;

Explanation

The second position is C versus G and the fourth is T versus A. The first and third match: two differences.

Example 2
Input:
first = "GATT"
second = "GATT"

Expected output:
expected = 0
Input:
std::string first = "GATT";
std::string second = "GATT";

Expected output:
long long expected = 0;
Input:
string first = "GATT";
string second = "GATT";

Expected output:
long expected = 0;

Explanation

All four positions match, so no differences are counted.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Compare both strings one position at a time and count when the characters differ.

Hint 2

A single pass with paired iteration is enough; no rearranging or substring searches are needed.

Hint 3

Remember that equal-length inputs can still be empty, which should yield zero differences.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.