S1Q1 · Check if String is Repeated Thrice¶
⚡ Quick Reference
Function: is_repeated_thrice(s: str) -> bool
Core idea: length must be divisible by 3, and all three equal-length parts must be identical.
def is_repeated_thrice(s: str) -> bool:
if len(s) % 3 != 0:
return False
part = len(s) // 3
return s[:part] == s[part:2*part] == s[2*part:]
Key rules:
- len(s) % 3 != 0 → immediately False
- Split into three equal slices and compare all three
- Chained == checks all three in one expression
Problem Statement¶
Problem
Write a function is_repeated_thrice(s) that returns True if s is formed by repeating the same substring exactly three times - i.e. its length is divisible by 3 and all three equal parts are identical.
Examples:
"abcabcabc"
True
"xyzxyzxyz"
True
"ababab"
True
"hello"
False
Understanding the problem¶
Two conditions must both be true:
len(s) % 3 == 0- length is divisible by 3s[:n] == s[n:2n] == s[2n:]- all three parts are identical (wheren = len(s) // 3)
"abcabcabc" → n=3
Part 1: s[0:3] = "abc"
Part 2: s[3:6] = "abc"
Part 3: s[6:9] = "abc"
All equal → True
"hello" → len=5, 5 % 3 = 2 ≠ 0 → False
Chained comparison: a == b == c
Python allows chaining equality checks: a == b == c is equivalent to a == b and b == c. This checks all three parts in one clean expression.
Tracing all examples¶
| String | len |
% 3 |
Part 1 | Part 2 | Part 3 | Result |
|---|---|---|---|---|---|---|
"abcabcabc" |
9 | 0 ✅ | "abc" |
"abc" |
"abc" |
True |
"aaaaaa" |
6 | 0 ✅ | "aa" |
"aa" |
"aa" |
True |
"xyzxyzxyz" |
9 | 0 ✅ | "xyz" |
"xyz" |
"xyz" |
True |
"ababab" |
6 | 0 ✅ | "ab" |
"ab" |
"ab" |
True |
"hello" |
5 | 2 ❌ | - | - | - | False |
Solution approaches¶
def is_repeated_thrice(s: str) -> bool:
if len(s) % 3 != 0:
return False
part = s[:len(s) // 3]
return part * 3 == s
Extract the first third, multiply it by 3, and check if it reconstructs s. Clean and readable - reads like the problem statement itself.
def is_repeated_thrice(s: str) -> bool:
if len(s) % 3 != 0:
return False
n = len(s) // 3
parts = [s[i*n:(i+1)*n] for i in range(3)]
return all(p == parts[0] for p in parts)
Splits into three parts using a list comprehension, then checks all are equal to the first. Scales naturally if the problem were generalised to k repetitions.
Key takeaways¶
part * 3 == s - the reconstruction trick
If a string is truly made of three identical parts, repeating the first third three times must give back the original. part * 3 == s is the most readable way to express this.
Chained equality: a == b == c
Python's chained comparisons work for equality too. s[:n] == s[n:2n] == s[2n:] is cleaner than two separate and conditions.
Check length first - short-circuit
The length check is O(1); slicing and comparing is O(n). Always put the cheap condition first so the expensive comparison is skipped when the string length is wrong.