Difficulty | = in Ruby

What is complexity (Big O) for this operation:

my_array |= [new_element]

Is this O(n)because it needs to pass validation of an existing array, if exists new_element?

+4
source share
1 answer

Let me expand on the Wand Maker comment. Take a look at

Source rb_ary_or

static VALUE
rb_ary_or(VALUE ary1, VALUE ary2)
{
    VALUE hash, ary3;
    long i;

    ary2 = to_ary(ary2);
    hash = ary_make_hash(ary1);

    for (i=0; i<RARRAY_LEN(ary2); i++) {
        VALUE elt = RARRAY_AREF(ary2, i);
        if (!st_update(RHASH_TBL_RAW(hash), (st_data_t)elt, ary_hash_orset, (st_data_t)elt)) {
            RB_OBJ_WRITTEN(hash, Qundef, elt);
        }
    }
    ary3 = rb_hash_values(hash);
    ary_recycle_hash(hash);
    return ary3;
}

I would say that the answer to your question is yes (at best - see @cliffordheath comment), "as it seems that O (n1) for ary_make_hash(aryl)and O (n2) for for.

+1
source

Source: https://habr.com/ru/post/1619632/


All Articles