Skip to content

Commit f0f3641

Browse files
Merge pull request #42 from BhavikDhandhalya/patch-1
added find permutation
2 parents 2f28ef1 + f06e792 commit f0f3641

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Arrays/Find Permutation.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Solution by : Bhavik Dhandhalya
3+
Given a positive integer n and a string s consisting only of letters D or I, you have to find any permutation of first n positive integer that satisfy the given input string.
4+
5+
D means the next number is smaller, while I means the next number is greater.
6+
7+
Notes
8+
Length of given string s will always equal to n - 1
9+
Your solution should run in linear time and space.
10+
11+
Input 1:
12+
13+
n = 3
14+
s = ID
15+
Return: [1, 3, 2]
16+
17+
Solution Complexity : O(N) time and O(1) space
18+
Refer this URL for lexicographically smaller permutation solution:
19+
https://leetcode.com/articles/find-permutation/
20+
*/
21+
22+
vector<int> Solution::findPerm(const string A, int B) {
23+
vector < int > ans;
24+
int n = A.length();
25+
int maxi = n + 1, mini = 1;
26+
for (int i = 0; i < n; i++) {
27+
if (A[i] == 'I') ans.push_back(mini++);
28+
if (A[i] == 'D') ans.push_back(maxi--);
29+
}
30+
ans.push_back(maxi);
31+
return ans;
32+
}

0 commit comments

Comments
 (0)