2025-02-18 Daily Challenge

Today I have done leetcode's February LeetCoding Challenge with cpp.

February LeetCoding Challenge 18

Description

Construct Smallest Number From DI String

You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.

A 0-indexed string num of length n + 1 is created using the following conditions:

  • num consists of the digits '1' to '9', where each digit is used at most once.
  • If pattern[i] == 'I', then num[i] < num[i + 1].
  • If pattern[i] == 'D', then num[i] > num[i + 1].

Return the lexicographically smallest possible string num that meets the conditions.

 

Example 1:

Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.

Example 2:

Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.

 

Constraints:

  • 1 <= pattern.length <= 8
  • pattern consists of only the letters 'I' and 'D'.

Solution

class Solution {
  bool solve(
    string &result,
    const string &pattern,
    vector<bool> &used,
    int pos
  ) {
    if(pos == pattern.size()) return true;
    char begin = -1;
    char end = -1;
    if(pattern[pos] == 'I') {
      begin = result[pos] + 1;
      end = '9' + 1;
    } else {
      begin = '1';
      end = result[pos];
    }
    for(char c = begin; c < end; ++c) {
      if(used[c - '1']) continue;
      result[pos + 1] = c;
      used[c - '1'] = true;
      if(solve(result, pattern, used, pos + 1)) return true;
      used[c - '1'] = false;
    }
    return false;
  }
public:
  string smallestNumber(string pattern) {
    vector<bool> used(10);
    string answer;
    answer.resize(pattern.size() + 1);
    for(int i = 0; i < 9; ++i) {
      answer[0] = '1' + i;
      used[i] = true;
      if(solve(answer, pattern, used, 0)) break;
      used[i] = false;
    }
    return answer;
  }
};

// Accepted
// 104/104 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 73.43 % of cpp submissions (7.9 MB)