Pairwise Solution Feedback

Hey all, kind of feeling my way around the forums and I got a question… is there a central place to see the solutions other people came up with, like on Leetcode?

I find it useful after I solve a challenge, or when I get stuck, to see other people’s approaches.

If you have a solution to post for discussion, where is the best place?

For example, in the Javascript Pairwise challenge, I’ve found several solution posts, but they are a locked.

In my solution, for example, I used a Set, and it would be nice to be able to talk to people about the prose and cons of different approaches.

function pairwise(arr, arg) {
  const set = new Set();
  let sum = 0;

  for(let i = 0; i < arr.length; i++) {
    for(let j = i+1; j < arr.length; j++) {
        if(arg - arr[i] == arr[j]) {
          if(!set.has(i) && !set.has(j)) {
            set.add(i)
            set.add(j)
            sum += i + j
          }
        }
    }
  }
  
  return sum;
}

pairwise([1,4,2,3,0,5], 7);

Thanks!

We don’t have solution threads because we’ve discovered that they become dumping grounds with little to no discussion.

But it’s fine to create a thread to ask for feedback on your solution. Just remember to wrap your code in spoiler tags!

I think a Set is fine. You have to have some method to keep track of the indexes you have already used. I’m guessing a lot of people would probably just use a plain old object because they think it would be “faster” than using the Set methods. And it may be slightly faster, but this type of micro tuning is almost never worth it except for possibly huge datasets or when you really do need to get every microsecond out of your code.

I do think there is something you could do that just makes sense logically. Right now you are going through every index in the array in the outer for loop (represented by the variable i) and testing it against all the remaining indices in the inner for loop. But are there some i's that you don’t need to do this for? Once you find an i + j that adds up to the proper value, doesn’t that take both of those indices out of the running? So when the outer for loop eventually makes it to that j does it really need to run the inner for loop since that index has already been used up?

Likewise, once an i + j adds up correctly do you really need to continue running the inner for loop?