4

I am trying to understand this line of code. What is the minus and tilde doing to r[e]?:

r = {}
for (e of s)
    r[e] = -~r[e] // What is this specific line assigning?

for (e in r)
    if (r[e] == 1)
        return e
return '_'

The problem this code solves is this(specific line is commented):

Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.

I understand the other lines except the commented one.

2
  • I don't think your code solves the problem you're describing. It assumes for (e in r) iterates properties in order of their creation. Commented Feb 23, 2018 at 6:47
  • This is a CodeFights interview problem and this solution was upvoted 30 times. I came up with a solution using indexOf/lastIndexOf, but looked at this and didn't understand. Here is the link : codefights.com/interview-practice/task/uX5iLwhc6L5ckSyNC/… Commented Feb 23, 2018 at 6:48

2 Answers 2

5

Tilde is a unary operator that takes the expression to its right performs this small algorithm on it

-(N+1) // N is the expression right to the tilde

So in your code it is incrementing r[e] with 1 (because of double negation).

See the examples below:

console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3

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

Comments

2

Tilde is the bitwise operator for NOT operation.

It takes in a number as operand, converts it into a 32 bit integer (refer IEEE_754-1985 and flips all the bits. 0 becomes 1, 1 becomes 0.

For example, if the number 5 is represented by

00000000 00000000 00000000 00000101

The number ~5 is the above, with the bits flipped

11111111 11111111 11111111 11111010

The decimal value of ~5 is (-6). This is also known as 2's complement. Since the most significant bits, which represent the sign of the number in JavaScript are flipped, the sign will always change. 2's complement causes the value of X to change to -(X+1)

Certain applications like engines, use bitwise data structures and bitwise operations play a role in those.

  • Bitwise OR (|)
  • Bitwise AND (&)
  • Bitwise NOT (~)
  • Bitwise XOR (^)
  • Bitwise LEFT SHIFT (<<)
  • Bitwise RIGHT SHIFT (>>)

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.