A mentally ill man who has been in and out of psychiatric confinement over the past decade has pleaded guilty to raping a 10-year-old girl he followed into a Minneapolis apartment building.

Ahmed H. Abdi, 35, of Minneapolis, was given a 12-year term Tuesday by Hennepin County District Judge Juan Hoyos on a charge of first-degree criminal sexual conduct in connection with the assault in October 2015.

With credit for time in jail since his arrest, Abdi will serve a little more than seven years in prison and then be placed on supervised release for another 10 years.

"This is a horrendous crime committed against an innocent young girl," County Attorney Mike Freeman said Thursday. "We need to keep Mr. Abdi in prison and off the streets."

Abdi's attorney, Lindsay Siolka, said her client showed "a tremendous amount of remorse at the sentencing ... and he apologized to the girl and her family."

Abdi was found competent to stand trial, and said during sentencing that he was amenable to treatment while incarcerated.

According to court records filed before the rape, Abdi has a long and sometimes violent history in connection with mental illness and is someone who "engages in grossly disturbed behavior … and he poses a substantial likelihood of causing physical harm."

During one hospitalization, the court records continued, he "demonstrated poor sexual boundaries with female hospital staff," attempted to leave without permission, refused to take his medication and engaged in "intense staring at staff and other residents."

On Aug. 6, 2015, roughly nine weeks before the rape, the court ordered Abdi back to the University of Minnesota Medical Center for treatment. A week later, a letter from U Medical Center clinical treatment coordinator Anna Burke to the county attorney's office endorsed Abdi being provisionally discharged again, writing that he "has endorsed readiness for discharge, no longer meets the criteria for inpatient hospitalization and is in agreement with the discharge plan."

On the day of the assault, people outside the Riverside Plaza complex in the 1600 block of S. 4th Street flagged down police after they heard screams from the third-floor hall and saw the girl crying.

According to the criminal complaint, the girl told officers that a man followed her into an elevator, got out at the same time on the third floor and went with her to the east hallway. He then reportedly asked her what her name was and extended his hand. When she shook it, he refused to let go and ordered her not to move. He then raped her, the complaint said.

Relying on the girl's description, police spotted the man on surveillance video entering the elevator with the girl and determined his identity.