Skip to content

Instantly share code, notes, and snippets.

@mahendrakalkura
Last active August 29, 2015 14:10
Show Gist options
  • Save mahendrakalkura/40e671bc9408bc4ef71c to your computer and use it in GitHub Desktop.
Save mahendrakalkura/40e671bc9408bc4ef71c to your computer and use it in GitHub Desktop.
An algorithm whose name I cannot remember!
# -*- coding: utf-8 -*-
def is_valid(s, q, p):
for k in xrange(0, q - p):
if s[k] != s[k + p]:
return False
return True
def solution(N):
s = bin(N)[2:]
q = len(s)
# (q / 2) + 1 => to handle both odd and even numbered cases of "s"
for p in xrange(1, (q / 2) + 1):
# This is not memory optimized
'''
if not [k for k in xrange(0, q - p) if s[k] != s[k + p]]:
return p
'''
# This is not stack optimized but still preferable over the previous one
if is_valid(s, q, p):
return p
return -1
assert solution(955) == 4
assert solution(102) == -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment