Hackerrank - Mars Exploration Solution

Hackerrank - Mars Exploration Solution

Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help.

Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string, , determine how many letters of Sami's SOS have been changed by radiation.

For example, Earth receives SOSTOT. Sami's original message was SOSSOS. Two of the message characters were changed in transit.

Function Description

Complete the marsExploration function in the editor below. It should return an integer representing the number of letters changed during transmission.

marsExploration has the following parameter(s):

  • s: the string as received on Earth

Input Format

There is one line of input: a single string, .

Note: As the original message is just SOS repeated  times, 's length will be a multiple of .


  • will contain only uppercase English letters, ascii[A-Z].

Output Format

Print the number of letters in Sami's message that were altered by cosmic radiation.

Sample Input 0


Sample Output 0


Explanation 0

= SOSSPSSQSSOR, and signal length . Sami sent  SOS messages (i.e.: ).

Expected signal: SOSSOSSOSSOS
Recieved signal: SOSSPSSQSSOR
Difference:          X  X   X

We print the number of changed letters.

Sample Input 1


Sample Output 11

Explanation 1

= SOSSOT, and signal length . Sami sent  SOS messages (i.e.: ).

Expected Signal: SOSSOS     
Received Signal: SOSSOT
Difference:           X

We print the number of changed letters, which is .

Sample Input 2


Sample Output 2


Explanation 2

Since no character is altered, we print 0.

Solution in Python

s = input()
print(sum(1 for i in range(len(s)) if (i%3 in [0,2] and s[i]!="S") or (i%3==1 and s[i]!="O")))

Alternative one liner

print(sum((1 for i,v in enumerate(input()) if ((i+2)%3 and v!="S") or (not (i+2)%3 and v!="O"))))

Alternative solution

def marsExploration(s):
    for i in range(0, len(s), 3):
        if s[i+0]!="S": c+=1
        if s[i+1]!="O": c+=1
        if s[i+2]!="S": c+=1
    return c
s = input()

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]