I can't figure this interview question.
You have an array of integers. You need to provide another Data structure that will have these functions:
int get(int index)
void set (int index, int value)
void setall(int value)
They all do what you guess they're suppose to do. The limitation is that every function is in O(1).
How can you design it so that setAll will be O(1).
I thought about adding another field to each integer, that will point to an integer that will be changed every time setAll is called. the problem comes when someone call setAll and then set then get.
Edit: I changed the names of the variables so it would be clearer. Also, since you asked, get is suppose to return array[i], set(index, value) suppose to put the value value in array[index].
After setall(index, value)
you should get (get(i) == get(j) == value)
for every i,j in the array.
A grammar is said to be ambiguous if there exists more than one leftmost derivation or more than one rightmost derivative or more than one parse tree for the given input string. If the grammar is not ambiguous then it is called unambiguous.
It is well known that a number of phrase and sentence types in English may give rise to cases of structural ambiguity. The phenomenon is exemplified by the following sentences: The professor's appointment was shocking, I found her an entertaining partner, The chicken is ready to eat, etc.
A data ambiguity (DA) is a case in which two separate pieces of data in a computer system have the same representation. For example, suppose there are two people named Frederick James Smith and Frederick John Smith.
Examples and Observations"I can't tell you how much I enjoyed meeting your husband." "We saw her duck is a paraphrase of We saw her lower her head and of We saw the duck belonging to her, and these last two sentences are not paraphrases of each other. Therefore We saw her duck is ambiguous."
How about storing a "version number" with each variable, i.e.
int globalValue, globalVersion;
int nextVersion;
int[] localValue, localVersion;
int get(int i) {
if (localVersion[i] > globalVersion)
return localValue[i];
else
return globalValue;
}
void set(int i, int value) {
localValue[i] = value;
localVersion[i] = nextVersion++;
}
void setAll(int value) {
globalValue = value;
globalVersion = nextVersion++;
}
Keep a DateTime field ( or simply a counter ) with each element in the array, a setAllValue variable and setAllDateTime variable. With each set, update the DateTime/counter of the element. With SetAll, update the value and DateTime of setAllDateTime.
In get, compare the DateTime of SetAll with DateTime of the element, whichever is newer, return that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With