imashutosh51

Untitled

Feb 3rd, 2026 (edited)
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. """
  2. Key intuition:
  3. We partition the array into four regions: 0s on the left, 1s in the middle,
  4. unknown elements to be processed, and 2s on the right.
  5.  
  6. Approach:
  7. Traverse the array once using three pointers. When a 0 is found, swap it to
  8. the left region; when a 2 is found, swap it to the right region; when a 1 is
  9. found, simply move forward. The middle pointer is not advanced after swapping
  10. a 2 because the incoming element is still unclassified.
  11.  
  12. Important insight:
  13. When swapping with the left pointer, the element coming into the middle
  14. position must be a 1 or 0, so it is safe to advance
  15. the middle pointer. However, when swapping with the right pointer, the incoming
  16. element can be 0, 1, or 2, so the middle pointer must stay to reprocess it.
  17. """
  18.  
  19.  
  20. class Solution:
  21. def sort012(self, arr):
  22. i=0
  23. j=0
  24. k=len(arr)-1
  25. while j<=k:
  26. if arr[j]==0:
  27. arr[i],arr[j]=arr[j],arr[i]
  28. i+=1
  29. j+=1 #here we are increasing j because left element is already processed and after swapping j with i will be having 1 because if K would have been there, it would have been gone to right side and if 0 it would have gone on the left side
  30. elif arr[j]==2:
  31. arr[j],arr[k]=arr[k],arr[j]
  32. k-=1
  33. else:
  34. j+=1
  35. return arr
  36.  
  37.  
Advertisement
Add Comment
Please, Sign In to add comment