HackerRank 문제풀이 Warm-up Challenges <python>

SeoYng·2021년 11월 14일
0
post-thumbnail

The HackerRank Interview Preparation Kit > Warm-up Challenges

  • Counting Valleys
  • Sales by Match
  • Jumping on the Clouds
  • Repeated String

🟢 Counting Valleys

문제링크

❗️ 시뮬레이션

def countingValleys(steps, path):
    # initialize
    cur_h, valley_cnt = 0, 0
    is_valley, is_in_spot = False, False
    # search
    for state in path:
        is_down = state == 'D'
        # check in spot
        if cur_h == 0 and not is_in_spot:
            is_valley = is_down
            is_in_spot = True
        # update cur_h
        cur_h = cur_h - 1 if is_down else cur_h + 1
        # check out spot
        if cur_h == 0 and is_in_spot:
            valley_cnt = valley_cnt + 1 if is_valley else valley_cnt
            is_in_spot = False

    return valley_cnt

🟢 Sales by Match

문제링크

❗️ set 사용

def sockMerchant(n, ar):
    sock_set = set()
    answer = 0
    for sock in ar:
        if sock not in sock_set:
            sock_set.add(sock)
        else:
            sock_set.remove(sock)
            answer += 1
    return answer

🟢 Jumping on the Clouds

문제링크

❗️ 탐욕법

def jumpingOnClouds(c):
    LAST_IDX = len(c) - 1
    SAFE, DANGER = 0, 1
    cur_idx, step_num = 0, 0
    while cur_idx < LAST_IDX - 1:
        can_two_step = c[cur_idx+2] == SAFE
        cur_idx = cur_idx + 2 if can_two_step else cur_idx + 1
        step_num += 1
    return step_num if cur_idx == LAST_IDX else step_num + 1

🟢 Repeated String

문제링크

❗️ 메모리 / 시간복잡도 주의

def repeatedString(s, n):
    STR_LEN = len(s)
    div, mod = divmod(n, STR_LEN)
    return s.count('a') * div + s[:mod].count('a')
profile
Junior Web FE Developer

0개의 댓글