Question d’entretien chez Rafael

Reverse a string without extra memory space. (Only one char)

Réponse à la question d'entretien

Utilisateur anonyme

10 janv. 2025

You dont even need one character. I would show the solution with and without a character. Lets say we do have a character - Lets call the saved character 'saved' and the characters in the array in positions [i] and [length - 1 - i] - A and B respectively. so lets just change 'saved' with the value of A, and change A with the value of B, and change B with the value of 'saved'. ANOTHER way to do this and it will be the same method for no-character requirement - 'saved' = XOR between A and B = A ^ B. Now, we know that (A ^ B) ^ B = A, or basically A ^ 0 = A (Because the commutative & negation properties of XOR) so now when we have the XOR result in hand (in 'saved') we can just XOR again with any of them (A or B) and get the OTHER value, that we need to be switched for, In other words (TL;DR -) we got (A ^ B) value in 'saved', now we can just (A ^ B) ^ B = A, or (A ^ B) ^ A = B. So we will set A as the value - ('saved' ^ A) to get B and we will set B as the value ('saved' ^ B) to get A Done! How should we do it with no character? Just make A or B to be the 'saved' container. lets pick A to be changed. So - A changed to : new_A = orig_A ^ orig_B. then change B to : new_A ^ orig_B = orig_A then change A to : new_A ^ new_B = orig_B kablam