You are on page 1of 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