happywobbuffet's blog

By happywobbuffet, history, 15 months ago, In English

Hello, I was solving this Leetcode problem yesterday.

I'll rewrite the problem statement once again for convenience:

Problem Statement
Examples
Constraints

I would suggest to try solving by your own before reading further.

I came across this nice solution where you first sort the edges, in increasing order of their edge weights.
This is followed by greedily picking edges from smallest to largest and using Disjoint Set/Union Find to keep count of connected components so far.

While reading through the solution, I came up with an idea that works in reverse:

  • Build the entire graph using the edge information. Initially it is guaranteed to be 1 connected component.

  • Sort the edges in decreasing order of their edge weights (large to small).

  • Greedily remove the edges (largest to smallest) and for every edge removed edge, check if connected components reaches upto $$$k$$$ or not.

The last step "kind of" resembles the operation that has the opposite effect than what the Disjoint Set/Union Find Data Structure does. You perform the opposite of Union and then have to check if the components are disconnected or not.

This is probably a harder way to approach this problem, but I wanted to give it a try for better understanding.

  • How do I approach this if I wanted to follow the steps that I wrote?.
  • Is there a way to solve this problem efficiently?
  • Is there a data structure that is able to calculate connected components and can support edge deletions for given constraints?.

Wobbuffet

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

By happywobbuffet, history, 16 months ago, In English

Hello! I was solving this Leetcode problem yesterday.

I'll rewrite the problem statement once again for convenience

Problem Statement
Examples
Constraints

I would suggest you to solve (in your head or code) this before going further

My Submission (C++)

Now, lets say I have $$$q$$$ Queries of Type:

  • $$$1$$$ $$$L$$$ $$$R$$$ $$$k$$$ where-
  • $$$L$$$ and $$$R$$$ represent the left and rite endpoints of a subarray in $$$nums$$$ inclusive.
  • $$$k$$$ represents the number of operations that can be used to make the entire subarray equal.

For every query, we need to return $$$true$$$ or $$$false$$$ if we are able to make the entire subarray equal.

Here are my observations and approach:

O(n + qlogn) Approach

Not completely positive of my approach so would like to hear any corrections, improvements or suggestions.

So far, we've only seen static/immutable arrays. Lets say I also have a query of Type 2, where

  • $$$2$$$ $$$p$$$ : nums[p] *= -1. (flipping the value at index $$$p$$$).

In this case, how do i device an efficient solution when considering queries of both types? Any Ideas?

Wobbuffet

Full text and comments »

  • Vote: I like it
  • +15
  • Vote: I do not like it