Purgatory is a place where souls become perfected. Since God is perfect, souls should be in a clean state before being physically with God. Luckily, unlike Hell, purgatory is not eternal. The length of time spent in purgatory is individualized, but we will be with God when we’re finished.
Purgatory may be as long as centuries in the case of the more guilty souls, or of those who, being excluded from the Catholic communion, are deprived of the suffrages of the Church, although by the divine mercy they have escaped Hell. If you read about Mary in Fatima, she was asked if an 18 year old girl was in Heaven – Mary said she would be in purgatory until the end of time.
When we’re alive, we can change our fate. By prayers, especially the Rosary, being good, receiving the Eucharist, and helping others we can probably reduce our time in purgatory. It all comes down to how pure our soul is.
At the end of the world, purgatory also ends. God will reconcile His justice in the purification of the last members of humankind. Then God will make His final judgement of Heaven or Hell. This judgement will be permanent.