avatarjb stevenard

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2509

Abstract

<span class="hljs-keyword">let</span> temp <span class="hljs-operator">=</span> allPermutations(string: newString)

    <span class="hljs-comment">// 3.</span>
    <span class="hljs-keyword">for</span> subString <span class="hljs-keyword">in</span> temp {
        result.insert(<span class="hljs-type">String</span>(char) <span class="hljs-operator">+</span> subString)
    }
}

<span class="hljs-comment">// 4.</span>
<span class="hljs-keyword">return</span> result

}</pre></div><h2 id="089b">Explanations:</h2><p id="9feb">1. As a recursive function, define first the base case (empty string or single character).</p><div id="c6e9"><pre><span class="hljs-keyword">guard</span> <span class="hljs-operator">!</span>string.isEmpty <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> <span class="hljs-type">Set</span><<span class="hljs-type">String</span>>() } <span class="hljs-keyword">guard</span> string.count <span class="hljs-operator">></span> <span class="hljs-number">1</span> <span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> <span class="hljs-type">Set</span><<span class="hljs-type">String</span>>([string]) }</pre></div><p id="044b">2. Iterate over all characters, keep the character at index i and recurse on the rest of the string (given string without the character at index i).</p><div id="8b1e"><pre><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span><span class="hljs-operator">..<</span>string.count { <span class="hljs-keyword">let</span> newString <span class="hljs-operator">=</span> string[<span class="hljs-number">0</span><span class="hljs-operator">..<</span>i] <span class="hljs-operator">+</span> string[i<span class="hljs-operator">+</span><span class="hljs-number">1</span><span class="hljs-operator">..<</span>string.count] <span class="hljs-keyword">let</span> temp <span class="hljs-operator">=</span> allPermutations(string: newString)</pre></div><p id="000c">3. Add to the results the concatenation of the character at index i plus all permutations gave by the recursive call.</p><div id="5d16"><pre><span class="hljs-keyword">for</span> subString <span class="hljs-keyword">in</span> temp { result.insert(<span class="hljs-type">String</span>(char) <span class="hljs-operator">+</span> subString) }</pre></div><p id="1202">4. Return the results.</p><div id="fa44"><pre><span class="hljs-keywor

Options

d">return</span> result</pre></div><h2 id="5417">Complexity:</h2><p id="4efb">- Time Complexity: The number of permutations for n elements is n!, so the time complexity is O(n!).</p><p id="0c0d">- Space Complexity: The number of permutations for n elements is n!, so the space complexity is O(n!).</p><h2 id="5a72">Test-cases:</h2><div id="90df"><pre><span class="hljs-keyword">public</span> <span class="hljs-keyword">func</span> <span class="hljs-title function_">testAllPermutations</span>() { <span class="hljs-built_in">assert</span>(allPermutations(string: <span class="hljs-string">""</span>).sorted() <span class="hljs-operator">==</span> [], <span class="hljs-string">"allPermutations 1 not equal"</span>) <span class="hljs-built_in">assert</span>(allPermutations(string: <span class="hljs-string">"ho"</span>).sorted() <span class="hljs-operator">==</span> [<span class="hljs-string">"ho"</span>, <span class="hljs-string">"oh"</span>], <span class="hljs-string">"allPermutations 2 not equal"</span>) <span class="hljs-built_in">assert</span>(allPermutations(string: <span class="hljs-string">"hey"</span>).sorted() <span class="hljs-operator">==</span> [<span class="hljs-string">"ehy"</span>, <span class="hljs-string">"eyh"</span>, <span class="hljs-string">"hey"</span>, <span class="hljs-string">"hye"</span>, <span class="hljs-string">"yeh"</span>, <span class="hljs-string">"yhe"</span>], <span class="hljs-string">"allPermutations 3 not equal"</span>) }</pre></div><h2 id="3b21">Follow-up:</h2><p id="6780">You could try to do it using an iterative way.</p><p id="4404"><a href="https://readmedium.com/algorithms-questions-429c4d84a98f"><< More Interview Questions</a> | <a href="https://readmedium.com/learn-data-structures-and-algorithms-with-swift-5-6-d9f36a4027dd">Data Structures and Algorythms >></a></p><div id="c879" class="link-block"> <a href="https://medium.com/@jbstevenard/membership"> <div> <div> <h2>Join Medium with my referral link — jb stevenard</h2> <div><h3>Read every story from jb stevenard (and thousands of other writers on Medium). Your membership fee directly supports jb…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*TEb_Qg9xmrjfkxhH)"></div> </div> </div> </a> </div></article></body>

1. All Permutations

Question: Write a recursive function that returns all permutations of a given string.

- For example, given “”, y should return [],

- For example, given “ho” should return [“ho”, “oh”],

- For example, given “hey” should return [“ehy”, “eyh”, “hey”, “hye”, “yeh”, “yhe”].

Hints:

- You can treat one character of the given string and call recursively to treat the remaining part,

- What are the primary cases to stop the recursion?

Solution:

func allPermutations(string: String) -> Set<String> {
    // 1.
    guard !string.isEmpty else { return Set<String>() }
    guard string.count > 1 else { return Set<String>([string]) }

    var result = Set<String>()
    for i in 0..<string.count {
        // 2.
        let char = string[i]
        let newString = string[0..<i] + string[i+1..<string.count]
        let temp = allPermutations(string: newString)

        // 3.
        for subString in temp {
            result.insert(String(char) + subString)
        }
    }

    // 4.
    return result
}

Explanations:

1. As a recursive function, define first the base case (empty string or single character).

guard !string.isEmpty else { return Set<String>() }
guard string.count > 1 else { return Set<String>([string]) }

2. Iterate over all characters, keep the character at index i and recurse on the rest of the string (given string without the character at index i).

for i in 0..<string.count {
  let newString = string[0..<i] + string[i+1..<string.count]
  let temp = allPermutations(string: newString)

3. Add to the results the concatenation of the character at index i plus all permutations gave by the recursive call.

for subString in temp {
  result.insert(String(char) + subString)
}

4. Return the results.

return result

Complexity:

- Time Complexity: The number of permutations for n elements is n!, so the time complexity is O(n!).

- Space Complexity: The number of permutations for n elements is n!, so the space complexity is O(n!).

Test-cases:

public func testAllPermutations() {
  assert(allPermutations(string: "").sorted() == [], "allPermutations 1 not equal")
  assert(allPermutations(string: "ho").sorted() == ["ho", "oh"], "allPermutations 2 not equal")
  assert(allPermutations(string: "hey").sorted() == ["ehy", "eyh", "hey", "hye", "yeh", "yhe"], "allPermutations 3 not equal")
}

Follow-up:

You could try to do it using an iterative way.

<< More Interview Questions | Data Structures and Algorythms >>

Data Structures
Algorithms
Coding
Programming
Permutations
Recommended from ReadMedium