graphs – Why did Hopcroft and Karp write $M_0, M_1, M_2, cdots, M_i, cdots$? (Hopcroft – Karp Algorithm)

I am reading “An $n^{frac{5}{2}}$ Algorithm for Maximum Matchings in Bipartite Graphs” by Hopcroft and Karp.

Please see the image below.

Let $s$ be the cardinality of a maximum matching.
I think any of $M_0, M_1, M_2, cdots, M_s$ is a matching and $M_s$ is a maximum matching.
So, I think $P_s$ doesn’t exist.
But the authors wrote $M_0, M_1, M_2, cdots, M_i, cdots$ and $|P_0|, |P_1|, cdots, |P_i|, cdots$.


Maybe I am confused.
enter image description here

algorithm – HackerRank Apples(Python) – Code Review Stack Exchange

There are M Women sitting on the chair in a row. Every woman has a number assigned to it.

Person A is distributing the apples to those women with following conditions.

Each woman has at least one apple

An woman with higher number than neighbour get more apples than that neighbour.

What number of minimum apples Person A should have ?

Input Format

First line is an array of intergers


Each integer value < 50
Number of intergers in array < 10
Output Format

An integer

Sample Input 0
(11, 1, 34)

Sample Output 0

Explanation 0

Person A can give 2 apples to the first, 1 apple to the second and 2 apples to the third woman. Because it satisfies the given 2 conditions. i.e. First woman has number 11 assigned to her and Second woman has number 1, because second woman has low number than first woman minimum number of apples distribution is 2 apples to first woman and 1 apple to second woman, similarly for 3rd woman, she will get 1 apple(minimum) extra from second woman.

Sample Input 1

(1, 2, 2)

Sample Output 1

Explanation 1
Person A can give 1 apple to the first, 2 apple to the second and 1 apple to the third woman. Because it satisfies the given 2 conditions. i.e. First woman has number 1 assigned to her and Second woman has number 2, because second woman has higher number than first woman minimum number of apples distribution is 1 apple to first woman and 2 apples to second woman, similarly for 3rd woman, she will get 1 apple less than second woman because her number is not higher that the second woman.

Source code:

if __name__ == '__main__':

     temp = input().strip()

     temp = temp(1:-1)

     temp = ''.join(temp).split(',')

row = (int(i) for i in temp)

min = 0

min += len(row)

for i in range(0,len(row)):

    if i ==0:

         if row(i) > row(i+1):

              min += 1

    elif i == len(row)-1:

         if row(i) > row(i-1):

              min += 1

    elif row(i)>row(i-1) and row(i)>=row(i+1):

         min += 1

I can pass the test case but not the hidden case?
Please help me debug it or suggest a new appproach

javascript – Heaviest Stone algorithm time complexity

I implemented the heaviest stone algorithm, but I am not sure about its time complexity. I’m doing sort which is O(nlogn), but it’ inside a while loop.


We have a collection of stones, each stone has a positive integer weight.

Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:

If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)


Input: (2,7,4,1,8,1)
Output: 1
We combine 7 and 8 to get 1 so the array converts to (2,4,1,1,1) then,
we combine 2 and 4 to get 2 so the array converts to (2,1,1,1) then,
we combine 2 and 1 to get 1 so the array converts to (1,1,1) then,
we combine 1 and 1 to get 0 so the array converts to (1) then that's the value of last stone.

My solution:

