DSA Factory
Free lessonsProgramming basics · Stage 6 · Text · Step 4

Comparing neighbours

Compare each letter with the one before it, and stop at the first surprise. About 9 minutes.

Letters have an order

Letters line up in the order of the alphabet, as in a dictionary. So you can ask which of two letters comes first. The letter b comes after a, and c comes after b. You can compare letters with less than and greater than, just like numbers.

A word is in alphabetical order when no letter comes before the one in front of it. "abbey" is in order, but "abca" is not, because the last a comes before the c.

Letters compare: in the order of the alphabet.
In code
"a" < "b"      # True
"c" < "b"      # False

Check each pair of neighbours

To check a whole word, look at each letter and the one just before it. Start from the second letter, because the first has nobody in front of it. If a letter comes before its neighbour, the word is out of order, and you can say no right away.

If you get to the end without finding a problem, the answer is yes. A word of one letter, or no letters, is in order, because there is nothing to compare.

Start at the second letter, so there is always one before it.
In code
for i in range(1, len(s)):
    if s[i] < s[i - 1]:
        return False
return True
Is "abca" in order?
a
0
b
1
c
2
a
3
beforenow
now
b
before
a

Compare b with the letter before it, a. b doesn't come before a, so that's fine.

Move 1 of 3
Quick check

Is the word "abbey" in alphabetical order, where a repeated letter is fine?

  1. AYes
  2. BNo, because b is repeated
  3. CNo, because it ends in y
Show the answer

Yes. a, b, b, e, y: no letter comes before the one in front of it.

Your problem

Is it in order?

Return true if the letters of the word are in alphabetical order, where a repeated letter is fine (each letter is the same as or after the one before it). Words of 0 or 1 letters are in order.

Example
s = "abbey" → true

0 ≤ length of s ≤ 1,000 · lowercase letters only

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding