Problem


You are given an array of integers representing coordinates of obstacles situated on a straight line.

Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.

Find the minimal length of the jump enough to avoid all the obstacles.


Example


For inputArray = [5, 3, 6, 7, 9], the output should be
avoidObstacles(inputArray) = 4.

Check out the image below for better understanding:


Input/Output

  • [input] array.integer inputArray

    Non-empty array of positive integers.

    Guaranteed constraints:
    2 ≤ inputArray.length ≤ 10,
    1 ≤ inputArray[i] ≤ 40.

  • [output] integer

    The desired length.



Solution

def avoidObstacles(inputArray):

s = sorted(set(inputArray))

m = max(s)


for size in range(1, m+2):

steps = set([i for i in range(0, m+size+1, size)])

if len(steps.intersection(i)) == 0:

return step


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] isIPv4Address  (0) 2018.03.02
[Algorithm] arrayMaximalAdjacentDifference  (0) 2018.03.02
[Algorithm] areEquallyStrong  (0) 2018.03.02
[Algorithm] palindromeRearranging  (0) 2018.02.26
[Algorithm] arrayChange  (0) 2018.02.26

Problem


An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.

IPv4 addresses are represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255 inclusive, separated by dots, e.g., 172.16.254.1.

Given a string, find out if it satisfies the IPv4 address naming rules.


Example


  • For inputString = "172.16.254.1", the output should be
    isIPv4Address(inputString) = true;

  • For inputString = "172.316.254.1", the output should be
    isIPv4Address(inputString) = false.

    316 is not in range [0, 255].

  • For inputString = ".254.255.0", the output should be
    isIPv4Address(inputString) = false.

    There is no first number.


Input/Output

  • [input] string inputString

    Guaranteed constraints:
    1 ≤ inputString.length ≤ 30.

  • [output] boolean

    true if inputString satisfies the IPv4 address naming rules, false otherwise.



Solution

def isIPv4Address(inputString):

splt = inputString.split('.')

return len(splt) == 4 and all(i.isdigit() and 0 <= int(i) <= 255 for i in splt)

*splt : inputString을 점(dot)을 기준으로 나누어 반환한 값을 저장한 변수

'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] avoidObstacles  (0) 2018.03.02
[Algorithm] arrayMaximalAdjacentDifference  (0) 2018.03.02
[Algorithm] areEquallyStrong  (0) 2018.03.02
[Algorithm] palindromeRearranging  (0) 2018.02.26
[Algorithm] arrayChange  (0) 2018.02.26

Problem


Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.


Example


For inputArray = [2, 4, 1, 0], the output should be
arrayMaximalAdjacentDifference(inputArray) = 3.


Input/Output

  • [input] array.integer inputArray

    Guaranteed constraints:
    3 ≤ inputArray.length ≤ 10,
    -15 ≤ inputArray[i] ≤ 15.

  • [output] integer

    The maximal absolute difference.



Solution

def arrayMaximalAdjacentDifference(inputArray):

return max([abs(inputArray[i] - inputArray[i+1]) for i in range(len(inputArray) - 1)])


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] avoidObstacles  (0) 2018.03.02
[Algorithm] isIPv4Address  (0) 2018.03.02
[Algorithm] areEquallyStrong  (0) 2018.03.02
[Algorithm] palindromeRearranging  (0) 2018.02.26
[Algorithm] arrayChange  (0) 2018.02.26

Problem


Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.


Example


  • For yourLeft = 10yourRight = 15friendsLeft = 15 and friendsRight = 10, the output should be
    areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true;
  • For yourLeft = 15yourRight = 10friendsLeft = 15 and friendsRight = 10, the output should be
    areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true;
  • For yourLeft = 15yourRight = 10friendsLeft = 15 and friendsRight = 9, the output should be
    areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = false.


Input/Output

  • [input] integer yourLeft

    A non-negative integer representing the heaviest weight you can lift with your left arm.

    Guaranteed constraints:
    0 ≤ yourLeft ≤ 20.

  • [input] integer yourRight

    A non-negative integer representing the heaviest weight you can lift with your right arm.

    Guaranteed constraints:
    0 ≤ yourRight ≤ 20.

  • [input] integer friendsLeft

    A non-negative integer representing the heaviest weight your friend can lift with his or her left arm.

    Guaranteed constraints:
    0 ≤ friendsLeft ≤ 20.

  • [input] integer friendsRight

    A non-negative integer representing the heaviest weight your friend can lift with his or her right arm.

    Guaranteed constraints:
    0 ≤ friendsRight ≤ 20.

  • [output] boolean

    true if you and your friend are equally strong, false otherwise.



Solution

def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):

return sorted([yourLeft, yourRight]) == sorted([friendsLeft, friendsRight])


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] isIPv4Address  (0) 2018.03.02
[Algorithm] arrayMaximalAdjacentDifference  (0) 2018.03.02
[Algorithm] palindromeRearranging  (0) 2018.02.26
[Algorithm] arrayChange  (0) 2018.02.26
[Algorithm] areSimilar  (0) 2018.02.26

Problem


Given a string, find out if its characters can be rearranged to form a palindrome.


Example


For inputString = "aabb", the output should be
palindromeRearranging(inputString) = true.

We can rearrange "aabb" to make "abba", which is a palindrome.


Input/Output

  • [input] string inputString

    A string consisting of lowercase English letters.

    Guaranteed constraints:
    1 ≤ inputString.length ≤ 50.

  • [output] boolean

    true if the characters of the inputString can be rearranged to form a palindrome, false otherwise.



Solution

def palindromeRearranging(inputString):

stringCount = [inputString.count(i) % 2 for i in set(inputString)]


return sum(stringCount) <= 1


*stringCount : input된 문자열에서 중복값을 없애고, 해당 문자를 for문으로 반환한 값을 2로 나눈 나머지 값을 리스트로 저장

'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] arrayMaximalAdjacentDifference  (0) 2018.03.02
[Algorithm] areEquallyStrong  (0) 2018.03.02
[Algorithm] arrayChange  (0) 2018.02.26
[Algorithm] areSimilar  (0) 2018.02.26
[Algorithm] addBoarder  (0) 2018.02.26

Solution


You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.


Example

For inputArray = [1, 1, 1], the output should be
arrayChange(inputArray) = 3.


Input/Output

  • [input] array.integer inputArray

    Guaranteed constraints:
    3 ≤ inputArray.length ≤ 105,
    -105 ≤ inputArray[i] ≤ 105.

  • [output] integer

    The minimal number of moves needed to obtain a strictly increasing sequence from inputArray.
    It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type.



Solution

def arrayChange(inputArray):

count = 0

for i in range(len(inputArray) - 1):

if inputArray[i+1] <= inputArray[i]:

count += inputArray[i] - inputArray[i+1] + 1

inputArray[i+1] = inputArray[i] + 1


return count


*count : sequence하게 올라가야 하는 횟수를 저장한 변수


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] areEquallyStrong  (0) 2018.03.02
[Algorithm] palindromeRearranging  (0) 2018.02.26
[Algorithm] areSimilar  (0) 2018.02.26
[Algorithm] addBoarder  (0) 2018.02.26
[Algorithm] alternatingSums  (0) 2018.02.26

Problem


Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar.


Example


  • For a = [1, 2, 3] and b = [1, 2, 3], the output should be
    areSimilar(a, b) = true.

    The arrays are equal, no need to swap any elements.

  • For a = [1, 2, 3] and b = [2, 1, 3], the output should be
    areSimilar(a, b) = true.

    We can obtain b from a by swapping 2 and 1 in b.

  • For a = [1, 2, 2] and b = [2, 1, 1], the output should be
    areSimilar(a, b) = false.

    Any swap of any two elements either in a or in b won't make a and b equal.


Input/Output

  • [input] array.integer a

    Array of integers.

    Guaranteed constraints:
    3 ≤ a.length ≤ 105,
    1 ≤ a[i] ≤ 1000.

  • [input] array.integer b

    Array of integers of the same length as a.

    Guaranteed constraints:
    b.length = a.length,
    1 ≤ b[i] ≤ 1000.

  • [output] boolean

    true if a and b are similar, false otherwise.



Solution

def areSimilar(a, b):

return sorted(a) == sorted(b) and sum([i != j for i,j in zip(a,b)]) <= 2:


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] palindromeRearranging  (0) 2018.02.26
[Algorithm] arrayChange  (0) 2018.02.26
[Algorithm] addBoarder  (0) 2018.02.26
[Algorithm] alternatingSums  (0) 2018.02.26
[Algorithm] reverseParentheses  (0) 2018.02.20

Problem


Given a rectangular matrix of characters, add a border of asterisks(*) to it.


Example


For

picture = [&quot;abc&quot;,
           &quot;ded&quot;]

the output should be

addBorder(picture) = [&quot;*****&quot;,
                      &quot;*abc*&quot;,
                      &quot;*ded*&quot;,
                      &quot;*****&quot;]


Input/Output

  • [input] array.string picture

    A non-empty array of non-empty equal-length strings.

    Guaranteed constraints:
    1 ≤ picture.length ≤ 100,
    1 ≤ picture[i].length ≤ 100.

  • [output] array.string

    The same matrix of characters, framed with a border of asterisks of width 1.



Solution

def addBoarder(picture):

lst = []


lst.append("*" * len(picture[0] + 2))

for i in picture:

i = "*" + i + "*"

lst.append(i)

lst.append("*" * len(picture[0] + 2))


return lst


*lst : 애스터리스크(*)를 포함하여 저장할 리스트 변수입니다.

'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] arrayChange  (0) 2018.02.26
[Algorithm] areSimilar  (0) 2018.02.26
[Algorithm] alternatingSums  (0) 2018.02.26
[Algorithm] reverseParentheses  (0) 2018.02.20
[Algorithm] sortByHeight  (0) 2018.02.09

Example


Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.

You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.


Example


For a = [50, 60, 60, 45, 70], the output should be
alternatingSums(a) = [180, 105].


Input/Output

  • [input] array.integer a

    Guaranteed constraints:
    1 ≤ a.length ≤ 10,
    45 ≤ a[i] ≤ 100.

  • [output] array.integer



Solution

def alternatingSums(a):

lst = [a[i] for i in range(len(a)) if i == 0 or i % 2 == 0]

lst2 = [a[i] for i in range(len(a)) if a[i] not in lst]


return [sum(lst), sum(lst2)]


*lst : 짝수번째에 해당하는 숫자를 저장하는 리스트입니다.

*lst2 : 홀수번째에 해당하는 숫자를 저장하는 리스트입니다.



'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] areSimilar  (0) 2018.02.26
[Algorithm] addBoarder  (0) 2018.02.26
[Algorithm] reverseParentheses  (0) 2018.02.20
[Algorithm] sortByHeight  (0) 2018.02.09
[Algorithm] isLucky  (0) 2018.02.09

Problem


You have a string s that consists of English letters, punctuation marks, whitespace characters, and brackets. It is guaranteed that the parentheses in s form a regular bracket sequence.

Your task is to reverse the strings contained in each pair of matching parentheses, starting from the innermost pair. The results string should not contain any parentheses.


Example


For string s = "a(bc)de", the output should be
reverseParentheses(s) = "acbde".


Input/Output

  • [input] string s

    A string consisting of English letters, punctuation marks, whitespace characters and brackets. It is guaranteed that parentheses form a regular bracket sequence.

    Constraints:
    5 ≤ s.length ≤ 55.

  • [output] string



Solution

def reverseParentheses(s):

for i in range(len(s)):

if s[i] == '(':

start_idx = i

elif s[i] == ')':

end_idx = i

return reverseParentheses(s[:start_idx] + s[start_idx + 1:end_idx][::-1] + s[end_idx + 1:]

return s


*start_idx : 괄호가 시작하는 부분의 인덱스를 저장하는 변수입니다.

*end_idx : 괄호가 끝나는 부분의 인덱스를 저장하는 변수입니다.


괄호 사이에 위치한 문자를 거꾸로 배열하여 전체 문장을 반환하는 문제였습니다.

Input값에서 괄호가 한 번씩만 등장한다면 문제가 수월해지겠으나, 한 번씩만 등장한다는 전제조건은 없기 때문에 재귀 함수를 사용하여 문제를 해결하였습니다.


'Programming > Algorithm' 카테고리의 다른 글

[Algorithm] addBoarder  (0) 2018.02.26
[Algorithm] alternatingSums  (0) 2018.02.26
[Algorithm] sortByHeight  (0) 2018.02.09
[Algorithm] isLucky  (0) 2018.02.09
[Algorithm] commonCharacterCount  (0) 2018.02.09

+ Recent posts