import
java.util.LinkedList;
public
class
ConstantTimeArray {
private
static
final
int
CHUNK_SIZE =
3
;
private
LinkedList<Integer>[] chunks;
private
int
size;
public
ConstantTimeArray()
{
chunks =
new
LinkedList[
1
];
chunks[
0
] =
new
LinkedList<>();
size =
0
;
}
public
void
insert(
int
element)
{
if
(size % CHUNK_SIZE ==
0
)
{
addChunk();
}
int
chunkIndex = size / CHUNK_SIZE;
chunks[chunkIndex].add(element);
size++;
}
public
void
delete(
int
index)
{
if
(index <
0
|| index >= size)
{
throw
new
IndexOutOfBoundsException(
"Index out of bounds"
);
}
int
chunkIndex = index / CHUNK_SIZE;
int
elementIndex = index % CHUNK_SIZE;
chunks[chunkIndex].remove(elementIndex);
size--;
if
(chunks[chunkIndex].isEmpty() && chunks.length >
1
)
{
removeChunk(chunkIndex);
}
}
private
void
addChunk()
{
LinkedList<Integer>[] newChunks =
new
LinkedList[chunks.length +
1
];
System.arraycopy(chunks,
0
, newChunks,
0
, chunks.length);
newChunks[chunks.length] =
new
LinkedList<>();
chunks = newChunks;
}
private
void
removeChunk(
int
index)
{
LinkedList<Integer>[] newChunks =
new
LinkedList[chunks.length -
1
];
System.arraycopy(chunks,
0
, newChunks,
0
, index);
System.arraycopy(chunks, index +
1
, newChunks, index, chunks.length - index -
1
);
chunks = newChunks;
}
public
void
printArray()
{
for
(LinkedList<Integer> chunk : chunks)
{
for
(Integer element : chunk)
{
System.out.print(element +
" "
);
}
}
System.out.println();
}
public
static
void
main(String[] args)
{
ConstantTimeArray constantTimeArray =
new
ConstantTimeArray();
constantTimeArray.insert(
1
);
constantTimeArray.insert(
2
);
constantTimeArray.insert(
3
);
constantTimeArray.insert(
4
);
System.out.print(
"Array after insertion: "
);
constantTimeArray.printArray();
constantTimeArray.delete(
2
);
System.out.print(
"Array after deletion: "
);
constantTimeArray.printArray();
}
}