Skip to content

Instantly share code, notes, and snippets.

@Cijin
Last active April 11, 2022 04:46
Show Gist options
  • Save Cijin/53bd59f90abb0181aa998cb52d83fccb to your computer and use it in GitHub Desktop.
Save Cijin/53bd59f90abb0181aa998cb52d83fccb to your computer and use it in GitHub Desktop.
The negative nacy approach to solving logical or programming problems

The idea came to me while I was petting my cat of all times and I remembered an interview question that I was asked once that I royally cocked up. That interview has had the greatest impact on how I think as a developer or person. Why? Let me give more context first.

The interview question was simple, it was a bracket matching question similar to what a linter would do. i.e. Given an input of string, check if an opening bracket is accompanied by a closing bracket and the order matters (I forgot about that "tiny" detail when I started to solve the problem 😁). Ex:

Input : {[( )])}
Output: True or Valid

Input: [[ ]}
Output: False or Invalid

Without going into many details, I learned to write psuedo-code that day and the problem solved itself.

Now back to the idea! That question got me thinking about something else. What if instead of looking for the right output, you only filter out the cases where the output is invalid. Kind of like returning early but deliberately looking for ways to return early.

As an example to the problem above, some early return cases:

Parse the string to remove any char that is not a bracket
 if the length of this string is not even, return false
 
 if a closing bracket is ecountered and the previous bracket
 was not an opening bracket of the same type, return 
 
 ... add more invalid cases here
 
 Finally, what you are left with, if anything, might (reality is a bitch for surprises πŸ˜‚) 
 be a valid string in which case you would return true
 
 Now for some reason if you still get a valid response for an invalid string
 It means you missed a case, which will the case most times till eventually
 you take into account all cases for that string, till the next edge case 
 unwelcomingly presents itself. Depending on the scope of the problem you are trying
 to solve.

I'm calling the method the Negative Nancy Approach. Now I'm not claiming that this is an original idea by any means, cause the odds are someone's already thought of this or is such a common approach that it doesn't need a name other than, wait for it ...common sense. Either ways, it does not matter, to me the idea is original as I never read about it before. I know that does not make it an original idea, but that's not the point. For me anyways. Cause I don't judge ideas or people πŸ˜‰.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment