Retour aux défis
Facile 0 résolus 0 % de réussite

Hamming Distance

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

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

Exemples

Exemple 1
Entrée :
first = "ACCT"
second = "AGCA"

Sortie attendue :
expected = 2
Entrée :
std::string first = "ACCT";
std::string second = "AGCA";

Sortie attendue :
long long expected = 2;
Entrée :
string first = "ACCT";
string second = "AGCA";

Sortie attendue :
long expected = 2;

Explication

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

Exemple 2
Entrée :
first = "GATT"
second = "GATT"

Sortie attendue :
expected = 0
Entrée :
std::string first = "GATT";
std::string second = "GATT";

Sortie attendue :
long long expected = 0;
Entrée :
string first = "GATT";
string second = "GATT";

Sortie attendue :
long expected = 0;

Explication

All four positions match, so no differences are counted.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.