×

# RKABOL02 - Editorial

Author: ravikiran0606
Editorialist: ravikiran0606

EASY-MEDIUM

# PREREQUISITES:

RECURSION, BACK-TRACKING

# PROBLEM:

Given an integer N and a string S of length N. We need to generate a number with N+1 digits such that the following contraints holds true,

1) If the (i)'th character of the string is I, then (i)'th digit in the number > (i+1)'th digit in that number.
2) If the (i)'th character of the string is D, then (i)'th digit in the number < (i+1)'th digit in that number..
3) All the digits of the number are distinct and non-zero.

# EXPLANATION:

In this question, its very easy to find one of the cases for -1 that for all N>=9, the answer is always -1 since there are only 9 non-zero distinct digits from 1 to 9. Thus we can find solution only if N<=8. If the length of the string is N, we need to generate a number with N+1 digits with the given contraint. We can solve this using recursion and backtracking by trying all possible combinations of digits of length N+1 with the given constraint and print the lexicographically smallest one. If no solution exists we can print -1. The expected complexity is O(9n).

# AUTHOR'S SOLUTION:

Author's solution can be found here

41
accept rate: 0%

19.3k348495534

 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×15,005
×1,484
×19
×19
×19