- Practice
- Data Structures
- Arrays
- Dynamic Array
- Discussions

# Dynamic Array

# Dynamic Array

EdwardSkrod + 20 comments BOOOOM! That was challenging and fun. I wish the language of the challenge were easier to understand. For example, the lastAn should have been named "lastAnswer" so as to be easier to understand. I thought lastAn was some kind of mathematical term. I would recommend the person responsible for making these challenges read "Clean Code" by Uncle Bob Martin!

bcrestel + 4 comments I completely agree, the wording of the question is terrible. I thought 'lastans' would be assigned the value of 'size'.... Your comment put me back on the right track. Thanks.

triethuynh + 0 comments Agree the wording is not goode enough. I was not quite understand his explaination why he came up to the output initially. Got it and solved the problemm finally. Thanks.

[deleted] + 4 comments Agreed, very confusing wording of the question. For me, the use of curly braces in the example made me think, wait, should seqList be a set? But he said it was a list? Does the word sequence suggest it should be ordered? I guess this question reflects real life, when the client cannot express accurately what they want!

neeraj85vns + 1 comment completely agree.. question is not explained well enough to write code..

aadivartak + 0 comments yeah I too agree to the fact.It became cryptic for me

christine_e_hill + 2 comments Also, they say "size", which is non-specific, when they mean "length". Size could be size in memory.

jonjanelle1 + 0 comments Agreed that the wording was a bit odd.

The usage of "size" instead of length is consistent the Java list interface, but not so much in general.

tyler_christian2 + 1 comment Just adding a comment because I understood this incorrectly.

*Size*is the y %*length of*seqList[index].So it is the length of the sub-array in the seqList array with an index ( seq ) calcuated from the original XOR ( ( x ^ lastAnswer ) % N ).

Size = y % len( seqList[seq] )

Patje + 2 comments Thank you! Thank you! After banging my head on the wall for an hour trying to understand their modulus statement, this cleared it up. Such a poorly written set of instructions.

rebelgiri + 1 comment Took an hour on understand. very confusing problem

I think you guys interpreted problem wrongly for query type 2

- Determine sequence number using ( ( x ^ lastAnswer ) % N ).
- ( y % size ) tell the index in an sequence. we need assign value at that index in the sequence(Step 1) to lastAnswer.

Hope its clear now :)

Guptarajat1996 + 0 comments what are the values of x and y ?

abhiemin + 2 comments import java.io.