var lastStoneWeight = function(stones) {
    if(!stones || stones.length === 0)  return 0;
    if(stones.length === 1) return stones(0);
    stones.sort((a,b) => b-a);
    while(stones.length > 1) {
        const x = stones(0);
        const y = stones(1);
        stones.splice(0, 2);
        if(x !== y) {
            if(stones.length === 1) return stones(0);
            stones.sort((a,b) => b-a);
    return stones.length > 0 ? stones(0) : 0;

By the way, is there a way to have a better performance? Maybe not sorting?


algorithm – 8 Puzzle problem using BFS in python

i want to apply 8 puzzle problem in python using BFS algorithm in simplest way. please somebody help me.
i just write the main class but i cant go further.

class Board(object):
def __init__(self, initial_values=(), dimensions=(3,3)):
    rows, columns = dimensions
    assert len(initial_values) == rows * columns

    self._values = tuple(initial_values)
    self._rows = rows
    self._columns = columns

modular arithmetic – Algorithm to find slope of line with a modulus

Say I have some data which represents a single line, and I want to determine its approximate slope. This data has a known minimum and maximum on the y-axis. When the line crosses the maximum, it re-emerges at the minimum, or vice versa, so there appear to be many parallel lines in the data. Clearly, the feasibility of this is dependent on the sampling rate and the amount of noise in the data. Also, a slope too steep will put the apparent parallel lines too close to each other such that they’d become impossible to distinguish. So, we’ll assume that the sampling rate, noise, and slope are all within reasonable limits. Is there a particularly elegant way to approach this problem?

algorithm – A star in C++ path tracing issue

I am implementing the A* algorithm on a 2D grid of nodes (squares). I am unable to trace back the path from the end node once the path is solved. I think that I am not linking the nodes correctly.

If someone would have 5 mins to check my code and provide the feedback why it doesn’t works & how to improve it I would be thankful !

Program description:

I am generating a square 2D grid of n x n size. I represent the source by ‘*’ and target as ‘x’. Output looks as per below if the path is found. However, I can’t trace the path from the target to the source by linking my nodes.

enter image description here

#include <iostream>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include <unistd.h> 

using namespace std;

typedef pair<int, int> Pair;

class Node


/*Cost variables */

int h;
int g;
int f;

/*(x,y) position of a node*/

Pair position;

/*Pointer to the parent of a gieven node.*/

Node *parent;

bool operator== (const Node &node);

bool Node::operator== (const Node &node)
    return (node.position.first  == this->position.first &&
        node.position.second == this->position.second);

class AStar

    /*obstacle density*/
int density;

/*size of the grid row, col*/
int       x;
int       y;

/*initial position row, col*/
int     x_0;
int     y_0;

/*final position row, col*/
int x_f;
int y_f;

/*Path grid*/
char **grid;

/*Initialize & declare a 2D moving array

traversal direction | traversal cost
north           10
south           10
east            10
west            10
north_east      14
south_east      14
north_west      14
south_west      14 */

int move(8)(2) =
        {{1 ,   0},         
        {-1,    0}, 
        {0,     1}, 
        {0,    -1},
        {1,     1},
        {-1,    1},
        {1, -   1},
        {-1,    -1} };

    AStar(int x_0, int y_0, int x_f, int y_f, int density, int x, int y);

    void printGrid();
    void BeginPathSearch();
    void tracePath(Node *node);
    void costF(Node new_node, Node curr_node);

    bool isNotMovable(Pair pos);
    bool isOnList(Node node, vector<Node> list);

    int costH(Pair pos);
    int costG(Node node, Pair pos);

/*  Constructor for AStar class. Initialize the variables
    and create the 2D grid (path) with pseudo-random
    obstacles.                      */

AStar::AStar(int x_0, int y_0, int x_f, int y_f, int density = 2, int x = 10, int y = 10)
    int i;
    int j;

    this->x = x;
    this->y = y;

    this->x_0 = x_0;
    this->y_0 = y_0;

    this->x_f = x_f;
    this->y_f = y_f;

    this->density = density;

    grid = new char*(x);

    srand (time(NULL));
    for (i = 0; i < y; i++)
        grid(i) = new char(y);
        for (j  = 0; j < x; j++)
            if (int (rand() % y) < density)
                grid(i)(j) =  'o'; //obstacle
                grid(i)(j) =  '.'; //walkable path
    grid(x_0)(y_0)  = '*'; //start
    grid(x_f)(y_f)  = 'x'; //finish

    delete *grid;

void AStar::printGrid()
    int i;
    int j;

    for (i = 0; i < y; i++)
        for (j = 0; j < x; j++)
            cout << grid(i)(j);
        cout << endl;

Calculate the cost from the current node
to the each of its surrounding 8 squares.
Count horizontal or vertical distance as
10 points.
Count diagonal distance as 14 points.
int AStar::costG(Node node, Pair pos)
    if ( abs(node.position.first - pos.first) == 1 && abs(node.position.second - pos.second) == 1)
        return 14;
        return 10;

Calculate the distance from a given square to
the end square using the Manhattan method.
int AStar::costH(Pair pos)
    return abs(pos.first - x_f) + abs(pos.second - y_f);

/*Check if a node is on a list */
bool AStar::isOnList(Node node, vector<Node> list)
    int i;

    for (i = 0; i < list.size(); i++)
        if (node == list(i))
            return true;
    return false;

/*Trace path from the end node.
    Isn't working! */

void AStar::tracePath(Node *node)
    Node  *p = node;
    while(p != nullptr)
        cout << "(" << p->position.first << "," << p->position.second << ")" << endl;
        p = p->parent;

/*Calculate the total cost as the sum of two
costs. */
void AStar::costF(Node new_node, Node curr_node)
    new_node.h = costH(new_node.position);
    new_node.g = costG(new_node, curr_node.position);
    new_node.f = new_node.h + new_node.g;

void AStar::BeginPathSearch()

    int i;
    int pos_x;
    int pos_y;
    int index;
    int curr_pos;

    Node start_node;
    Node curr_node;
    Node end_node;

    Node *new_node;
    Node *tmp_node;

    vector<Node>    open_list;
    vector<Node>    closed_list;

    start_node.position.first  = x_0;
    start_node.position.second = y_0;

    end_node.position.first    = x_f;
    end_node.position.second   = y_f;

    start_node.g =  0;
    start_node.h =  0;
    start_node.f =  0;

    end_node.g =    0;
    end_node.h =    0;
    end_node.f =    0;

start_node.parent = nullptr;
end_node.parent   = nullptr;

    /* Push the starting node on the open list. */

        /* Look for the lowest F cost node on the
        open_list. Name it current node(squre).*/
        index       = 0;
        curr_node   = open_list(0);
        for (i = 0; i < open_list.size(); i++)  
            if (open_list(i).f < curr_node.f)
                index     = i;
                curr_node = open_list(i);
        Remove the current node from the open_list,
        put it on the closed_list.
        open_list.erase(open_list.begin() + index);

        For each of the 8 squares adjacent
        to the current square repeat :
        for (curr_pos = 0; curr_pos < 8; curr_pos++)
            Calculate the distance of a current square
            to each of the 8 adjacent squares,
            i.e. calculate positions on the (x,y) grid 
            pos_x = curr_node.position.first  + move(curr_pos)(0);
            pos_y = curr_node.position.second + move(curr_pos)(1);

            /* If it is not walkable ignore it. */
            if (pos_x < 0 || pos_x > x - 1 || pos_y < 0 || pos_y > y - 1)
            else if (grid(pos_x)(pos_y) == 'o')
            Create a new node and assign its coordinates
            calculated in the previous step 
            new_node = new Node;
            new_node->position.first  = pos_x;
            new_node->position.second = pos_y;
            /* If it is on the closed list ignore it. */
            if (isOnList(*new_node, closed_list))

            /* If it isn’t on the open list, add it  to
            the open list. Make the current square  the
            parent of this square. Record the F, G, and
            H costs of the square.
            else if(!isOnList(*new_node, open_list))
                new_node->parent = &curr_node;

                costF(*new_node, curr_node);

            /*If it is on the open list already, check
            to see if this path to that square is 
            better, using G cost as the measure. A 
            lower G cost means that this is a better 
            path. If so, change the parent of the square
            to the current square, and recalculate the G
            and F scores of the square.*/
                if (new_node->g < curr_node.g)
                    new_node->parent = &curr_node;
                    new_node->g = costG(*new_node, curr_node.position);
                    new_node->f = new_node->g + new_node->h;

        /*Check if the end square is on the closed
        list, if it's the case the path has been
        if (isOnList(end_node, closed_list))
            cout << "Path is found !" << endl;
    cout << "There is no path !" << endl;

int main(int argc, char* argv())
    if (argc < 8)
        cerr << "Usage: " << argv(0) << " x_0, y_0, x_f, y_f, density, x, y" << endl;
        return 1;
    else if (   stoi(argv(1)) >= stoi(argv(6)) || stoi(argv(3)) >= stoi(argv(6)) ||
                stoi(argv(2)) >= stoi(argv(7)) || stoi(argv(4)) >= stoi(argv(7)))
        cerr << "Usage: n(x_0 < x, x_f < x) n(y_0 < y, y_f < y)" << endl;
        return 1;

    AStar path_finding( stoi(argv(1)), stoi(argv(2)),
                stoi(argv(3)), stoi(argv(4)),
                stoi(argv(5)), stoi(argv(6)),
                stoi(argv(7)) );




Boyer-Moore majority vote algorithm second iteration

There’s a problem in one of my textbooks that goes as follows.

You are given the results of a presidential election. Each ballot is presented one by one, and on each ballot the name of a candindate is written(Let’s assume candidates name’s are represented by numbers). Before announcement of the result, the total number of candidates and the number of people who voted, are unknown.All valid ballots are presented on by one as input, and this process repeats 2 times total. We only have 2 simple varibles we can use for the whole process. You have to design an algorithm which can decide if there is a candidate that has gathered the majority of the votes(meaning more than 50%) of the people who voted, or not. If such a candidate exists, print the candidates name otherwise print “blah blah blah”

Now what first got into my mind, is to use the Boyer-Moore majority algorithm and keep updating the majority and the counter variables as soon as the next result comes in. In case i haven’t made that clear, the results aren’t stored in an array or anywhere else. You get informed of one ballot, then you calculate(and this goes on until all the ballots have been used, meaning i don’t have access to any previous information).
Whether this information is stored in array or not, i know i can still run the first iteration of this algorithm to get a “possible” majority result, since the algorithm always produces one. My problem lies in the second iteration.I see the results one more time one by one. How am i supposed to verify if my original result is indeed the majority or not? Is there any other way i can get around it with only 2 variables?

data structures – Algorithm for Estimating Number of Unique Monthly Visitors

Is there a way to estimate the number of unique monthly visitors to a site based on a limited sample of one week of data? I have information about when a given user visited the site. This isn’t as simple as just multiplying the number of unique visitors the first week by 4, due to the hotel problem. If 10 people visit your site the first week and the same people are the only visitors to your site the second, third, and fourth week, the total number of monthly unique visitors to your site is only 10.

I know you can use HLL to estimate the number of unique visitors to a site in O(1) space. I’m wondering if there’s a similar approach to estimate how many unique visitors there will be after a month, preferably that also works in O(1) space.

graphs – Minimum vertex cover algorithm

Consider the following algorithm: given a graph $G$ with $n$ vertices, set up a linear programming problem LP where there is a variable $x_i$ for each vertex $v_i$ of $G$, each variable can take value $geq 0$, for each edge $v_av_b$ of $G$ set the constraint $x_a+x_bgeq 1$. The objective function is $minsumlimits_{1}^{n}{x_i}$.
Find the variable (or one of the variables) $x_i$ that set to $0$ gives the minimum value of the objective function. Add the constraint $x_i=0$ to LP. Repeat until the optimal solution of LP is integer (that is each variable takes value in $left{0; 1right}$).

I am looking for a graph where the vertices associated to the variables that take value $1$ in the final optimal solution of LP are not a minimum vertex cover of $G$ (if it exists).

complexity theory – Provide a polynomial time algorithm that decides whether or not the language recognized by some input DFA consists entirely of palindromes

The most straightforward way is the following:

Let $p(u,v)$ (“p” for palindrome) be a predicate which means “any path from $u$ to $v$ is a palindrome”. We are interested in $p(S, F)$ for each starting state S and each finishing state F. To compute it, we need an auxiliary predicate $c(u,v)$ (“c” for connected): “there exists a pat from state $u$ to state $v$“. $c$ can be computed in $O(n^3)$ time using transitive closure.

Let $E$ be the set of transitions. Let $ell(u,v)$ be the label (symbol) on edge $u to v$. Then:

$$p(u,v) = false, text{if $exists u’, v’: (u,u’), (v’, v) in E, c(u’,v’)=true, ell(u,u’) ne ell(v’,v)$}$$
Simply put, if there is a path $u to u’ leadsto v’ to v$ such that the first and the last symbols don’t match, $p(u,v)$ is false.

If such a path doesn’t exist, we can define $p(u,v)$ recursively:
$$p(u,v) = land_{u’, v’: (u,u’), (v’, v) in E, c(u’,v’)=true} p(u’, v’)$$
I.e. if there is a path $u to u’ leadsto v’ to v$ such that $u’ leadsto v’$ is not a palindrome, then $p(u,v)$ is not a palindrome.

Now, we can write a DFS-like solution. Let $G$ be a graph where vertices are pairs of states and edges are as defined by the second equation:
$$ (u,v) to (u’,v’) iff (u,u’), (v’, v) in E, c(u’,v’)=true $$
Intuitively, an edge leads from a problem to a “subproblem”.

Our starting vertices for DFS are $(S,F)$ for each starting state $S$ and each finishing state $F$. We need to check that none of these vertices reaches a “bad” vertex, where $(u,v)$ is bad if it fails the condition from the first equation, i.e.:
$$exists u’, v’: (u,u’), (v’, v) in E, c(u’,v’)=true, ell(u,u’) ne ell(v’,v)$$
This is a standard use-case for DFS or BFS.