Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The solution needs to be O(n) time and with space O(1). This leaves out sorting and the space O(1) requirement is a hint that you probably should make a hash of the strings and compare them.</p> <p>If you have access to a prime number list do as cheeken's solution.</p> <p><em>Note: If the interviewer says you don't have access to a prime number list. Then generate the prime numbers and store them. This is O(1) because the Alphabet length is a constant.</em></p> <p>Else here's my alternative idea. I will define the Alphabet as = {a,b,c,d,e} for simplicity. The values for the letters are defined as:</p> <pre><code>a, b, c, d, e 1, 2, 4, 8, 16 </code></pre> <p><em>note: if the interviewer says this is not allowed, then make a lookup table for the Alphabet, this takes O(1) space because the size of the Alphabet is a constant</em></p> <p>Define a function which can find the distinct letters in a string.</p> <pre><code>// set bit value of char c in variable i and return result distinct(char c, int i) : int E.g. distinct('a', 0) returns 1 E.g. distinct('a', 1) returns 1 E.g. distinct('b', 1) returns 3 </code></pre> <p>Thus if you iterate the string "aab" the distinct function should give 3 as the result</p> <p>Define a function which can calculate the sum of the letters in a string.</p> <pre><code>// return sum of c and i sum(char c, int i) : int E.g. sum('a', 0) returns 1 E.g. sum('a', 1) returns 2 E.g. sum('b', 2) returns 4 </code></pre> <p>Thus if you iterate the string "aab" the sum function should give 4 as the result</p> <p>Define a function which can calculate the length of the letters in a string.</p> <pre><code>// return length of string s length(string s) : int E.g. length("aab") returns 3 </code></pre> <p>Running the methods on two strings and comparing the results takes O(n) running time. Storing the hash values takes O(1) in space.</p> <pre><code> e.g. distinct of "aab" =&gt; 3 distinct of "aba" =&gt; 3 sum of "aab =&gt; 4 sum of "aba =&gt; 4 length of "aab =&gt; 3 length of "aba =&gt; 3 </code></pre> <p>Since all the values are equal for both strings, they must be a permutation of each other.</p> <p><strong>EDIT</strong>: The solutions is not correct with the given alphabet values as pointed out in the comments.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload