-3

Ques. 1.) I was writing a code to swap two numbers using a temp variable. I don't know how this temp variable will affect the space complexity in this case. Below is the code.

public void swap(int a, int b){
   int temp;
   temp = a;
   a = b;
   b = temp;
}

Ques. 2) How does using these extra variables like temp have an affect on space complexity in any function in general code practice?

8
  • I think that would be helpful stackoverflow.com/questions/36363550/… Commented Jan 8, 2021 at 16:46
  • 1) How do you solve it without the temp variable? 2) Can you give any way that adding a new variable does not increase space complexity? Commented Jan 8, 2021 at 16:47
  • 4
    1. The method won't actually swap the variables for the caller. 2. It's O(1). Commented Jan 8, 2021 at 16:47
  • An int is around four bytes on typical platforms. Looking at the space impact of the temp variable like an extreme microoptimization at best, unless you're somehow severely memory-constrained. Commented Jan 8, 2021 at 16:49
  • 2
    @RandomCoder_01 that is actually a code smell rules.sonarsource.com/java/type/Code%20Smell/RSPEC-1450 . And the space used by local variable will be almost immediately available for reuse after the method is gone. Commented Jan 8, 2021 at 17:14

1 Answer 1

1

General Answer: No, this does neither affect space- nor time-complexity

Space complexity is to declare, how how much space is used, when the algorithm has to process a lot (converging to infinity) of data. Since this temp variable is just used in the scope of this method, this would not affect the space in a space-complexity manner.

This article explains the topic quite good => https://www.baeldung.com/cs/space-complexity

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.