0% found this document useful (0 votes)
156 views1 page

Swap Two Numbers

This document discusses an approach to swapping two variables without using a third variable. It explains that the sum of the two variables can be stored in the first variable, and then the difference between the sum and the second variable assigns the value of the second variable to the first. The process is then repeated to assign the value of the first variable to the second, swapping the values without an extra variable. The time and space complexity of this approach are both O(1).

Uploaded by

Sa Dik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
156 views1 page

Swap Two Numbers

This document discusses an approach to swapping two variables without using a third variable. It explains that the sum of the two variables can be stored in the first variable, and then the difference between the sum and the second variable assigns the value of the second variable to the first. The process is then repeated to assign the value of the first variable to the second, swapping the values without an extra variable. The time and space complexity of this approach are both O(1).

Uploaded by

Sa Dik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Practice Guided Paths Interview Prep Challenges Knowledge Centre

Problem Submissions Solution Python (3.5)

Contribute a new Your Code Solution Report


Approach 1
approach
Approach 2 1 '''
2   Time complexity: O(1)
Contributed By 3   Space complexity: O(1).
Shrey Pansuria | Level 1
4 '''
5 ​
Using arithmetic operation 6 def swap(a, b):

We can swap values of two variables by using a


7    # Store the sum of the 2
third variable and instead of that, we can use the variables in a.
arithmetic operation to do it without an extra 8    a = a + b
variable.
9    # The differnce between a and b
The idea is to store the sum of two variables in the
first variable. Now if we assign the sum(which is 1st is equal to b.
variable) - 2nd variable in the 2nd variable then the 10    b = a - b
value in the 2nd variable will be equal to the 1st 11    # The difference between a and b
variable.
is a.
Again assign the first variable equal to the sum(first
variable) - 2nd variable(which has a value equal to 12    a = a - b
1st variable) so 1st variable will now have a value 13 ​
equal to 2nd variable.
14    return a, b

Time Complexity
O(1), 

The Time Complexity is O(1).

Space Complexity
O(1), 

The Space Complexity is O(1).

Suggest Edit

Console

Rate this Show Saving


problem Previous Next Hint Code... Run Code S

You might also like