title: How to find number of operations required to get Kaprekar constant?
body: <p>Problem statement:</p>
  <blockquote>
  <p>Harry got a letter from Hogwarts School to join the wizardry. This letter consists of a magical key (6174) and a 4-digit number n with at least two distinct digits. Harry has to count in how many steps this number n can be converted to magical key invented by professor Dumbledore with this procedure as follows:</p>
  </blockquote>
  <pre><code>For example:
  N = 1234
  Step 1: x = 4321 y= 1234 =&gt; n = x-y =&gt; 3087
  Step 2: x = 8730 y= 0378 =&gt; n = x-y =&gt; 8352
  Step 3: x = 8532 y= 2358 =&gt; n = x-y =&gt; 6174 
  and you are done.
  
  Answer is 3
  </code></pre>
  <p>I am interested in knowing the minimum number of the above operations required to get <code>6174</code></p>
  <p>My solution which is kind of bfs gives TLE.</p>
  <pre class="lang-py prettyprint-override"><code>a = input()
  ref = a
  b = 0
  while(ref != &quot;6174&quot;):
      b=b+1
      ref=list(ref)
      num1=&quot;&quot;.join(sorted(ref))
      num2=&quot;&quot;.join(sorted(ref, reverse = True))
      num1=int(num1)
      num2=int(num2)
      diff=num2-num1
      ref=str(diff)
  print(b)
  </code></pre>
  <p>Is it possible to reduce time complexity?</p>