[LeetCode] 1718. Construct the Lexicographically Largest Valid Sequence (Python)

2025. 2. 16. 12:35·코딩 테스트
728x90

Problem

Solution

backtracking
heuristic (bruteforce)

처음에 한번에 이해하는게 어려웠던 문제.

조건은 아래와 같다.

1 ~ n 까지의 수 중에서

 

1) 1 은 한번만 나옴

2) 2~n 사이의 수는 2번 나옴

3) 사전순으로 정렬했을 때 a[i] == a[j] 에 대해서 |j-i| = n 이어야한다. 예를들어

     arr = [3, 1, 2, 3, 2] 에서 3은 2번 등장하고 두 거리는 3 이다. (arr[0] = 3, arr[3] = 3)

     2는 2번 등장하고 두 거리는 2이다. (arr[2] = 2, arr[4] = 2)

4) 사전순으로 정렬했을 때 가장 큰 배열 return

이때 처음에 숫자를 넣을 때 n (가장 큰 수) 부터 배열에 넣는게 유리하다.

 

 

Code

class Solution:
    def constructDistancedSequence(self, n: int) -> List[int]:
        size = 2*n - 1 # 총 배열 크기
        arr = [0] * size # init arr
        used = [False] * (n + 1) #check used number

        def dfs(idx):
            #arr이 다 채워지면 종료
            if idx == size:
                return True
            #arr가 이미 채워져있으면 다음으로
            if arr[idx] != 0:
                return dfs(idx+1)
            
            #가장 큰 숫자부터 채우기 n~1까지
            for num in range(n, 0, -1):
                #이미 사용한 숫자이면 continue
                if used[num]:
                    continue
                # 1은 한번만 사용
                if num == 1:
                    arr[idx] = 1
                    used[num] = True
                    if dfs(idx + 1):
                        return True
                    #backtracking
                    arr[idx] = 0
                    used[num] = False
                else:
                    #그 외 숫자는 2번 사용
                    if idx + num < size and arr[idx+num] == 0:
                        arr[idx] = arr[idx+num] = num
                        used[num] = True
                        if dfs(idx + 1):
                            return True
                        #backtracking
                        arr[idx] = arr[idx+num] = 0
                        used[num] = False
            #cannot append any num
            return False
        dfs(0)
        return arr

 

Complexity

Time Complexity

최악의 경우 모든 n에대해서 탐색하므로 O(N!) 가 걸리지만

조건에서 n <= 20이라서 20까지는 큰 수부터 체크하므로 무리없이 가능

 

Space Complexity

arr -> O(N)

used -> O(N)

재귀 -> O(N)

728x90
저작자표시 비영리 변경금지 (새창열림)

'코딩 테스트' 카테고리의 다른 글

[LeetCode] 1415. The k-th Lexicographical String of All Happy Strings of Length n (Python)  (0) 2025.02.19
[LeetCode] 2375. Construct Smallest Number From DI String (Python)  (0) 2025.02.18
[LeetCode] 2698. Find the Punishment Number of an Integer (Python)  (0) 2025.02.15
[LeetCode] CodeTestcaseTestcaseTest Result1352. Product of the Last K Numbers (Python)  (0) 2025.02.14
[LeetCode] 3066. Minimum Operations to Exceed Threshold Value II (Python)  (0) 2025.02.13
'코딩 테스트' 카테고리의 다른 글
  • [LeetCode] 1415. The k-th Lexicographical String of All Happy Strings of Length n (Python)
  • [LeetCode] 2375. Construct Smallest Number From DI String (Python)
  • [LeetCode] 2698. Find the Punishment Number of an Integer (Python)
  • [LeetCode] CodeTestcaseTestcaseTest Result1352. Product of the Last K Numbers (Python)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바
    CodingTest
    스프링부트
    kafka
    프로그래머스
    Python
    네트워크
    Spring
    java
    금융용어
    코딩테스트
    MySQL
    리트코드
    자료구조
    codility
    스프링
    이분탐색
    알고리즘
    pythoncodingtest
    코딩
    LeetCode
    카카오코테
    쿠버네티스
    db
    코테공부
    C++
    Kotlin
    코딜리티
    springboot
    코테
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[LeetCode] 1718. Construct the Lexicographically Largest Valid Sequence (Python)
상단으로

티스토리툴바