Tasks Details
easy
Find a symmetry point of a string, if any.
Task Score
100%
Correctness
100%
Performance
100%
Write a function:
def solution(S)
that, given a string S, returns the index (counting from 0) of a character such that the part of the string to the left of that character is a reversal of the part of the string to its right. The function should return −1 if no such index exists.
Note: reversing an empty string (i.e. a string whose length is zero) gives an empty string.
For example, given a string:
"racecar"
the function should return 3, because the substring to the left of the character "e" at index 3 is "rac", and the one to the right is "car".
Given a string:
"x"
the function should return 0, because both substrings are empty.
Write an efficient algorithm for the following assumptions:
- the length of string S is within the range [0..2,000,000].
Copyright 2009–2025 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Solution
Programming language used Python
Time spent on task 1 minutes
Notes
not defined yet
Code: 01:14:32 UTC,
java,
autosave
Code: 01:14:40 UTC,
py,
verify,
result: Passed
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# -*- coding:utf-8 -*-
# &Author AnFany
# Lesson 99:Future training
# P 99.2 StrSymmetryPoint
def solution(S):
"""
判断字符串S是否是中心对称的
:param S: 字符串
:return: 返回中心字符的下标或者-1
"""
length = len(S)
if length % 2 == 0:
return -1
if length == 1:
return 0
center = length // 2
if S[:center][::-1] == S[center+1:]:
return center
else:
return -1
Analysis
Code: 01:14:44 UTC,
py,
final,
score: 
100
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# -*- coding:utf-8 -*-
# &Author AnFany
# Lesson 99:Future training
# P 99.2 StrSymmetryPoint
def solution(S):
"""
判断字符串S是否是中心对称的
:param S: 字符串
:return: 返回中心字符的下标或者-1
"""
length = len(S)
if length % 2 == 0:
return -1
if length == 1:
return 0
center = length // 2
if S[:center][::-1] == S[center+1:]:
return center
else:
return -1
Analysis summary
The solution obtained perfect score.
Analysis
Detected time complexity:
O(length(S))
expand all
Correctness tests
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
expand all
Performance tests
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
1.
0.036 s
OK
1.
0.040 s
OK
1.
0.040 s
OK
2.
0.040 s
OK
3.
0.036 s
OK
1.
0.040 s
OK
2.
0.040 s
OK
3.
0.040 s
OK
4.
0.040 s
OK
5.
0.040 s
OK
6.
0.040 s
OK