*; import java.util.*;public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc = new Scanner(System.in); int N= sc.nextInt(); int q=sc.nextInt(); int lastAnswer=0; int x=1; int a[] [] = new int[q][3]; List> seqList = new ArrayList>(); for(int i=0;i

`} x=(a[i][1]^lastAnswer%N); if(a[i][0]==1) { seqList.add(new ArrayList<Integer>()); seqList.get(x).add(a[i][2]); } else { int s = seqList.get(x).size() - 1; lastAnswer =seqList.get(x).get(s); if(lastAnswer!=0) System.out.println(lastAnswer); } } } } what is wrong with this code as it is giving only one positive test case?????`

fezett + 0 comments Why don't you print lastAnswer when it's 0?

francescq + 0 comments I have the same behaviour in javascript. My success test is the 10th one.

The problem is seq calculation returns a value much bigger than N, the actual length of seqList.

The solution is to add the paranthesis on xor calculation ( a ^ b) % c

saurabhyacky + 1 comment There are 2 queries , when to use which query?Like in the example they are executing 3 type 1 query and then type 2. When to switch from 1 to 2?

rantudas2480 + 0 comments I had the same doubt. The query formats are: Query: 1 x y(for query 1) & Query: 2 x y(for query 2).

amscopub_forum + 0 comments No in real life, you ask the client clarifying questions. If you build using unclear requirements, you will fail.

cook_tylerj + 0 comments I found that the example at the bottom contradicted what the explanation of the different queries did. They actually detail 2 different operations.

xingru_deng + 0 comments true. I find it unnecessarily hard to understand. The example is organized in a bad and confusing way.

rahulshetty96 + 7 comments import java.io.

*; import java.util.*;public class Solution {

`public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int q = sc.nextInt(); int inc=0,inb=0; int last = 0,x; int a[][] = new int[q][3]; int b[] = new int[100000]; int c[] = new int[100000]; for(int i = 0; i<q ; i++) { for(int j=0;j<3;j++) a[i][j] = sc.nextInt(); x = ((a[i][1]^last)%n); //sequence s1 or s0 if(a[i][0] == 1) // query 1 or 0 { if(x == 0) b[inb++] = a[i][2]; else c[inc++] = a[i][2]; } else{ if(x == 0) last = b[a[i][2]%(inb)]; else last = c[a[i][2]%(inc)]; System.out.println(last); } } }`

}

WOULD ANYONE MIND HELPING ME TO FIND WHATS WRONG WITH THIS PROGRAM?

Murli0802 + 1 comment n is number of sequences so ther might possible more then 2 sequences. In that case you need more array like b[],c[].Max possible size of these arrays are q so there you can also save some memory.

rahulshetty96 + 1 comment Thanks a lot friend!I got my mistake.

swaroophople + 1 comment I have the same problem can you explain??

Murli0802 + 1 comment n = number of sequence lastAns=0 q = number of query sequences S0={} S1={} S2={} . . . Sn={}

for queries type (1) 1 x y index of sequence id = (x^lastAns)%n append y in Si-th sequence

(2) 2 x y index of sequence id = (x^lastAns)%n lastAns = valueAt(y%(size of Si-th sequence)) and pint lastAns

after every query value of lastAns will be updated according to query type.

anmolnarang4210 + 2 comments what is y and x

Murli0802 + 2 comments y and x are integer inputs (given in question)

ankit_1310029 + 3 comments what is the size of every sequence??

according to me it must be n, but i'm guessing that size of each sequence should be exactly the amount of elements that are present at that moment.

cemelo + 0 comments Yeah. That sentence has terrible phrasing.

ankit_1310029 + 0 comments [deleted]

muntaqeem + 6 comments watch each input line after the first one.

1 0 5

this means, query type 1, x is 0 and y is 5

2suprit + 0 comments Thank you so much, understood this now

undefitied + 0 comments Thanks! It was unclear.

Gaurav_B + 0 comments Thank You So much. Really it was unclear.

Aliya_I + 0 comments oh, without your explanation I've could not figure it out. Thank you!

wasitshafi + 0 comments tnks bro.... i was missing that....

anji_praji + 0 comments Thanks a lot! the problem statement is clear now.

vincent_g + 0 comments [deleted]darkcode + 1 comment Use ArrayList,it will be easier

tiger_1 + 2 comments how to create N number of arraylist dynamically ??

steffen_vulpius + 1 comment ArrayList[] sequenceArray=new ArrayList[length]; for (int j = 0; j <length; j++) { sequenceArray[j]=new ArrayList<Integer>(); }

where length is the first int read from the input.

codertoaster + 0 comments Or you can just create and ArrayList of ArrayLists.

ArrayList> arr=new ArrayList<>();

each element i in the list arr will be another ArrayList.

aparnamsh29 + 2 comments To avoid errors such as "Unsafe operations",Use the following:-

ArrayList<ArrayList<Integer>> b=new ArrayList<ArrayList<Integer>>(n); for(int i=0;i<n;i++) b.add(new ArrayList<Integer>());

And to later on perform the operations, use expressions like:

int t=(a[i][1]^last)%n; b.get(t).add(a[i][2]);

serpentsmiles + 1 comment Many, many users have repeatedly asked that others not post their code in the discussions. If you wish help with your code, simply say so, and if another user responds yes, then send them a private message. Please.

WittyNotes + 1 comment Is this really true? I've never seen others comment on this, and it's seems to be a function of the discussion board to post your (working) result and compare to others' solutions.

AGRN96 + 0 comments I find it much better to just submit your code, then copy the link and posting it on here. It seems to be a way to deter people from just copying the code and not learning anything. The submission link method requires them to forgo any points if they have not completed the problem.

rwan7727 + 10 comments In c++:

`int n,q; cin >> n >> q; vector <vector <int> > s(n,vector <int> ()); int lastAnswer=0; for (int i=0;i<q;i++) { int t,x,y; cin >> t >> x >> y; if (t==1) { s[(x^lastAnswer)%n].push_back(y); } else { lastAnswer=s[(x^lastAnswer)%n][y%s[(x^lastAnswer)%n].size()]; cout << lastAnswer << endl; } }`

bhavgothadiya + 2 comments Here why vector > s(n,vector ());

bhavgothadiya + 0 comments what is used here vector>

MarkMile + 0 comments [deleted]

bhavgothadiya + 0 comments what is T,X,y Here

amorthyo + 0 comments Why did you do lastAnswer=s[(x^lastAnswer)%n][y%s[(x^lastAnswer)%n].size()]; in the column sec for s?

josepaez_2 + 0 comments great approach!

aryabharat + 1 comment we can make it a bit more simple by replacing vector decl. by

vector <int> s[n];

abhaykuma + 0 comments what will that do ? will it declare 2d vector of n rows ?

thethanh92 + 0 comments [deleted]rohanshenoy96 + 5 comments I wrote this and i am getting Run time error. ALmost same code. Can anyone tell me why this isn't working.

#!/bin/python3 import math import os import random import re import sys # Complete the dynamicArray function below. def dynamicArray(n, queries): lastNumber = 0 seqList=[]; for i in range(n): seqList.append([]) res = []; for k, x, y in queries: index = (x^lastNumber)%n if k==1: seqList[index].append(y) print(seqList) else: size = len(seqList[index]) print(seqList) print(size) lastNumber = seqList[index][y%size] print(lastNumber) res.append(lastNumber) return res if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nq = input().rstrip().split() n = int(nq[0]) q = int(nq[1]) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) result = dynamicArray(n, queries) fptr.write('\n'.join(map(str, result))) fptr.write('\n') fptr.close()

laurent_philipp1 + 1 comment Hi ! Just remove your "print" instructions because they perturb the output...

Edit: Why minus votes? Could someone explain?

vivekgangwar02 + 0 comments Bro youre correct, those who downvoted thoughts that adding print in between makes no negative effect on grading.

heyifuwhu + 1 comment I have a small problem: when we generate the dynamic array, i used seqList= [[]] * n instead of your approach, but we i used seqList.append(y), every list in seqList add the element of y. Do you know why it happened like this?

Thanks verymuch

deeprob + 2 comments Use [[] for i in range(n)] instead.

heyifuwhu + 0 comments thanks dude!!

abhisheksinghal + 1 comment Can you please explain why seqList= [[]*n] * n is not working

vivekgangwar02 + 0 comments becuase all the empty sequences youre creating referring to the same object, they all will simultaneously when you make inplace changes to one of the "[]".

ramofficial + 0 comments lastNumber=seqList[index][y%len(seqList[index])]

abhilash04sharm1 + 0 comments *It's XOR operation not Addition.*def dynamicArray(n, queries): lastAnswer = 0 answerList = [] seqLists = [[] for i in range(n)] for i in range(len(queries)): query_type = queries[i][0] x = queries[i][1] y = queries[i][2] if query_type == 1: seq = (x^lastAnswer) % n seqLists[seq].append(y) else: seq = (x^lastAnswer) % n size = len(seqLists[seq]) index = y % size lastAnswer = seqLists[seq][index] answerList.append(lastAnswer) return answerList

nishkarsh_19180 + 0 comments this is the solution in python

def dynamicArray(n, queries): # Write your code here la=0 a=[] for i in range(n): a.append([]) for i in queries: t=(i[1]^la)%n if i[0]==1: a[t].append(i[2]) if i[0]==2: la=a[t][i[2]%len(a[t])] print(la)

first_multiple_input = input().rstrip().split()

n = int(first_multiple_input[0])

q = int(first_multiple_input[1])

queries = []

for _ in range(q): queries.append(list(map(int, input().rstrip().split())))

dynamicArray(n, queries)

hainam2511 + 0 comments vector<vector<long>> l; for(int i = 0; i < n; i++) l.push_back( *(new vector<long>()) );

You can also do this to initiate the 2D vector

chhayaprakashj + 0 comments why did you use y%s[(x^lastAnswer)%n].size()? in here: -

lastAnswer=s[(x^lastAnswer)%n][y%s[(x^lastAnswer)%n].size()];

cause, acc to que, it should be just this much: -

lastAnswer=s[(x^lastAnswer)%n][y];

chhayaprakashj + 1 comment I also had used vector only but, i am getting segementation fault though, i dont know what is wrong!?

vector>s(n);

`vector<int>m; int lastAns=0; for(int i=0;i<queries.size();i++){ if(queries[i][0]==1){ int re=(queries[i][1]^lastAns)%n; s[re].push_back(queries[i][2]); } else{ int re=(queries[i][1]^lastAns)%n; lastAns=s[re][queries[i][2]]; m.push_back(lastAns); } }`

Vikas_Gautam123 + 1 comment Bro your code passes only sample test case . Other test cases gives segmentation fault.

keshavojha98 + 0 comments [deleted]

raghuchahar007 + 0 comments [deleted]nikhilsai_v + 0 comments it works only for two sequences if there are more than 2 sequences then error

SuperGogeta + 1 comment Funny thing is it's a simple piece of code, just 11 lines in python, shame the question is so poorly framed.

knightofbaghdad + 0 comments [deleted]

Superleroy + 2 comments After reading the description several times, trying to map the output to the input, then reading the comments, reading the description again, taking a ten minute break, reading the description again and only after that realizing what the types of query actually means, I have to agree that it was fun too solve. Seriously is there any way to obscure the intention any more? The description is way to hard for the work that has to be done.

cal_pang123 + 1 comment Agreed - I read the question start to finish twice and still don't completely understand what the question is asking.

Alphonso + 1 comment When you first read the question you look over at the difficulty level and wonder if "Easy" is relative to a genius. The person who wrote this question definitely needs to rewrite it so it's more clear.

thedurphy + 0 comments No, the sign of a genius is to be able to explain a subject matter to a child. This guy couldn't explain to me how to work a faucet if he wanted to.

thinhpng + 0 comments Boy, I had no clue what he was asking about. I did not understand what the problem is.

techniker + 0 comments So true. The question was really abstruse. Kind of infuriated me.

manisha_9801 + 0 comments can u pls explain me this question

pritz007 + 0 comments Agreed! Problem discription is way too confusing.

meghanareddy500 + 0 comments can u please explain the question?

juanjoalbo + 0 comments Hard to read, it made me want to avoid that challenge.

lucyluo88 + 0 comments I completely agree, the wording of the question is terrible.

Luane + 0 comments The style of writing used was very much the kind we find in technical books or some textbooks. It is closer to "mathematical language".

limpingandroid + 0 comments 3 years later, and it's still worded in a confusing way. Also, the mathematics appear to use non-standard symbols.

The example gives (1 XOR 7) % 2 = 3. So 1 XOR 7 is 6, but 6 mod 2 gives 0. So apparently they mean integer division when using the % sign??? Who does that??

Edit: Oops, never mind. Re-read it once again, and they do go with 6 mod 2 = 0. But the zero is then used as an index into array1 (3,5), and LastAnswer is set to that. That's where the 3 comes from. Okay, I think I understand it well enough to start programming finally.

Luane + 0 comments I am still wondering if the difficulty I found to understand the challenge was because I need to study more or was because the question was made in a confusing way?

Kanahaiya + 0 comments hi,

I have uploaded a video tutorial on the same.

I hope this comment will help you to understand the problem.

https://www.hackerrank.com/challenges/dynamic-array/forum/comments/591510

fakhruddin_ezzey + 1 comment Hello, I'm Fakhruddin. I am new to HackerRank. Sorry for this silly question but I can not understand this specific question at all. If you could please help me understand what the problem wants to convey. It would be really great.

Kanahaiya + 1 comment hi,

I hope this comment will help you to understand the problem.

https://www.hackerrank.com/challenges/dynamic-array/forum/comments/591510

harisha_ven + 0 comments agree, challenge should invoke logical thought process in our mind not lost in understanding the english statments

harall09 + 0 comments [deleted]CodeTrafficker + 0 comments The description of what they want is almost incomprehensible.

sekhar_samala + 1 comment Question is so confusing. Cloud you please re-frame question?

jensbodal + 3 comments You just need to break it down into each part.

There is a dynamic array of sequences.

There are two types of queries:

one adds an element to a sequence at a calculated index

two finds the sequence at a calculated index and prints the value at the calculated subindex.

Sammieo + 2 comments Thank you for the simplification. Can I ask what, precisely, you mean by a 'calculated index' though?

jensbodal + 13 comments The calculated index is definied in the two bullet points:

`x`

`y`

: Insert`y`

at the end of the`((x XOR lastans) mod N)`

th sequence`x y`

: Print the value of the`(y mod size)`

th element of the`((x XOR lastans) mod N)`

th sequence. Here,**size**denotes the size of the related sequence. Then, assign this integer to**lastans**.

So given 2 squences (

`N=2`

),`lastans=0`

and`1 0 5 | {type = 1, x = 0, y = 5}`

you would apply operation**#1**to`0`

and`5`

: You would insert 5 at the end of the squence at the calculated index of`((0^0)%2)`

Think of it like a hashmap with buckets: the sequences are buckets, and you are inserting a new collision at the end of the bucket's linked list.

enricotalbot + 0 comments Thanks jensbodal, the hardest part of it was deciphering the extremly poorly worded question/explanation.

shoaibahmed9922 + 0 comments thank You very much " jensbodal "...

namanrocks94 + 1 comment `for(int i=0; i<Q;i++) { long int k=A[i][0]; if(k==1) { long int x=A[i][1]; t=((x^lastAns)%N); list[t][a[t]]=A[i][2]; a[t]++;} else{ long int x=A[i][1]; t=((x^lastAns)%N); long int y=A[i][2]; long int size= y % a[t]; lastAns=list[t][size]; cout<<lastAns<<endl; } } is the logic right here ?`

jlokhande46 + 1 comment no its wrong u have to place the element right after its first one

brajeshsingh + 0 comments vector> v(n); vector result; int lastans = 0; for (int i = 0; i < queries.size(); i++) { if (queries[i][0] == 1) { int seq = (queries[i][1] ^ lastans) % n; v[seq].push_back(queries[i][2]);

`} else { int seq = (queries[i][1] ^ lastans) % n; int ind = queries[i][2] % v[seq].size(); lastans = v[seq][ind]; // cout << "last anser" << lastans << '\n'; result.push_back(lastans); } } return result;`

Priten + 0 comments Thank you for the clarification!

zainul118 + 0 comments Cheers mate..thanks for this explanation... I was going mad understanding the problem statement

786lokesh + 0 comments [deleted]anukritinigam02 + 0 comments thank you so much so for the description

caglaror + 0 comments Without your explainations i couldn't solve. Thank you @jensbodal.

UmkaFrom + 0 comments GOD BLESS YOU, seriously, I read the description and the example so many times and could not figure out where the author gets values for x and y... Such a simple problem if you word it right

teja2213 + 0 comments the inputs are 1 x y. Unfortunately, I am reading it as 1xy(1 multiplied with y).

nawnaw011222 + 0 comments Many thanks "jensbodal"! Without your explanations I coud not able solve the problem.

ddebnath_32 + 0 comments But in question word "append" is used for query 1.

h276692580 + 1 comment Have a confuse about task.

Q1: 1 x y

Find the sequence seqList, seq , at index ((x xor lasAns) % N)in seqList.

what is x, what is y? x, y not confirm, how we can get the index?

triethuynh + 0 comments See post from "jensbodal" (6 months ago) - he explained x, y, etc.

wasitshafi + 0 comments tnks @jensbodal

pokedev8 + 0 comments Apologies for any offence caused to the author/writer of the quiz, it's just, I would be really grateful if someone could help me decipher what the question is asking for?

I've read the questions about 5 times, and am struggling to understand what it is that is needed to be done?

(I'll keep re-reading in the meantime, but if someone could help in the meantime that would be grand :( )

lmahanand + 0 comments Hackerrank,

Please have readable question libraries. You questions very poorly written. It needs more effort in undertanding the questions than solving the questions.

Please improve the question descriptions.

kprateek88 + 1 comment This is a simple "do as you are told" thing, with a direct straightforward implementation and no algorithmic cleverness needed. I wonder why it is marked "difficult".

dawguy + 3 comments Dynamicly increasing the size of the array in for query (1) might be why its marked as difficult.

[edit] Although if you in Java if you use an ArrayList then it does seem like a very straight forward problem. If you understood the question and could walk through the example on paper you can implement a solution.

jakezorx + 1 comment Yeah, they should perhaps limit this problem to something like C++ or C, without all the goold ol' memory errors its perhaps a bit too easy.

willybarro + 0 comments C++ has the vector container that works pretty much like Java's ArrayList, so it'd be as easy as it was for you in Java. And I agree with you that it should be limited to C or some language that don't have builtin dynamic array types. The biggest difficulty in this challenge is interpreting the text :-/.

thricefall + 0 comments Why do we have to dynamically increase the size of the array for query 1? Something MOD n will always return a value less than n.

vaschetan + 0 comments [deleted]

Sort 1145 Discussions, By:

Please Login in order to post a comment