Your browser is not supported. Please, update your browser or switch to a different one. Learn more about what browsers are supported.

Check out Codility training tasks
Tasks Details
easy
Find a symmetry point of a string, if any.
Task Score
100%
Correctness
100%
Performance
100%

Task description

Write a function:

class Solution { public int solution(String 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 Java 8
Time spent on task 1 minutes
Notes
not defined yet
Task timeline
06:53:36
06:53:59

Away from Codility tab

0%

Code: 06:53:59 UTC, swift4, final, score:  100
import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

public func solution(_ S : inout String) -> Int {
    if S.count % 2 == 0 { return -1 }
    
    let mid = S.count / 2
    var start = 0
    var end = S.count - 1
    let s = Array(S).map({ String($0) })
    
    while start < mid {
        if s[start] != s[end] {
            return -1
        }
        
        start += 1
        end -= 1
    }
    
    return mid
}
Analysis summary

The solution obtained perfect score.

Analysis
Detected time complexity:
O(length(S))
expand all Example tests
example1
first example
OK
example2
second example
OK
expand all Correctness tests
extreme_empty_or_one
empty or one character strings
OK
symmetric
short symmetric strings
OK
even
even length or symmetric strings
OK
three_chars
3 characters (multiple runs)
OK
letters_a
letters 'a' only
OK
alphabet_symmetric
nontrivial symmetry, N = 51
OK
nonsymmetric_inside
mismatch close to the middle, N = 43
OK
nonsymmetric_outside
mismatch close to the ends, N = 43
OK
expand all Performance tests
large_nonsymmetric
nonsymmetric string, N = 100k+ + [aba]
OK
large_symmetric1
symmetric string, N=100k
OK
large_symmetric2
symmetric string, N=200k
OK
big_symmetric3
symmetric string, N=1M+
OK
big_nonsymmetric
nonsymmetric string, N = ~1M
OK
extreme_size
N = ~2M
OK